Call function when pressed outside a specific div
I have an html structure like
<div class="abc"> <div id="test"> <label>Name</label> <input type="checkbox"> <label>Name</label> <input type="checkbox"> <label>Name</label> <input type="checkbox"> </div> </div> I want that when you click the div id test button, you can call a specific function. and also no event will be triggered if inside the div id tag when I click the checkboxes , no event should be fired.
Any help would be really appreciated.
+6
9 answers
You can achieve this with the following code (demo: http://jsfiddle.net/CrfCD/ )
$(document).ready(function(){ $(document).click(function(e){ if ($(e.target).is('#test,#test *')) { return; } else { alert("Hi"); //Perform your event operations } }); }); +8
Just use: (demo)
Javascript
$('.abc').click(function(e){ alert('Do anything'); }); $('#test').click(function(e){ e.stopPropagation(); // Do only if anything in #test was clicked }); e.stopPropagation() prevents bubbling events for the next item
+1
Use the Div focus event, as it will be called only once when the div loses focus. Refer to the post Div-onblur Function
+1