Is it possible to change a function that is called by an existing onmouseover or onmouseout event? For the following example is there a way for me to have ChangeItemAEvent change the “ItemA” onmouseover function from ChangeColor() to ChangeColorBack()? Currently I need to declare an entirely new function that I feel is not elegant because I am repeating code when I should be able to call an existing function.
javascript:
function ChangeColor(elementid)
{
document.getElementById(elementid).style.background = "Orange";
document.getElementById(elementid).style.color = "Black";
}
function ChangeColorBack(elementid)
{
document.getElementById(elementid).style.background = "Black";
document.getElementById(elementid).style.color = "White";
}
function ChangeItemAEvent()
{
document.getElementById("ItemA").onmouseover = function() {
document.getElementById("ItemA").style.background = "Black";
document.getElementById("ItemA").style.color = "White";
};
}
html:
<span id="ItemA" onmouseover="ChangeColor(this.id)">
<button id="ButtonB" onclick="ChangeItemAEvent()">
Thanks in advance
Attach the events in JavaScript instead of in the markup:
Note that capitalized function names are usually reserved for constructors as a convention.
Then on your function use
thiswhich refers to the element where is being called:Now you can use these functions on any element by just assigning a new function to the element’s event or by overriding the function that was previously set.