Satinder Singh Satinder Singh - 1 year ago 74
HTML Question

How can we pass an element to event handler in javascript

I have created an

HTML element using Javascript. Now I want to add an
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
. How can I do that?

function hello_function(element) {

Answer Source

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() {

function hello_function(element) {

Also note the preferred use of addEventListener over onblur.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download