james emanon
james emanon

Reputation: 11807

Why isn't this working - using :not() with an event handler

I seem to have another issue that I am not conquering. Real simple premise. I have a mousedown event, and basically IF one particular element on the page is clicked, I want nothing to happen, else I want hide() some div.

    $(function(){
        $("document :not(#_ignorelement)").mousedown(function(event){
                if($('#_hidethiselement').length){
                    $('#_hidethiselement').hide();
                }
        })
     })

That is not working at all. I also tried the following:

    $(document).not($("#_ignorelement")).mousedown(function(event){

    $(document).not("_ignorelement").mousedown(function(event){

IF I can solve that, curious how I would actually have ":not" encompass the parent div, like so:

$().not("_ignoreelement").parent().closest('div').mousedown(function

Because the element "_ignorelement" is an anchor tag that is in a div. Wonder how I can use the parent div perhaps, instead of the anchor tag.

Anyways, any help would be appreciated.

Upvotes: 1

Views: 64

Answers (2)

stephband
stephband

Reputation: 2643

This should work:

var ignoreNode = jQuery('#_ignorelement')[0];

jQuery(document).on('mousedown', function(e) {
  if (ignoreNode === e.target || jQuery.contains(ignoreNode, e.target)) {
    // If the target is, or is inside the ignoreNode, don't
    // do anything.
    return;
  }

  // Do your hiding handling here 
});

Note that it really is a good idea to cache your jQuery objects so that you're not running selector queries on every event!

Upvotes: 1

FishBasketGordo
FishBasketGordo

Reputation: 23142

document isn't a node that you can select. Try this instead:

$(function(){
    $("body :not(#_ignorelement)").mousedown(function(event){
        if($('#_hidethiselement').length){
            $('#_hidethiselement').hide();
        }
        return false;
    })
 });

Here's a working example

Upvotes: 2

Related Questions