How To Do An Action Only When There Is No Default In Javascript / Jquery?
I'm asked that a click anywhere in a div does a specific action (say collapse it) unless the click was on a link, a button, etc... Basically, I'd like the reverse of event.preventD
Solution 1:
You just have to make sure the event target
is not 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");
}
});
Solution 2:
Just add this handler to your link:
$("#click_me a,button,input,textarea,video,map,object").click(function(e){
e.stopPropagation();
});
To prevent the event to get to the div (bubble up). It will stop so the link will behave correctly.
See it in action. (click preview)
Solution 3:
Event bubbling
is the keyword here. Bind an event handler to the div and check the event target
to specify 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 for the targets tagName
or nodeType
.
Solution 4:
functiononClick(e){
var gates = "A,INPUT,TEXTAREA,SELECT";
var bound = this;
var isCollapse = function ( node ){
if( node == bound ){ returntrue; }
var re = newRegExp( "\\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 like: <a href="_"><span><strike> a link </strike></span></a>
Post a Comment for "How To Do An Action Only When There Is No Default In Javascript / Jquery?"