-1

My question is simple: Is there a way to have the event as a variable or any variable after a dot in general? Is there a way to do something like this?

var type = "onkeyup";
document.getElementById("test").type = myFunction;

or

var element = "body";
document.element.style.marginTop = 0;
  • 3
    `document.getElementById("test")[type]` this should work. – Mr_Green May 12 '17 at 09:34
  • 2
    Your question is not as simple as you might think. Yes, there is a way to have an event as a variable, but what has an event to do with your code examples? – Clijsters May 12 '17 at 09:35

4 Answers4

0

Use [] notation instead of dot .. The reason is square bracket allows to deal with variable property names.

var type = "onkeyup";
document.getElementById("test")[type] = myFunction;

function myFunction() {
  alert('worked')
}
<input id='test'>
brk
  • 48,835
  • 10
  • 56
  • 78
0

Similar to the comment provided by Mr_Green above:

var myEvent = "onkeyup";
myInput[myEvent] = function() {}

Here is a Fiddle: https://jsfiddle.net/43ceL4gf/

RobertFrenette
  • 629
  • 3
  • 8
  • 29
0

You could use addEventListener and the event as string.

The EventTarget.addEventListener() method adds the specified EventListener-compatible object to the list of event listeners for the specified event type on the EventTarget on which it's called. The event target may be an Element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest).

document.getElementById('test').addEventListener('pointerdown', myFunction, false);
//                       id
//                              add an event listener
//                                               event type
//                                                              callback
//                                                                          options
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Your code is close to solution except .type use [type]

Example here

<input type="button" value="Click me" id="test">

var type = "onclick";
document.getElementById("test")[type] =function myFunction(){
alert("Button Clicked");
}

JSfiddle link

devil_coder
  • 1,115
  • 1
  • 9
  • 12