user56062
user56062

Reputation: 369

How to dynamically assign DOM event and then execute it?

i am trying to execute DOM events within a function that expects the event to handle, such as onmouseover, onclick and so on, by name as a function parameter like so:

...

doSomething(target, 'onmouseover');

doSomething : function(tgt, evt)
{
   ...
   o.evt = function() {
      alert(evt);
   }
   ...
}

...

The assignment does not throw any errors, so i guess, it is syntactically correct, but it does also not do the alert. Why?

(Please do not recommend using frameworks. I would like to understand my mistake and how to get this managed.)

Upvotes: 0

Views: 43

Answers (1)

MrCode
MrCode

Reputation: 64526

You can assign the event dynamically using the [] notation:

Demo

var obj = {
   doSomething : function(tgt, evt)
   {
      tgt[evt] = function() {
         alert(evt);
      }
   }
};

obj.doSomething(document.getElementById("test"), 'onmouseover');
​

Upvotes: 2

Related Questions