I’m trying to set the “onclick” attribute of a link generated with jQuery.
While other attributes work without problem (eg. href, but also other custom attrs), setting “onclick” seems to only work in FireFox. On other browsers the attribute just gets ignored.
Any hint? Is this behaviour correct? And why?
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function(){
var obj = $('<a/>');
obj.html('click me');
obj.attr({'href':'#test', 'onclick':'alert("o hai"); return false;'});
$('body').append(obj);
});
</script>
</head><body /></html>
EDIT: I know about the .click() jQuery method; but that’s not the point, I just want to set the attribute and can’t figure out why it doesn’t work like any other attr does.
In as much as
attr('onsomeevent', ...)has never been the way to add event listeners, has never been supported, and only works on Firefox due to coincidence, yes.Because IE before version 8 can’t directly get/set HTML attributes. Calling
setAttribute()only sets a DOM property of the same name. And theonclickproperty isn’t a string property so you can’t write a string to it. It only accepts a function value.jQuery’s
attr()muddies the issue by being calledattrbut actually writing to DOM properties and not HTML attributes… but using HTML attribute names (like eg.class) rather than DOM property names (likeclassName).(Except when it doesn’t, because for some cases it tries to hide the difference by using attributes. Except that still doesn’t work all the time in IE for the reason above. This is not one of jQuery’s proudest moments.)
Anyhow, in general having JavaScript in a string is a code smell. The best way forward for jQuery and modern JavaScript in general is to use function objects (possibly inline
function() { ... }expressions) instead.