Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: selector for an event on an element but not on its children?

I would like to know if this is possible, with a jquery selector, to bind an event on an element but not on its children. Actually, I have two divs one on the other, in absolute position, and I would like to detect the same event on the two divs, but not if the event is happening on a child of the top div (I mean, I would like to detect if the event is on the transparent parts of the top div, as if it was happening on the lower div).

for example, here, #desktop and #apps are one on the other, with the same fixed width and height, and I would like to detect an event on: #desktop, or on #apps, but not on .stuff

HTML

<div id="desktop">

</div>
<div id="apps">
    <div class="stuff">
        test
    </div>
    <div class="stuff">
        test2
    </div>
</div>

JavaScript

$("#desktop, #global:not(its_CHildren?)").mousemove(function (mouse){
    // ...
}

If this is not possible with a selector, I was thinking of doing something like this, which works satisfiyingly:

$("#desktop, #apps").mousemove(function(mouse){
    $("#global stuff").mousemove(function() {
        return false;
    });
    // ...
});
like image 937
Jo Pango Avatar asked Jul 05 '11 18:07

Jo Pango


1 Answers

The handlers are only bound to the parent elements. The issue is that the events bubble up from the descendants, and fire the handler attached to the parent.

You could test the event.target to see if it is the same value as this (the element to which the handler is bound).

$("#desktop, #apps").mousemove(function(e){
     if( e.target === this ) {
        //run your code
     }
});

Example: http://jsfiddle.net/KAJhe/ (open your console to see when the code logs the ID of the hovered element)

Now the code in the if will only fire when you're not moving the mouse over a parent, but not over a descendant element.

like image 53
user113716 Avatar answered Sep 24 '22 17:09

user113716