-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
  • 46,805
  • 5
  • 49
  • 71
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
  • 545
  • 1
  • 7
  • 28
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
  • 351,820
  • 24
  • 303
  • 358
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,085
  • 1
  • 9
  • 12