Problem with return false in JavaScript

0

I need to develop an accordion menu and am having trouble with the click event. My script:

$(document).ready(function(){
    $('.dropdown').click(
        function(){
            $(this).find("ul").slideToggle();
            return false;
        }
    );
});

SlideToggle calls an unordered list that sits inside an LI element. It works perfectly, but the links in the list stop redirecting. When I click on any of them, slideToggle () simply undoes, the menu returns to the original state and I am not redirected. Where am I going wrong?

    
asked by anonymous 08.06.2014 / 02:57

3 answers

2

The error occurs exactly with return false; , which does not let the event started on the submenu link finish executing.

Add the following code shortly after registering handler to click in the dropdown:

$('.sub-menu a').click(function(e) { e.stopPropagation(); });

By giving stopPropagation in the click of the link, you will prevent the event from propagating up, and there will not block the browsing event.

And by clicking on the link, the user will be redirected to the page.

    
08.06.2014 / 03:30
1

In there is a function called .preventDefault() that " deny "the original event of an tag HTML, this way you can use it so your links do not have their original effect as soon as they are clicked

$(document).ready(function(){
    $('.dropdown').click(
        function(event){
            event.preventDefault();
            $(this).find("ul").slideToggle();
        }
    );
});
    
08.06.2014 / 03:08
0

Let's imagine your HTML looks like this:

<ul>
    <li class="dropdown">
        <a href="">Abrir drop down A</a>
        <ul>
            <li><a href="">Link A 1</a></li>
            <li><a href="">Link A 2</a></li>
        </ul>
    </li>
    <li class="dropdown">
        <a href="">Abrir drop down B</a>
        <ul>
            <li><a href="">Link B 1</a></li>
            <li><a href="">Link B 2</a></li>
        </ul>
    </li>
</ul>

And your script is applying click to the .dropdown element when the correct one is to apply the click to the direct child link of the .dropdown element.

Then your jQuery.click should look like this:

$(document).ready(function(){
    $('.dropdown >a').click(function(){
       $(this).siblings("ul").slideToggle();
       return false;
    });
});
    
08.06.2014 / 16:19