Only call the function if you click on Parent and not on Childrens

Asked

Viewed 117 times

1

I have the Following div:

<div class="sub-menu">
    <ul>
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>
        <li><a href="#">Link 3</a></li>
        <li><a href="#">Link 4</a></li>
    </ul>
</div>

I have a function in jQuery that shows and hides this menu when I click on div botão, I have two conditions to hide this sub menu, or by clicking on div botão or by clicking on div sub-menu using this function:

  $(".sub-menu").click(function(){
    if(status == 1){
        $('.sub-menu').animate({
            left: '-224px',                     
        }, 300);    
        $('.fade').fadeOut();
        status = 0;
        $('.hamburg').removeClass('open');            
    }    
  });

the variable status checks whether the sub-menu open or closed, the problem is that when I click on li's within the sub-menu he ignores the link and just closes the div sub-menu, how to make it readition normally to the supposed pages by clicking on the links?

1 answer

3


When you use $(".sub-menu").click(function(){ that anonymous function (callback) will be called when an element with the class sub-menu receive an event. What is interesting and useful here is that this callback provides an argument, the event itself and runs with the context pointed to the element. That is, the this within that function is the very element whose .click( was applied.

The event object that is passed to callback has an important property which is the .target, or is the element where the click if it did. Now that’s the answer to your question:

When the this and the e.target are the same click on .sub-menu and not a descendant. You can test this here (see the console): https://jsfiddle.net/pLgL82pk/

So in the code you can have:

$(".sub-menu").click(function(e){
    if (e.target == this){
        // o click deu-se no sub-menu
    } else {
        // o click deu-se num descendente
    }
    // etc...
  • worked perfectly my dear, had no knowledge of it, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.