Saturday, September 09, 2006

Javascript hover-over HTML popup  [Digg.com This!]

I've recently needed to create some Javascript to show a small hover-over popup when the mouse is over a HTML element. A working sample can be found here. View source to and copy it for your website.

Script:

<script type="text/javascript">
function ShowPopup(hoveritem)
{
hp = document.getElementById("hoverpopup");

// Set position of hover-over popup
hp.style.top = hoveritem.offsetTop + 18;
hp.style.left = hoveritem.offsetLeft + 20;

// Set popup to visible
hp.style.visibility = "Visible";
}

function HidePopup()
{
hp = document.getElementById("hoverpopup");
hp.style.visibility = "Hidden";
}
</script>

Body:

<a id="hoverover" style="cursor:default;" onMouseOver="ShowPopup(this);" onMouseOut="HidePopup();">Hover over me!</a>

<br>This is some<br>incidental<br>Text.

<div id="hoverpopup" style="visibility:hidden; position:absolute; top:0; left:0;"><table bgcolor="#0000FF">
<tr><td><font color="#FFFFFF">This is my popup</font></td></tr>
<tr><td bgcolor="#8888FF">Hello I am a popup table</td></tr></table></div>

This sample uses a hidden div tag containing a table that forms your popup. When the mouse hovers over the target text (in this case an anchor, although it could be an image or anything else that uses the onMouseOver event) the function ShowPopup is called and the position of the popup is set to that of the target text (the offsetTop and offsetLeft members), the popup is then set to visible.

You can find the sample source here.