Event.srcElement is not the same as the binded element on IE click handlers
I had this problem where it seemed like setAttribute didn't work. After investigation the setAttribute() in my click handler was acting on the wrong element in IE only.
In IE, the click handler has access to event.srcElement. This event.srcElement is not necessarily the DOM element that is binded on the onClick event: it can be an element embedded inside the wanted element. Thus you would be assigning the attribute to the wrong element ! For example :
<div class="superCool jsBindedOnThis">
<div class="decoration">yep</div>
</div>
More bed-time reading http://javascript.info/tutorial/bubbling-and-capturing
The solution I used was to capture inside a closure the binded element, and feed it to the click handler function as follow :
Toolbox.onClick = function(el, callback)
{
if (el.length == null) { el = [el] };
for (var i=0; i<el.length; i++)
{
var singleEl = el[i];
if (singleEl.attachEvent) //Internet Explorer
{
var createHandler = function(scopedElement)
{
return function(event)
{
event.currentTarget = scopedElement; // this fixes any bubbling issue with IE where srcElement is not the element bound to the click handler.
callback.call(scopedElement, event);
};
}
var handler = createHandler(singleEl);
singleEl.attachEvent("onclick", handler);
}
else if (singleEl.addEventListener) //Firefox & company
{ singleEl.addEventListener("click", callback, false);
}
else {
singleEl["onclick"] = callback;
}
}
};
Recent Comments