0
votes

Q: I have a content page with an empty div inside it that fades in different background images depending on which menu item is hovering over. My question is how I can wait for the current background image to fadeOut before the current menu item is hovering on is allowed to fadeIn. Currently, if I hover to quickly over another menu item the fadeIn background image animation is behaving like it's already happened.

You can see my solution and description image below.

Description

HTML

<div class="bg"></div>

          <a id="first" href="{{ url('example') }}" class="buttonlink">

                   <div class="buttontitle">

                    <h1 class="buttontitleinner">example</h1>

                     <p class="buttoncaption">example</p>

                 </div>
            </a>

          <a id="second" href="{{ url('example2') }}" class="buttonlink">

                   <div class="buttontitle">

                    <h1 class="buttontitleinner">example2</h1>

                     <p class="buttoncaption">example2</p>

                 </div>
            </a>

jQuery

$("#first").hover(function () {

    $(".bg").css("background-image", 'url("./img1.png")').stop().animate({'opacity': 0.25}, 300);

    },function(){

    $(".bg").css("background-image", 'url("./img1.png")').stop().animate({'opacity': 0}, 500);

});


$("#second").hover(function () {

    $(".bg").css("background-image", 'url("./img2.png")').stop().animate({'opacity': 0.25}, 300);

    },function(){   

    $(".bg").css("background-image", 'url("./img2.png")').stop().animate({'opacity': 0}, 500);

});

Questions? Just ask.

Thanks beforehand!

///E

1

1 Answers

0
votes

After calling .stop(), but before calling .animate() to fade the image in, set the opacity to 0. That way the fade-in animation will completely run. Otherwise, the opacity may already be at 0.25, so it won't run.

$(".bg").css("background-image", 'url("./img1.png")').stop().css({opacity: 0}).animate({opacity: 0.25}, 300);

jsfiddle