I'm looking for a jquery function doing the following :
- if I click everywhere inside the div (but elements inside this div), the code is executed .
if I click in an html element inside this div , noting happens .
I'm looking for a jquery function doing the following :
if I click in an html element inside this div , noting happens .
The event is lopped through the element, until a element with a click element is found. Solutions:
You need to test if the clicked target is this
. Fiddle here: http://jsfiddle.net/ZBC43/
$('div').on('click', function(e) {
if (e.target !== this) return;
alert('div clicked');
});
You need something like this (i try to find parent div with your class):
<div class='foobar'>
<span>child1</span>
<span>child2</span>
</div>
<span>child3</span>
<script>
$('.foobar').on('click', function(e) {
var testelem = $(e.target);
while (testelem != undefined && !testelem.hasClass('foobar')){
testelem = testelem.parent();
}
if (testelem != undefined && testelem.hasClass('foobar')) {
alert('code');
}
});
</script>
Try this:
$("div").click(function(e) {
if (e.target !== this) return;
alert("inside a div");
});
You can use tagName
dom property to get current target element name.
TagName: Returns the name of the element.
HTML
<div id="myDiv" style='display:inline-block; width:300px;'><span style='display:inline-block;'>Hello Click here</span><br /><span style='display:inline-block;'>Click here</span></div>
Javascript
$(document).ready(function(){
$('#myDiv').click(function (e) {
if (e.target.tagName == "DIV") {
alert('Clicked on Div');
}
else{
alert('Clicked on Inner Element');
}
});
});
OR also use nodeName
property to get current element.
NodeName: Returns the name of the current node as a string.