Change background image on hover to every image gallery links

547 Views Asked by At

How do i change the page background when i hover to every image link on the page. I would like to dynamically change the page background according to every image on the page. Please have a look at the code to get exact idea what i am trying to say.

    <script>
        $(function() {
        $("a").hover(function() {
        var $link = $("img").attr("src");
                $("body").css("background", "url(" + $link + ")" );
        });
        });
    </script>

<html>
   <body>
      <a href="#" title="">
        <img src="portfolio_files/NEWSALV.gif" alt="">
      </a>
      <a href="#" title="">
        <img src="portfolio_files/TSThumb.gif" alt="">
      </a>
      <a href="#" title="">
        <img src="portfolio_files/MoreheadThumb.gif" alt="">
      </a>
   </body>
</html>

Please help on this, thanks in advance.

1

There are 1 best solutions below

0
On

Using $("img") will return the first img element in your document each time. You need to find the img element relative to the a element each time.

This can be achieved by using $(this) and .find();

<script>
    $(function() {
        $("a").hover(function() {
            var $link = $(this).find("img").attr("src");
            $("body").css("background", "url(" + $link + ")" );
        });
    });
</script>