In case you need to call two different javascript methods on the same element, please do not mix jquery and javascript. Well yes, I can bundle the two methods into one and call one, but what if one method is bound to the type of element in the DOM (e.g., the table headers in the tablesorter plugin).
I always use javascript to bind events on elements because it is easier to debug, you do not have to look for the binded methods all over the js files. Also the onclick, onblur, onfocus, and such methods always work fine in all browsers.
Or so I thought.
Till I discovered this corner scenario where your onclick will not work in Internet Explorer:
Moral of the story: Do not intermingle jquery click() and javascript onclick(), and if you cannot avoid that, do not return false from your jquery click() method.
I always use javascript to bind events on elements because it is easier to debug, you do not have to look for the binded methods all over the js files. Also the onclick, onblur, onfocus, and such methods always work fine in all browsers.
Or so I thought.
Till I discovered this corner scenario where your onclick will not work in Internet Explorer:
- Your element e is already click-binded to a method called second() using jquery that returns false.
- You add a js onclick method called first().
- You invoke the click on this element e programatically using the click() method.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
function callOnClick(){
alert("call another item's onclick method");
$("#toclick").click();
}
function first(){
alert("one");
}
function second(){
alert("two");
}
function third(){
alert("three");
}
$(document).ready(function(){
$("#toclick").click(function(e){
second();
return false;
});
$("#toclick").click(function(e){
third();
});
});
</script>
<div id="toclick" onclick="first()" style="cursor:pointer; margin-bottom:10px">
This should get clicked automatically.
</div>
<div id = "trigger" onclick="callOnClick()" style="cursor:pointer;">
Click here.
</div>
The javascript method first() is not called at all. However, if you add another method called third() using jquery after the second() method, it gets called. If you are viewing this on any browser other than IE, you would see alerts two, three, and one when you click on click here.But on IE, you will see only two and three.Moral of the story: Do not intermingle jquery click() and javascript onclick(), and if you cannot avoid that, do not return false from your jquery click() method.
Here is a working sample:
This should get clicked automatically.
Click here.
View this post on IE and other browsers and you'll know the difference.
Edit: This works fine with jQuery 1.4.2. Seems like a bug in jQuery 1.2.6, the version I previously used.
No comments:
Post a Comment