Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide DIV when I click away

I've read many SO answers on this but none of them is quite what I need. I have a div button which when clicked shows a div called #settingswindow. I would like to be able to close it when I click away.

The code below does that but the #settingswindow div also closes when I click on it, which is an undesirable effect.

// settings button
$(document).ready(function(){
  $("#settings").click(function(event){
    event.stopPropagation();
  $("#settingswindow").toggle();
 });});
$(function(){
$(document).click(function(){
    $('#settingswindow').hide();
});
});

Thanks for your help.


2 Answers

Add this line:

$("#settingswindow").click(function(e){
    e.stopPropagation();
});

http://jsfiddle.net/DerekL/N9cbk/

like image 173
Derek 朕會功夫 Avatar answered Jan 01 '26 01:01

Derek 朕會功夫


Create a function for $('#settingswindow').click(), then use event.stopPropagation() http://api.jquery.com/event.stoppropagation/ to stop event bubbling.

like image 41
Gang Su Avatar answered Jan 01 '26 00:01

Gang Su