Search code examples
jqueryhoveropacity

Change opacity of 2 items on hover


I have 2 images on my page. when I hover over img.a, it changes opacity to 0 and works perfectly. However I would like img.c to also change opacity to 0 when img.a is being hovered over. My code works for img.a but nothing for img.c

<script type='text/javascript'>
$(document).ready(function(){
$("img.a").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
},
function() {
$("img.c").stop().animate({"opacity": "0"}, "slow");
},
function() {
$("img.c").stop().animate({"opacity": "1"}, "slow");
});

});
</script>

Solution

  • The problem is your syntax.

    jQuery's hover() function only has two arguments - the two functions. The first one is the one which is called when you mouseover the element, and the other one is called when you mouse out.

    You're almost there, now all you need to do is combine the 4 functions into two functions and it will work:

    <script type='text/javascript'>
    $(document).ready(function(){
    
      $("img.a").hover(
    
        function() { // this function is called on mouseover img.a
            $(this).stop().animate({"opacity": "0"}, "slow");
            $("img.c").stop().animate({"opacity": "0"}, "slow");
        },
        function() { // this function is called on mouseout img.a
            $(this).stop().animate({"opacity": "1"}, "slow");
            $("img.c").stop().animate({"opacity": "1"}, "slow");
        }
    
      });
    
    });
    </script>