Reputation: 843
I want to assign a JavaScript function to an event that already has a handler function. The new function should not change or remove (unassign) the existing function.
As an example:
I have a function called exFunction()
that is already assigned to document.onmousemove
. I have another function newFun()
to assign to the same event. What I want to happen is when the document.onmousemove
event occurs both functions are triggered.
newFun()
is not a static function. It is going to be changing according to the webpage. (otherwise I can just write another function that calls both functions).
pure JavaScript only
Upvotes: 2
Views: 1169
Reputation: 26161
addEventListener
is the right way to do this however time to time you may need to do this over the DOM element property event listeners by monkey patching.
Forgive me for partially snatching @AlexKudryashev's snippet.
var myDiv = document.getElementById('my-div'),
myBut = document.getElementById('my-button'),
f1 = e => console.log(`clicked "${e.currentTarget.id}" and f1 invoked`);
f2 = e => console.log(`clicked "${e.currentTarget.id}" and f2 invoked`);
monkeyPatch = (f1,f2) => e => (f1(e),f2(e));
myDiv.onclick = f1;
myBut.onclick = function(e){
console.log(`f2 monkey patched to f1. Click My Div to see the effect`);
myDiv.onclick = monkeyPatch(myDiv.onclick, f2);
}
<div id="my-div" style="width:100px;height:100px;border:solid 1px">My Div</div>
<button id="my-button">Monkey Patch f2</button>
Upvotes: 1
Reputation: 9470
As mentioned in other answers, you can easily assign several eventListeners to the event.
Note that the name of the function is the address of the code to execute and this address is immutable. The snippet shows what works and what doesn't.
var myDiv = document.getElementById('my-div');
function foo1(e) {
console.log('foo1');
if (e.altKey)
foo1 = foo2; //this doesn't work
};
function foo2(e) {
console.log('foo2');
if (e.shiftKey) {
myDiv.removeEventListener('click', foo2);
myDiv.addEventListener('click', foo3);
}
};
function foo3(e) {
console.log('foo3');
if (e.shiftKey) {
myDiv.removeEventListener('click', foo3);
myDiv.addEventListener('click', foo2);
}
};
//assign **addresses** of functions to eventListener
myDiv.addEventListener('click', foo1);
myDiv.addEventListener('click', foo2);
<div id="my-div" style="width:100px;height:100px;border:solid 1px"></div>
Upvotes: 1
Reputation: 159
You can also do like this
document.addEventListener("mousemove", function() {
myFunction();
someother();
});
Upvotes: 1
Reputation: 1114
By using addEventListener
, you can apply multiple functions.
document.addEventListener('mousemove', exFunction)
document.addEventListener('mousemove', newFun)
Upvotes: 2