Search code examples
jquerycssrollover

display image on mouse over


What would be the easiest way to add a zoom icon to the top left of an image when you hover over the image.

All I am finding with rollovers is affecting the background image.

Ideally I would only make 1 zoom div and image

<div class="zoom"><img src="img/zoom_icon.png" /></div>

and clone that to any image inside a div called gallery

 <div class="gallery">
  <a href="#zoomed"><img src="img/hey.png" /></a>
 </div>

And use jquery with mouseover to get the zoom class and position it correctly:

display: block; position: relative; top:0; left:0

And when you mouseout to hide the zoom icon.

Hope this makes sense. Any advice would be great.


Solution

  • With jQuery:

    var zoomIcon = $('<img src="path/to/zoom/icon.png" class="zoomIcon" />');
    $('.zoom').hover(
        function(){
            $(this).append(zoomIcon);
        },
        function(){
            $(this).find('.zoomIcon').remove();
        });
    

    With CSS:

    .gallery {
        position: relative;
    }
    
    .gallery > .zoomIcon {
        display: none;
        position: absolute;
        top: 0;
        left: 0;
    }
    
    .gallery:hover > .zoomIcon {
        display: block;
    }
    

    This requires the following mark-up, of course:

    <div class="gallery">
        <img src="path/to/zoom/icon.png" class="zoomIcon" />
        <!-- other content -->
    </div>