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);
Write the function inline, and the interpreter is smart enough to know you're writing a function. Do it like this, and it assumes it's just a string (which it technically is).
to make this work in both FF and IE you must write both ways:
thanks to this post.
UPDATE: This is to demonstrate that sometimes it is necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden:
There is a LARGE collection of attributes you can't set in IE using .setAttribute() which includes every inline event handler.
See here for details:
http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html
In some cases the examples listed here didn't work out for me in Internet Explorer.
Since you have to set the property with a method like this (without brackets)
it won't work if you have to pass an object-name or even parameters. For the Internet Explorer you should create a new object in runtime:
Works also on other browsers.
Not relevant to the onclick issue, but also related:
For html attributes whose name collide with javascript reserved words, an alternate name is chosen, eg.
<div class=''>
, butdiv.className
, or<label for='...'>
, butlabel.htmlFor
.In reasonable browsers, this doesn't affect
setAttribute
. So in gecko and webkit you'd calldiv.setAttribute('class', 'foo')
, but in IE you have to use the javascript property name instead, sodiv.setAttribute('className', 'foo')
.works great!
using both ways seem to be unnecessary now:
apparently works in every current browser.
tested in current Firefox, IE, Safari, Opera, Chrome on Windows; Firefox and Epiphany on Ubuntu; not tested on Mac or mobile systems.