Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery if clicked?

Tags:

jquery

With the following piece of code... Is it possible to say, if the li was clicked do this if not(user click somewhere else) do that? The code will only make the div disappear if the user clicks something in the list. I need it to disappear if they click anywhere else as well... ?? Thanks!

.bind('blur', function() {
   $('#search_suggestions_list li').click(function() {
       var selectedString = $(this).text();
       $('#search-box').val(selectedString);
       setTimeout("$('#search_suggestions').fadeOut('fast');", 200);
   })
})
like image 723
mike Avatar asked Feb 08 '10 18:02

mike


2 Answers

$(document).click(function(){
   //user clicked anywhere on the page
});

$('#search_suggestions_list li').click(function() {
   //user clicked on the li
   return false;
});

Make sure to return false, otherwise the document click event will be called as well.

like image 112
munch Avatar answered Sep 20 '22 12:09

munch


Handle the click event on the document, and then handle the click event on your li. Inside the click event for the li, use the stopPropogation function to prevent the document (parent) click event from firing...

$(document).click(function() {
  // Clicked outside the LI
});

$('#search_suggestions_list li').click(function(e) {
  var selectedString = $(this).text(); 
  $('#search-box').val(selectedString); 
  setTimeout("$('#search_suggestions').fadeOut('fast');", 200);

  e.stopPropagation(); // Stops document.click from firing
}) 
like image 40
Josh Stodola Avatar answered Sep 20 '22 12:09

Josh Stodola