How to do an action only when there is no default value in Javascript / jQuery?

I am asked to click anywhere in the div to do a certain action (say, collapse it), unless the click was on a link, button, etc.

Basically, I need the flip side of event.preventDefault() .

Is there a good and easy way to do this?

I am looking for a general solution here; I would not like to talk a lot about the content of the div.

It might look like this:

 <div id="click_me> <p>Clicking here should do stuff <a href="http://stackoverflow.com">but not here, nor on the following image</a> <a href="/xyz"><img url="/icon.png"/></a> imagine buttons... input areas, ... </p> </div> 

With the following Javascript:

 $("#click_me").click(function(){ if(black_magic) { $("#click_me").toggleClass("collapsed"); } }); 
+3
source share
4 answers

You just need to make sure that the target event is neither a link nor a button.

 $('#click_me').click(function(e) { interactive = 'a, button, input, textarea, video, map, object'; if($(event.target).closest(interactive).length == 0) ) { $("#click_me").toggleClass("collapsed"); } }); 
+4
source

Just add this handler to your link:

 $("#click_me a,button,input,textarea,video,map,object").click(function(e){ e.stopPropagation(); }); 

To prevent an event, go to div (bubble up). It will stop, so the link will behave correctly.

Look in action. (click preview)

+2
source

Event bubbling is the key word here. Bind the event handler to the div and check the event target to indicate what to do.

 $('div.mydivclass').bind('click', function(event){ switch(event.target.id){ case 'id_of_an_anchor':{ alert('anchor was clicked'); break; } case 'id_of_a_span':{ alert('span was clicked'); break; } default: { alert('something else was clicked within me'); } } }); 

Of course, you can even check target tagName or nodeType .

+1
source
 function onClick(e){ var gates = "A,INPUT,TEXTAREA,SELECT"; var bound = this; var isCollapse = function ( node ){ if( node == bound ){ return true; } var re = new RegExp( "\\b" +node.nodeName+ "\\b", "g" ); return re.test( gates ) ? false : isCollapse( node.parentNode ); }; if( isCollapse( event.srcElement || e.target ) ){ alert( "collapse" ) // collapse() } } document.getElementById("click_me").onclick = onClick; 

* fixed * for cases such as: <a href="_"><span><strike> a link </strike></span></a>

0
source

All Articles