tags:

views:

35

answers:

4

Here is what I am doing.

I am displaying a box, after click at a link CSS

#toshow { display:none; }

HTML

<a href="#" id="mylink" >Link</a>
<div id="toshow">Here is my content</div>

Jquery

$(document).ready(function() {
     $("#mylink").click(function() { 
         $("#toshow").show();
     });
});

Now I want to catch a event, where the user clicks the mouse, and if the portion the user is clicking is not either the link or the division, then the division should hide again.

How to do this?

A: 

Bind the click even (or mousedown event) to the document object:

$(document).bind('click', hideToShow());
Michael Shimmins
+2  A: 
$(document.body).click(function(e){
   var $box = $('#mylink');
   if(e.target.id !== 'mylink' && !$.contains($box[0], e.target))
      $("#toshow").hide();
});

You need to check for click events which bubbled up to document.body. In that event handler you look for the event target id and compare it with the element you do NOT want to include, plus all elements which are children of that excluded element.

@Starx: (question in the comments) $.contains() checks if a DOM node contains anther node you specify. So

!$.contains($box[0], e.target)

means, if e.target does NOT contain the node $box[0]
see http://api.jquery.com/jQuery.contains/

jAndy
Not `$box.hide()` for any reason?
sje397
@sje397 - absolutely, removing the box would prevent the #mylink click again from showing the box the next time it is clicked.
Sohnee
@sje397, @Sohnee: ups my bad.
jAndy
@jAndy, What does `!$.contains($box[0], e.target)` represent?
Starx
@Starx: answered in my post.
jAndy
@jAndy, I have created a working one.. Review it http://jsfiddle.net/nkHkw/4/
Starx
+1  A: 

Firstly, you should be a bit kinder to users who don't have JavaScript by hiding the content programatically, not via CSS. You could also just make the same link hide the content.

$(document).ready(function() {
    $("#toshow").hide();

    $("#mylink").click(function() { 
        $("#toshow").toggle();
    });
});

If you want to do it as you've suggested with "click away to de-focus" then you need to do this.

$(document).ready( function() {
    $("#toshow").hide();

    $("#mylink").click( function() { 
        $("#toshow").show();
    });

    $("body").click( function () {
        $("#toshow").hide();
    });

    $("#toshow").click( function (e) {
        e.stopPropagation();
        return false;
    });
});

The last bit, where we add a click handler to #toshow is intended to stop the propagation of the click event to the body of the document when you click on that element.

Sohnee
clear and readable. i like it. +1
ljubomir
A: 
giolekva