If you have already tried dynamically to generate HTML elements over Javascript DOM, then is the "setAttribute" method the one that you have used a lot. This method is very useful if you are developing Javascript/AJAX based custom control but the main problem of this method is that you cannot set Attributes (events) like "onClick", "onMouseMove", etc ...
When you try to add such attributes, you will not get any Errors, but the event will not be triggered, as showed in following example:
var newElement = document.createElement("INPUT");
newElement.setAttribute("type","button");
newElement.setAttribute("onClick", "element_onClick");
document.appendChild(newElement);
.....
function element_onClick()
{
alert ('Hello World');
}
The same effect will happend if you try to use attachEvent Method for newElement object. The only working solution that I have found is to register the Function on onClick property of newElement object as showed below:
var newElement = document.createElement("INPUT");
newElement.setAttribute("type","button");
newElem.onclick = function () {element_onClick(this)};
document.appendChild(newElement);
.....
function element_onClick(clickedObject)
{
alert (clickedObject.id);
}
Posted
Dec 21 2006, 11:45 AM
by
Armin Kalajdzija