I need to click on a document to call some function, but the problem is that when I click on some element that want it doesnt react, so the code:
<body>
<div class="some_element">
some element
</div>
</body>
and js:
$(document).click(function(){
//something to happen
})
and now if I click on the div with class="some_element" the document.click event will be called, but I need to call that event ONLY when I click on the document; or it is possible the make this element an exception?
More detailed:
$('#forma').click(function(e){
e.stopPropagation();
$('#assignment_type_list').slideUp();
})
Lets say #forma – its a parent element of those element, so when I click on the page I want to slideUp someElement and:
$('#assignment_type_select, #assignment_type_label').click(function(){
$('#assignment_type_list').slideToggle();
})
this is the elements when they are clicked the other element is toggled, but the problem is that when I click on this elements the $('#forma').click – also executes, because its parent and the e.stopPropagation() – doesn’t help.
All this
stopPropagationstuff is right, though this’ll cause your script to throw errors on older versions of a certain browser. Guess which one? a cross-browser way:However, you wanted to check if the element that was actually clicked, is the one you need. The problem with that is, that the way the event is passed through the DOM. In W3C browsers the event is first passed to the document, and then clambers down to the element that was actually clicked (propagates through the dom).
By contrast IE dispatches its events on the element itself, and then sends it up to the document (except for the
changeevent triggered by select elements… to add insult to injury). What this effectively means is that a click event that is registered in tobodyelement in W3C browsers might be on its way to a checkbox of sorts, or it could be a click inside an empty div.Again, in IE, when a click event reaches the
bodytag, it could have been dispatched too any element on the page. So it may prove useful in your case to google:event delegation, or turn to jQuery’s.delegate()method.Or check the event object to see if the event is allowed to propagate through or not:
The property names neatly show the difference between the bubbling model and the propagating one: in the first case (
srcElement), the event is coming from a source element in the dom. In the W3C propagating model, the event is cought while it’s headed for atargetelement somewhere in the dom.Look at it like a heat-seeking missile (w3c) versus a shower of debris after the target was shot down (IE, always the destructive one, and in this case often to late to respond to the events, and therefore to late to handle them:P)