Dynamically change onmouseover or onmouseout to call another function

Is it possible to change the function called by the existing onmouseover or onmouseout event? In the following example, do I have a way to change the ChangeItemAEvent onAmouseover ItemA function from ChangeColor () to ChangeColorBack ()? Currently, I need to declare a completely new function (), which I think is not elegant because I repeat the code when I can 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()"> 
+6
javascript css
source share
2 answers

try it

 function ChangeItemAEvent() { document.getElementById("ItemA").onmouseover = function() {ChangeColorBack(this.id)}; } 
+8
source share

Is it possible to change the function called by the existing onmouseover or onmouseout event?

Yes, by writing to the DOM property element.onmouseover with the value of the function. It can be a function name or an inline function expression.

If you run all of your scripts by writing down the properties of an event handler (or adding event listeners), you can use this to point to an element and avoid going around around identifiers, which simplifies it:

 <span id="ItemA"> <button type="button" id="ButtonB"> <script type="text/javascript"> function ChangeColor() { this.style.background= 'orange'; this.style.color= 'black'; } function ChangeColorBack(elementid) { this.style.background= 'black'; this.style.color= 'white'; } document.getElementById('ItemA').onmouseover= ChangeColor; document.getElementById('ButtonB').onclick= function() { document.getElementById('ItemA').onmouseover= ChangeColorBack; }; </script> 

However, for this type of work with hovering and selecting, you are usually better off using state variables or CSS instead of re-assigning event handlers. For example, something like:

 #ItemA:hover { background: orange; color: black; } #ItemA.selected:hover { background: black; color: white; } document.getElementById('ButtonB').onclick= function() { var a= document.getElementById('ItemA'); a.className= a.className==='selected'? '' : 'selected'; }; 

( :hover on the run does not work in IE6, so if you need to highlight this browser, you need to have onmouseover / mouseout to add or remove .hover className.)

+2
source share

All Articles