jquerycssimage-replacement

Replace an image with a div on hover


Seems fairly simple, but I can't get it to work.

The div contains facebook / twitter links. The way it should work is that the image is displayed and then when someone hovers on it, it disappears to be replaced by the social icons.

I've got the code to work with text in the div, but as soon as I add images / scripts, it seems to break. (The code I've got doesn't have the image disappearing either, that is something I haven't figured out how to do).

Here's what I've got:

<div class="image">
<img src="/some_image.jpg">

<div class="sharerDiv">
<p>Hello!</p>
</div>
</div>

With the following css:

.sharerDiv {
display:none;
}
img:hover + .sharerDiv {
display:block;
}

Here it is on jsfiddle: http://jsfiddle.net/randomlysid/dxwma/1/

I would like ot do this with css if possible, since that's what I'm familiar with, but if jQuery is the only way to get it done, that works as well.

Thanks!


Solution

  • Change your CSS to this:

    .image
    {
      width: 80px;
      height: 80px;
    }
    .sharerDiv
    {
      display: none;
      position: absolute;
      z-index: 99;
    }
    img
    {
      position: relative;
      display: block;
    }
    .image:hover .sharerDiv
    {
      display: block;
    }
    .image:hover img
    {
      display: none;
    }
    
    1. Your outer container .image should better have the same bounds (width and height).
    2. The position value of .sharerDiv should be absolute (so it can float).
    3. hover should be applied to the outer container.

    Here is an edited fork of your code on jsFiddle.