Marco Dinatsoli
Marco Dinatsoli

Reputation: 10590

jquery check has id always goes to else

This is the jfiddle http://jsfiddle.net/Vp942/1/

I have a div campaignDiv and I want when the user clicks out side of it, i want to hide it.

THis is what I tried

$(document).bind('click', function (e) {
    var $clicked = $(e.target);
    if (!$clicked.parents().has("#campaignDiv")) { $("#campaignDiv").hide(); } else { console.log("asdf");}
});

but for some reason, always the else is executed even when I clicked inside the campaignDiv

could u help please?

Upvotes: 1

Views: 61

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

.has() returns a jQuery object; when used inside an if condition it always evaluates to true even if contains zero elements. And don't confuse yourself that it will return either true or false as same as .hasClass()/.is()

Try,

$(document).bind('click', function (e) {
    var $clicked = $(e.target);
    if (!$clicked.parents().find("#campaignDiv").length) { 
        $("#campaignDiv").hide();
    } else { console.log("asdf");}
}); 

DEMO

Upvotes: 2

TecHunter
TecHunter

Reputation: 6141

I prefer this one, faster IMO:

$(document).bind('click', function (e) {
    var $clicked = $(e.target);
    if (!$clicked.closest('#campaignDiv').length) {
        $("#campaignDiv").hide();
    } else { 
        console.log("asdf");
    }
});

The $.closest function will go through the hierarchy (bottom to top) stopping at the first parent matching the selector.

Your modified JSFiddle

Upvotes: 2

Related Questions