Reputation: 4152
In the following code:
document.getElementById( 'elem' ).addEventListener( 'blur', function() {
myScript();
});
How can I pass the document.getElementById( 'elem' ) object to myScript()? I was thinking of something like the keyword "this," so I can then act on the element in the callback function.
Upvotes: 6
Views: 12111
Reputation: 33726
this
Bind the this
object and call the function:
This approach should be used if you need to execute some logic before myScript()
execution
function myScript() {
console.log(this.id);
}
document.getElementById('elem').addEventListener('click', function() {
myScript.bind(this)();
});
<button id="elem">Click me!</button>
Call the function myScript
using function call
:
This approach should be used if you need to execute some logic before myScript()
execution
Also read about function Function.prototype.apply()
.
function myScript() {
console.log(this.id);
}
document.getElementById('elem').addEventListener('click', function() {
myScript.call(this);
});
<button id="elem">Click me!</button>
Pass the function directly:
function myScript() {
console.log(this.id);
}
document.getElementById('elem').addEventListener('click', myScript);
<button id="elem">Click me!</button>
Or pass the object this
:
function myScript(element) {
console.log(element.id);
}
document.getElementById('elem').addEventListener('click', function() {
myScript(this); //Here you will need to use the param.
});
<button id="elem">Click me!</button>
Upvotes: 7
Reputation:
Further to the answer from Ele, you should prefer the binding method. As dfsq said in the comment, you can go
element.addEventListener('click', function() {
myScript(element);
}
However, using an anonymous function like this means you won't be able to remove the event listener.
const element = document.getElementById('elem');
// creates a new function instance with element bound as first arg
const eventListenerCallback = myScript.bind(null, element);
element.addEventListener('click', eventListenerCallback);
function myScript(element, event) {
element.setAttribute('data-clicked', 'true');
// remove the event listener once it has been clicked
element.removeEventListener('click', eventListenerCallback);
}
Upvotes: 1