Reputation: 307
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);
}
Upvotes: 10
Views: 1235
Reputation: 1086
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);
}
Upvotes: 1
Reputation: 22500
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);
}
Upvotes: 1
Reputation: 337656
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
.
Upvotes: 9