Simon
Simon

Reputation: 13

How to hide a div if user clicks anywhere but a link and the div itself using jQuery?

Ok, so simple question. I have a link which when clicked shows a div. If the user blurs off that link the div is hidden. This is good, but I don't want the div to be hidden if the user clicks on it. So if the user clicks anywhere other than the link or div itself only then should the div be hidden. Right now my code doesn't do this.

JSFiddle:

http://jsfiddle.net/gTkUG/

jQuery:

$('#myLink').click(function(e) {
    $('#myDiv').show();
    e.preventDefault();
});
$('#myLink').blur(function() {
    $('#myDiv').hide();
});

HTML:

<div style="display:none;width:100px;height:100px;border:1px solid red" id="myDiv"></div>

<a href="" id="myLink">Click Me</a>

So I guess the question is, how to detect blur on two or more events instead of just one?

Upvotes: 0

Views: 1074

Answers (1)

Majid Fouladpour
Majid Fouladpour

Reputation: 30242

$('#myLink, #myDiv').click(function(e) {
    $('#myDiv').show();
    e.preventDefault();
    e.stopPropagation();
});
$(document).click(function() {
    $('#myDiv').hide();
});

http://jsfiddle.net/gTkUG/3/

Upvotes: 2

Related Questions