Zwerfkat said:
In my HTML code is somewhere listed:
<div id=mydif onmouseover="do_something(this,3,2,1);">test</div>
Is there a way to add/change this mouseover event dynamically, including its parameters?
Because it looks like:
obj= getElementbyID("mydif");
obj.onmouseover = do_something;
or:
obj.attachEvent("onmouseover",do_something);
does not allow me to add parameters to the event, or?
Neither one is equivalent to the HTML code. You have to understand first
that there are events, event handlers and event listeners. The event here
is `mouseover'. It has a corresponding intrinsic event handler attribute,
`onmouseover'. By setting that attribute, an event listener for the
`mouseover' event is added to the corresponding DOM object that has the
attribute value as its code. It looks like this:
function()
{
do_something(this, 3, 2, 1);
}
But the signature of the event listener, i.e. the arguments it is being
passed, is built into the UA's DOM and cannot be modified. In standards
compliant DOMs, event listeners implement the EventListener interface,
where the Event object is passed as first and only argument:
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener
In the MSHTML DOM, no argument is passed; the reference to the Event object
has to be obtained through window.event:
http://msdn2.microsoft.com/en-us/library/ms535863.aspx
obj.attachEvent() works differently. The same as the standards compliant
obj.addEventListener(), this IE-proprietary method *adds* an event listener
to a DOM object. In contrast to obj.addEventListener() where the last
listener added will be the last one that is executed on event, the order of
listeners is not guaranteed with obj.attachEvent().
http://msdn2.microsoft.com/en-us/library/ms536343.aspx
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-addEventListener
So obj.attachEvent() and obj.addEventListener() *alone* are the wrong
methods to call when you want to replace the event listener. However,
you can try removing the previously assigned event listener first and
then add another one:
obj.detachEvent("onmouseover", obj.onmouseover);
obj.attachEvent("onmouseover", function() { window.alert(42); });
or
obj.removeEventListener(
"mouseover", obj.onmouseover, false);
obj.addEventListener(
"mouseover", function() { window.alert(42); }, false);
That would still rely on the proprietary `onmouseover' property to yield a
reference to the event listener, and I know of no way to avoid that. The
only alternative would be to go proprietary completely and assign to the
property itself:
obj.onmouseover = function(e)
{
window.alert(42);
};
A wrapper method could facilitate this resulting in only one direct call.
PointedEars