Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Close DIV By Clicking Anywhere On Page

I would like to open email-signup when I click on email-signup-link. Then I would like to close it by clicking anywhere on the page except for the box itself, of course.

I have looked around on this site and there are various solutions for this problem but every one I've tried shows and then hides my div instantly. I must be doing something wrong.

This is the HTML:

<a href="#" id="email-signup-link">Sign Up</a>
<div id="email-signup">
    <div id="inner">
        <h2>E-mail Notifications</h2>
        <input class="" type="text" name="description" placeholder="Enter your e-mail address" id="description" />
        <a href="#">Sign Up</a>
    </div>
</div>

This is my Javascript:

$('#email-signup').click(function(){
    e.stopPropagation();
});
$("#email-signup-link").click(function() {
    e.preventDefault();
    $('#email-signup').show();
});
$(document).click(function() {
    $('#email-signup').hide();
});
like image 254
Aaron Salazar Avatar asked Feb 24 '12 21:02

Aaron Salazar


2 Answers

Two things. You don't actually have e defined, so you can't use it. And you need stopPropagation in your other click handler as well:

$('#email-signup').click(function(e){
    e.stopPropagation();
});
$("#email-signup-link").click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    $('#email-signup').show();
});
$(document).click(function() {
    $('#email-signup').hide();
});​

http://jsfiddle.net/Nczpb/

like image 152
James Montagne Avatar answered Oct 24 '22 18:10

James Montagne


$(document).click (function (e) {
    if (e.target != $('#email-signup')[0]) {
        $('#email-signup').hide();
    }
});
like image 24
Alexander Varwijk Avatar answered Oct 24 '22 17:10

Alexander Varwijk