Flickering div driving me crazy...help!

I have an image that has an alt tag. On hover of the image I am showing the alt text over the image. My issue is that the div containing the alt text keeps flickering when you hover over the image… here is a demo of what’s happening: http://jsfiddle.net/mCrM5/1/

I am not sure what needs to be done to remedy the situation.

Any help would be greatly appreciated!

Hi there,

One way to stop the flickering would be to structure your HTML slightly differently:

<li>
  <a href="#" class="thumbnail" >
    <img src="http://placekitten.com/205/145" alt="Show alt text over image" />
  </a>
</li>

then attach the event handler to the anchor tag:

$("a.thumbnail").on(
{
  mouseenter: function()
  {
    var a = $(this).find("img").attr('alt');
    $(this).append('<div class="rollover">' + a + '</div>');
  },
  mouseleave: function()
  {
    $('.rollover').hide();
  }
});

Here’s a demo to copy and paste:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Image hover script</title>
    <style>
      ul li img.thumbnail{
        position:relative;
      }

      .rollover {
        position:absolute;
        display:block;
        background:yellow;
        background-repeat:repeat;
        -moz-box-shadow: 0 0 1px rgba(204,204,204,0.05);
        -webkit-box-shadow: 0 0 1px rgba(204,204,204,0.05);
        box-shadow: 0 0 1px rgba(204,204,204,0.05);
        z-index:1000;
        top:45px;
        text-align:center;
        width:207px;
        height:40px;
        padding-top:7px;
      }
    </style>
  </head>

  <body>
    <ul>
      <li>
        <a href="#" class="thumbnail" >
          <img src="http://placekitten.com/205/145" alt="Show alt text over image" />
        </a>
      </li>
    </ul>

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
      $("a.thumbnail").on(
      {
        mouseenter: function()
        {
          var a = $(this).find("img").attr('alt');
          $(this).append('<div class="rollover">' + a + '</div>');
          console.log("on");
        },
        mouseleave: function()
        {
          $('.rollover').hide();
          console.log("off");
        }
      });
    </script>
  </body>
</html>