Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we pass an element to event handler in javascript

I have created an <input> HTML element using Javascript. Now I want to add an onblur event handler to this element dynamically. However I do not understand how I can pass the created element as an argument to the function. Here's my code:

element = document.createElement("input");
element.onblur = hello_function;

In the above code you can see that the element is created. Now I want to pass that element to hello_function. How can I do that?

function hello_function(element) {
    alert(element);
}
like image 361
Satinder Singh Avatar asked Nov 15 '16 08:11

Satinder Singh


People also ask

How do I pass data to event handler?

If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.

How many ways can you attach an event handler to a DOM element?

There are three ways to assign an event handler: HTML event handler attribute. HTML DOM property. HTML DOM addEventListener() method.

How do event handlers work in JavaScript?

To react to an event, you attach an event handler to it. This is a block of code (usually a JavaScript function that you as a programmer create) that runs when the event fires. When such a block of code is defined to run in response to an event, we say we are registering an event handler.


3 Answers

To achieve this you can wrap the hello_function call in an anonymous function wrapper and provide the this argument:

element = document.createElement("input");
element.addEventListener('blur', function() {
  hello_function(this);
});
document.body.appendChild(element);

function hello_function(element) {
  console.log(element);
}

Also note the preferred use of addEventListener over onblur.

like image 154
Rory McCrossan Avatar answered Oct 04 '22 13:10

Rory McCrossan


try like this. passing the another variable into a function,

var something="hello";
var element = document.createElement("input");
  element.addEventListener('blur' , function ()
                           {
    hello_function(something);
  
  })
 document.body.appendChild(element)

 function hello_function (element){
      alert(element);
}
like image 42
prasanth Avatar answered Oct 04 '22 12:10

prasanth


i suggest to use addEventListener, also i think you need to append the created element to the document, something like this:

var elem = document.createElement("input");
if (elem) {
  elem.addEventListener('blur', hello_function, false);
}
document.body.append(elem);
function hello_function(element) {
  alert(element);
}
like image 43
Kevin Kloet Avatar answered Oct 04 '22 14:10

Kevin Kloet