Reputation: 23576
Say I have:
<div id="name" class="button"></div>
and in a javacript file I define click actions for both class button and id name, something like:
$("#name").click(function(event){
alert("hi");
})
$(".button").click(function(event){
alert("bye");
})
When I click that div, will I get the "hi" alert before the "bye" alert because "hi" appears above "bye"? Or does something else determine what happens first? What if the 2 functions were in different files? Would it then matter which javascript file was included first (appeared closer to the top of the html file)? I assume jQuery has nothing to do with this, right?
Upvotes: 1
Views: 273
Reputation: 55750
You see the 'hi'
alert first because that event was bound first.
So when the events are fired based on the order they are bound to..
Upvotes: 0
Reputation: 50933
You're absolutely right, that it's honestly based on which is bound first. In your case, the "#name"
one is bound first, then the ".button"
, so that's why they are finally executed in that same order. It's not based on which is seen first on the page, but which is bound first. The binding may occur in a function, so it won't happen until the function is called (obviously), but the function may be declared before other bindings - doesn't mean anything, it must be called. Same goes for being in different files. As files are parsed, they are executed. So what I said before applies to this too - as long as the binding executes in the order the things are parsed (from the top of the HTML page to the bottom), they will occur in that order. I'm pretty sure the reason this happens is because jQuery stores these bindings in a stack that is FIFO - first in, first out.
Upvotes: 3