Search code examples
javascriptjqueryhtmlcssfadein

fadeIn() starts over after resizing browser


I was going to give 3 backgrounds to a browser-sized div rotating it with jQuery's fading effect. The main problem is whenever I resize the browser, the effect starts over, and I want it to continue wherever it is at the exact moment. I am using Chrome 37. I would appreciate any help or suggestions.

HTML

<div class="wrap">
    <div class="wrapinside" style="background: url(1.jpg) no-repeat center center;"></div>
    <div class="wrapinside" style="background: url(2.jpg) no-repeat center center;"></div>
    <div class="wrapinside" style="background: url(3.jpg) no-repeat center center;"></div>
</div>

jQuery

$(window).load(function(){
$('div.wrapinside').hide();
var dg_H = $(window).height();
var dg_W = $(window).width();

$('.wrap').css({'height':dg_H,'width':dg_W});

function anim() {
    $(".wrap div.wrapinside").first().appendTo('.wrap').fadeOut(3000);
    $(".wrap div").first().fadeIn(3000);
    setTimeout(anim, 6000);
}
anim();})
$(window).resize(function(){window.location.href=window.location.href})

CSS

.wrap {
   position: fixed;
   z-index: -1;
   top: 0;
   left: 0;
   background: #000;
}   

.wrap div.wrapinside {
   position: absolute;
   top: 0;
   display: none;
   width: 100%;
   height: 100%;
   z-index: -1;
   background-size: cover;
}

Solution

  • First of all you could add this to your div.wrapinside css:

    display: none;
    

    After that you won't need this anymore:

    $('div.wrapinside').hide();
    

    Maybe this link could help you, too. Change background-image of a div with fade effect every 10 seconds with jquery

    The problem is, that you are updating the value of some variables, but not the size of the div itself, because this line:

    $('.wrap').css({'height':dg_H,'width':dg_W});
    

    is only execute once.

    Try this:

    var dg_H;
    var dg_W;
    $(window).load(function(){
    dg_H = $(window).height();
    dg_W = $(window).width();
    
    $('.wrap').css({'height':dg_H,'width':dg_W});
    
    function anim() {
        $(".wrap div.wrapinside").first().appendTo('.wrap').fadeOut(3000);
        $(".wrap div").first().fadeIn(3000);
        setTimeout(anim, 6000);
    }
    anim();})
    $(window).resize(function(){
    dg_H = $(window).height();
    dg_W = $(window).width();
    
    $('.wrap').css({'height':dg_H,'width':dg_W});
    })