Simple Mouseover Div Swap
This article contains copy and paste JavaScript to swap two divs on a page. Along with an example of how to use it.
The example swaps two divs. We'll call them Div A and Div B. Div A is displayed. Div B is un-displayed.
When the mouse pointer moves over Div A, the two divs swap their display definitions — Div A is un-displayed and Div B is displayed.
When the mouse pointer moves off Div B, the two divs swap their display definitions again.
(See the Mouseover DIV Swap Willmaster Library article for a more elaborate mouseover div swap.)
Here is a demonstration of this article's simple mouseover div swap:
The Simple Mouseover Div Swap Code
This is the code for the above example.
<!-- the code for Div A --> <div id="diva_id" style="display:block; width:125px; height:100px; padding:10px; border:5px solid gold; background-color:black; color:gold; text-align:center; font-size:100px; line-height:100px; font-weight:bold; font-family:arial,times" onmouseover="SwapDivs('diva_id','divb_id')"> A </div> <!-- the code for Div B --> <div id="divb_id" style="display:none; width:125px; height:100px; padding:10px; border:5px solid black; background-color:gold; color:black; text-align:center; font-size:100px; line-height:100px; font-weight:bold; font-family:arial,times" onmouseout="SwapDivs('diva_id','divb_id')"> B </div> <!-- the JavaScript --> <script type="text/javascript"> function SwapDivs(da,db) { var d = document.getElementById(da); if( d.style.display == "block" ) { d.style.display = "none"; document.getElementById(db).style.display = "block"; } else { d.style.display = "block"; document.getElementById(db).style.display = "none"; } } </script>
You'll notice that Div A has an onmouseover attribute and Div B has an onmouseout attribute. The value of both attributes is a call to JavaScript function SwapDivs() with two parameters, the id values of the divs to swap.
The JavaScript is copy and paste.
Use the JavaScript anywhere that the CSS display definitions of two divs need to be swapped. Any two divs on a page, so long as their id values are not duplicates of other id values.
Call the JavaScript function SwapDivs() with the id values of two divs (doesn't matter which id value is specified first) and it will merrily swap their CSS display definitions.
Will Bontrager