Link to home
Start Free TrialLog in
Avatar of dignified
dignified

asked on

Why Doesn't input.setAttribute("onblur", "myFunction(this)") Work in IE?

I am dynamically creating elements and want to set onblur to do something, this works in FF but not IE,

input.setAttribute("onblur", "myFunction(this)")

So basically the node will look something like this in the end:

<input type="text" onblur="myFunction(this)">

Is there an easy fix?
Avatar of kebabs
kebabs
Flag of Australia image

You have to use input.onblur unfortunately

IE interprets what you have as input[onblur] = "myFunction(this)" with the JS as a string.
Avatar of dignified
dignified

ASKER

That doesn't work using

input.onblur = "myFunction(this)"

This is going to be annoying then to try and get the "this" to perform properly. I may have to change the code to use a cloneNode(true)
ASKER CERTIFIED SOLUTION
Avatar of kebabs
kebabs
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I didn't suggest addEventListener because it is not well supported but forgot I tackled this same issue earlier. If you are interested, here is the cross browser compatible function I use. It invokes addEventListener, attachEvent or a pseudo method I conjured up that I use for this sort of stuff. Should work in your case.

e.g.
addEvent('input', 'blur', 'myFunction');

function myFunction(evt) {
// ...

Also see:
http://www.captain.at/howto-addeventlistener-attachevent-parameters.php
function addEvent(ele, event, callback) {
  if (typeof(ele) == "string")
    ele = byId(ele);
  if (ele.addEventListener) {
    ele.addEventListener(event, callback, false);
  } else if (ele.attachEvent) {
    ele.attachEvent("on"+event, callback);
  } else {
    psuedoAttachEvent(ele, event, callback);
  ele["on"+event] = function() { psuedoTriggerEvents(ele, event) };
  }
}
 
function psuedoAttachEvent(ele, event, callback) {
  if (!ele.psuedoEvents) ele.psuedoEvents = {};
  if (!ele.psuedoEvents[event]) ele.psuedoEvents[event] = [];
  ele.psuedoEvents[event][ele.psuedoEvents[event].length] = callback;
}
 
function psuedoTriggerEvents(ele, event){
  if (ele && ele.psuedoEvents && ele.psuedoEvents[event])
    for (var i=0, len=ele.psuedoEvents[event].length; i<len; i++)
      ele.psuedoEvents[event][i]();
}

Open in new window

thanks a lot. Actually what I did was had a dummy template node with the onblur already in there and set it to display:none

and then I clone it and change the id to make it unique.

Thanks for your help