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
source share
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
source

Try it,

  $('.abc').click(function(e){ if(e.target.id == 'test') { return false; } }) 
+2
source

You can get the id of the called div and check if it matches the test or not.

 $("body").on("click", function(e) { if(e.target.id != "test") { // do something return false; } else { return false; } }); 
+1
source
 $(document).click(function(e){ if(e.target.id == "test"){ e.preventDefault(); e.stopPropagation(); } else{ //your function call that you want to invoke on clicking anywhere outside of div _test_ } }); 
+1
source
 $(document).click(function(e) { if(e.target.id == 'test') { alert( "Handler for .click() called." ); } }); 

JSFIDDLE DEMO

+1
source

HTML:

 <div id="abc" onclick="getId()"> 

JavaScript:

 function getId() { --Write your function here-- } 
+1
source

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
source

try it

 $(document).click(function(e) { if($(e.target).is("#test")){ e.preventdefault(); e.stopPropogation(); } else{ //call your method } } 
+1
source

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
source

Source: https://habr.com/ru/post/952712/


All Articles