Goobi
Goobi

Reputation: 47

Hide a div using jQuery when

I have a list of items, each of which needs to show a div. Click on one, and it shows you a div with tweets in it. I've been able to successfully show the divs with jQuery. Unfortunately, I have no clue how to hide the divs when the user clicks outside of said div. I've tried fiddling around with the .not() selector, but I just can't do it. Here's my code:

$("#twitter-wid").click(function() {
$(".recent_tweets").fadeIn(400);
});

In this case, #twitter-wid is the 'li' item, and .recent_tweets is the div element that I need to show. I want it such that when the user clicks anywhere out of .recent_tweets that it should hide. I've so far tried to add:

$.not('.recent_tweets').click(function() {
$('.recent_tweets').hide();
});

But to no avail. Oh and I'm new to jQuery. Thanks!

EDIT: I wonder how Twitter does it for their little drop-down menu. Click on your username and it drops down a bunch of options. Click anywhere out and it slides up.

Upvotes: 1

Views: 110

Answers (2)

jargalan
jargalan

Reputation: 5184

 $(document).click(function() { //Click anywhere
  $('.recent_tweets').hide();
 });

//ADDED for inside click

$('.recent_tweets').click(function(e){
     e.stopPropagation();
 });

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382616

There is outside event jquery plugin you may want to use:

$(".recent_tweets").bind( "clickoutside", function(event){
  $(this).hide();
});

Upvotes: 2

Related Questions