Only call the function if you click the Parent and not the childrens

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 clicking div botão or clicking on div sub-menu itself using this function: / p>

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

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

    
asked by anonymous 01.06.2016 / 22:44

1 answer

3

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

The event object that is passed to the callback has an important property that is .target , that is, the element where click occurred. Now that's the answer to your question:

When this and e.target are the same the click occurred in .sub-menu and not in descending. You can test this here (see the console): link

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...
    
01.06.2016 / 23:14