Image hover using Javascript

This post shows how to implement simple image hover with IFRAME and DIV. In both cases JavaScript code will set innerHTML to DIV element and make it visible. IFRAME version will force browser to make connection each time while DIV version may have some problems with older browsers (dropdown menu stays in front of displayed image).

Here is live demo. Try both versions with moving mouse pointer over the Spider1 or Spider2 links.

Spider1 Spider2 – version with DIV
Spider1 Spider2 – version with IFRAME


I prepared a small JavaScript code to demonstrate the problem and to offer a solution. When user moves pointer over Spider1, JavaScript code calculates the element position on the page, sets the new DIV location and innerHTML property and finally shows the DIV element. After mouse pointer moves away, JavaScript will hide DIV element.

// define global elements
var hoverboxShow,
    hoverboxHide,
    getStyle,
    hoverboxDiv;

// set reference to the DIV element after page is loaded
window.onload = function () {
    hoverboxDiv = document.getElementById('hoverbox');
};

// show hoverbox
hoverboxShow = function (obj, src, type) {
    // define oTop and oLeft variables
    var oTop = 0,
        oLeft = 0,
        position;

    // find object position on the page
    do {
        // get element "position" style
        position = getStyle(obj, 'position');
        // calculate only "static" elements
        // e.g. ignore elements that appear in chain because they have "position: relative"
        if (position === 'static') {
            oLeft += obj.offsetLeft;
            oTop += obj.offsetTop;
        }
        // set next element in chain
        obj = obj.offsetParent;
    } while (obj && obj.nodeName !== 'BODY');
    
    // set the position of invisible DIV
    hoverboxDiv.style.top  = (oTop  + 20) + 'px';
    hoverboxDiv.style.left = (oLeft + 20) + 'px';
    // put IFRAME with IMG in DIV element (this will work in any browser)
    if (type === 'iframe') {
        hoverboxDiv.innerHTML = '<iframe marginwidth="0" marginheight="0" frameborder="no" ' +
                                  'width="100%" height="100%" scrolling="no" ' +
                                  'src="/my/img/' + src + '"></iframe>';
    }
    // or place IMG inside DIV element (IE6 has problem with select overlay)
    else {
        hoverboxDiv.innerHTML = '<img src="/my/img/' + src + '"/>';
    }
    // show hoverbox
    hoverboxDiv.style.visibility = 'visible';
};

// hide hoverbox (hide DIV element)
hoverboxHide = function () {
    hoverboxDiv.style.visibility = 'hidden';
};

// get element style (crossbrowser)
getStyle = function (el, style_name) {
    var val; // value of requested object and property
    if (el && el.currentStyle) {
        val = el.currentStyle[style_name];
    }
    else if (el && window.getComputedStyle) {
        val = document.defaultView.getComputedStyle(el, null)[style_name];  
    }
    return val;
};

Hover box is a hidden DIV element. You can place this DIV element anywhere on the page because hidden DIV will not interfere with other elements. I usually write DIV right after body tag.

/* hover box */
#hoverbox {
    position: absolute;
    width: 185px;
    height: 90px;
    visibility: hidden; 
}

And here is HTML code for use JavaScript functions mentioned above.

<!-- hidden DIV for hoverbox -->
<div id="hoverbox"></div>

<!-- DIV version -->
<span onmouseover="hoverboxShow(this, 'spider1_big.png', 'div')" onmouseout="hoverboxHide()">Spider1</span>
<span onmouseover="hoverboxShow(this, 'spider2_big.png', 'div')" onmouseout="hoverboxHide()">Spider2</span>

<!-- IFRAME version -->
<span onmouseover="hoverboxShow(this, 'spider1_big.png', 'iframe')" onmouseout="hoverboxHide()">Spider1</span>
<span onmouseover="hoverboxShow(this, 'spider2_big.png', 'iframe')" onmouseout="hoverboxHide()">Spider2</span>

AJAX isn’t needed to fetch and display images on mouseover event. Just use DIV and set innerHTML if you haven’t form elements on the page. Otherwise you will have to apply this IFRAME trick.

On the other hand, if you want to display HTML in hover box (like tooltip), you will have to set correct URL in IFRAME src attribute – nothing more. Solution with DIV will be a little complicated because you will have to request HTML content with AJAX. I wrote a post AJAX progress bar where you can see how to use AJAX.

11 thoughts on “Image hover using Javascript

  1. Hi!
    lol, Your pages with scripts are REALLY cool :)

    But mostly like image hover using JavaScript with div :)

    Thanks dude

  2. might i be able to use this if i were trying to get an image to hover over an iframe without needing the pointer to be over it?

  3. jess – Yes, you can create DIV element with inner iframe and absoulte position DIV element where ever on page. It’s only needed to properly set top and left styles of DIV element.

  4. You need an example of how to call this script from the html. I had to do a view source to see your html.

  5. @Stephen – HTML example is included on the page now. Thank you for suggestion.

  6. How would I get the hoverbox to fit the size of the image to the maximum size of 90px when I use the following code:

    div.innerHTML = '<iframe marginwidth="0" marginheight="0" frameborder="no" ' +
                              'width="90" height="90"
    

    At the moment, any images I select in my HTML page only show a proportion of the image!

    Greg

  7. @Greg – I’m not sure that fixed box can be created simply with iframe because iframe loads image from the server. But it is possible with DIV. Here is example of how you can create box of 50px width and height using inline CSS:

    div.innerHTML = '<div style="width:50px;height:50px">' + 
    '<img style="display:block;width:100%" src="http://www.redips.net/my/img/' + src + '"/>' +
    '</div>';
    

    I don’t prefer inline CSS (because of mixing with HTML) but I hope it will give you a hint …

  8. Hello dbunic.
    I now have a problem with images and a slideshow.
    In a nutshell, what the code needs to do is. Change to a next picture (7 in total) each time the mouse is over the pic. Then when the last one is reached my alert will pop and the pic will go back to the original. I have the code however I can not for the life of me get it to work. Can mail me directly if you like.

    I see I need to convert it, that will take some time. Any other methods of me showing you the code?

  9. @Zark – JS code to show each time the other image hover doesn’t sound complicated. Here are few tips that might help you:
    – image location can be stored in Array
    – set counter to 0 -> var i = 0;
    – on mouse over, display image with index definition like -> idx = i % 7;
    – on mouse out increase counter -> i++;
    The idea is to increase counter on each mouseout and to use modulo operation for preparing Array index. 7 is total number of images to rotate on each mouseover. Hope this tips will help you.

Leave a Comment