fafa
fafa

Reputation: 107

Why this jQuery selector does not work for me?

I am trying to start an action everytime anything on the webpage else than specific object is clicked (menu "tree horizontal lines" button with class called "navbutton"), like this:

<div class="test">
    <nav id="menu" class="pdng-lr">
        <div class="navbutton">
            <span class="top"></span>
            <span class="middle"></span>
            <span class="bottom"></span>
        </div>
    </nav>
</div>

CSS:

#menu .navbutton
{
    display:none;
}

@media screen and (max-device-aspect-ratio: 1/1) and (orientation: portrait)
{
.pdng-lr
{
    padding:0px;
}

#menu .navbutton
{
    display:block;
    width:25px;
    height:38px;
    margin-top:40px;
    margin-left:calc(100% - 40px);
    border:none;
    cursor:pointer;
}

#menu .navbutton span
{
    display:inline-block;
    float:left;
    min-height:6px;
    width:100%;
    margin:2px 0px;
    background-color:#cccccc;
    -webkit-transition:all 0.15s linear;
    -moz-transition:all 0.15s linear;
    -o-transition:all 0.15s linear;
    transition:all 0.15s linear;
}

#menu .navbutton .top
{
    margin-top:6px;
}
}

I thought this script could work:

jQuery('div:not(".navbutton")').click(function(){
    // just to test if it works
    alert();
});

...but it does not: when I click on the .navbutton it still fire up the action anyway (alert window opens up)!

Can anyone tell me what is wrong with the code or how to make it work?

I try to make it as simple as possible on jFiddle but it still doe snot work even like that, see: https://jsfiddle.net/eygka3cn/3/

Upvotes: 0

Views: 31

Answers (1)

Julien Duris
Julien Duris

Reputation: 89

Your selector is div:not(.navbutton). <div class="test"> triggers the click event, since it's a div without a .navbutton class bound to it. And .test is the parent of .navbutton.

You have some options:

  • add .test, in your not selector
  • make a click to .navbutton to stop propagating the event, as such
jQuery('.navbutton').click(function(e) {
  e.stopPropagation();
})

Complete code: https://jsfiddle.net/0r2u5x1y/

Upvotes: 2

Related Questions