Ran into this problem today, posting in case someone else has the same issue.
var execBtn = document.createElement('input');
execBtn.setAttribute("type", "button");
execBtn.setAttribute("id", "execBtn");
execBtn.setAttribute("value", "Execute");
execBtn.setAttribute("onclick", "runCommand();");
Turns out to get IE to run an onclick on a dynamically generated element, we can't use setAttribute. Instead, we need to set the onclick property on the object with an anonymous function wrapping the code we want to run.
execBtn.onclick = function() { runCommand() };
BAD IDEAS:
You can do
execBtn.setAttribute("onclick", function() { runCommand() });
but it will break in IE in non-standards mode according to @scunliffe.
You can't do this at all
execBtn.setAttribute("onclick", runCommand() );
because it executes immediately, and sets the result of runCommand() to be the onClick attribute value, nor can you do
execBtn.setAttribute("onclick", runCommand);
I did this to get around it and move on, in my case I'm not using an 'input' element, instead I use an image, when I tried setting the "onclick" attribute for this image I experienced the same problem, so I tried wrapping the image with an "a" element and making the reference point to the function like this.
This is an amazing function for cross-browser compatible event binding.
Got it from http://js.isite.net.au/snippets/addevent
With it you can just do
Events.addEvent(element, event, function);
and be worry free!For example: (http://jsfiddle.net/Zxeka/)
Here's the function:
If you don't want to use such a big function, this should work for almost all browsers, including IE:
In response to Craig's question. You're going to have to make a new element and copy over the attributes of the old element. This function should do the job: (source)
Try this execBtn.onclick =function() { eval('runCommand()') };
For me it works.
Or you could use jQuery and avoid all those issues:
jQuery will take care of all the cross-browser issues as well.
Did you try: