Skip to content
Advertisement

How to generalize this script for multiple popups on mouseover

I have a script that works to switch between two popups that are triggered by an onmouseover event. One feature of this is that the popup persists until the next onmouseover event. I want to have many of these and so the popup to be hidden can not be ‘hard coded’ as in my script. Is there a way to store in a variable the id of the popup that needs to be undisplayed the next time the popup function is called?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
function popup(show,hide){
    show.style.display="block"
    hide.style.display="none"
    }
</script>
<style type="text/css">
.pop {
    position: absolute;
    display: none;
    top: 50px;
    left: 200px;
    width: 300px;
}
</style>
</head>
<body>

<table><tr>
<td onmouseover="popup(pop1,pop2)">Show popup 1</td>
<td onmouseover="popup(pop2,pop1)">Show popup 2</td>
</tr></table>

<div class="pop" id="pop1">This is popup 1</div>
<div class="pop" id="pop2">Popup 2 is here</div>

</body>
</html>  

or go to http://www.salemharvest.org/Utilities/TestingPHP/testingpopupdivs5.php

Advertisement

Answer

One way to generalize it is to use element index to show the associated popup. This will require that the popup elements (pop class elements) is contained by an element, in order to make both the popper and the popup element indexes mapped equally like two arrays of same length.

When showing a popup, the popup element is saved in a variable which will be used later when the mouse is on a different popper element.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
addEventListener("DOMContentLoaded", function() {
  var lastPopup = null;
  function showit(ev) {
    var popups = document.getElementById("popups").children;
    eleToShow = popups[ev.target.cellIndex];
    if (lastPopup && (lastPopup !== eleToShow)) lastPopup.style.display = "none";
    eleToShow.style.display = "block";
    lastPopup = eleToShow;
  }
  var poppers = document.getElementById("poppers").cells, i;
  for (i = 0; i < poppers.length; i++) {
    poppers[i].addEventListener("mouseover", showit, false);
  }
}, false);
</script>
<style type="text/css">
.pop {
    position: absolute;
    display: none;
    top: 50px;
    left: 200px;
    width: 300px;
}
</style>
</head>
<body>

<table><tr id="poppers">
<td>Show popup 1</td>
<td>Show popup 2</td>
</tr></table>

<div id="popups">
<div class="pop">This is popup 1</div>
<div class="pop">Popup 2 is here</div>
</div>

</body>
</html>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement