So I have the following scenario:
Sample text.
Anchor link
Here is a demo (jsfiddle) with a forms and two fields:
<div id="container">
<form>
<div class="field">
<input id="demo" type="text" name="demo" />
</div>
<div class="field">
<input id="demo2" type="text" name="demo2" />
</div>
</form>
</div>
The code looks like this:
$(document).ready(function() {
$('#container').click(function(evt) {
if(this == evt.target) {
console.log('clicked container',evt.target);
$('#demo').focus();
} else {
console.log('clicked child -> ignoring');
}
});
$('.field').click(function(evt) {
if(this == evt.target) {
console.log('clicked field div',evt.target);
$(this).find('input').focus();
} else {
console.log('clicked child -> ignoring');
}
});
});
You can click the container that contains the form to set the focus on the first input field or behind the input field to set the focus into it.
If you click into the field, then the click will be ignored.
The code above works since jQuery assigns the DOM node to this
before calling event handlers, so you can easily check whether the current event was published by the DOM node by checking
this == evt.target
CSS:
#container {
width: 600px;
height: 600px;
background: blue;
}
.field {
background: green;
}
This is what you need: http://api.jquery.com/event.target/ .
Just compare to check if the element was triggered by the element you want or one of its children.
You can stop the clicks from bubbling up from links with an additional handler, like this:
$("#block a").click(function(e) { e.stopPropagation(); });
The the alternative we were discussing in comments:
$("#block").delegate('a', 'click', function(e){ e.stopImmediatePropagation(); })
.click(function() { alert('test'); });
This would prevent any child links from bubbling up (well, not really, but their handlers from executing), but not create a handler for each element, this is done via .stopImmediatePropagation().
You can test which node was clicked with the target property of the event object:
$("#block").click(function(event) {
if(event.target.nodeName != 'A') {
alert('test');
}
});
I suggest to read Event Properties from quirksmode.org.
$("#block").click(function(event) {
if($(event.target).attr('id') == $(this).attr('id'))
{
alert('test');
}
});