Joansy
Joansy

Reputation: 159

Why Does Js Slideshow Skip First Two Slides?

My Javascript slideshow works, except for the first two images act clunky. The images "skip" in, then seem to get caught when they're supposed to fade. The slideshow also starts with the last image instead of the first, which is why I have moved the images in the HTML out of order. What is causing this in the code?

The Javascript:

<script>
    $("#slideshow > div:gt(0)").hide();

    setInterval(function() { 
        $('#slideshow > div:first')
            .fadeOut(10000)
            .next()
            .fadeIn(10000)
            .end()
            .appendTo('#slideshow');
    }, 10000);
</script>

The HTML:

<div id="slideshow">
    <div>
        <img src="img/2.jpg">
    </div>
    <div>
        <img src="img/3.jpg">
    </div>
    <div>
        <img src="img/1.jpg">
    </div>
</div>

The CSS:

#slideshow { 
    position: relative; 
    width: 100%; 
    height: 350px; 
}

#slideshow > div { 
    position: absolute;
}

Upvotes: 2

Views: 286

Answers (2)

Joansy
Joansy

Reputation: 159

I discovered that my code will work the way I need if I add the same number of next/fadein/end sequences as photos I have. So, in this case, that's three, so I should have three next/fadein/ends before the appendTo.

This makes the transition to the next image fade, not jump.

    $("#slideshow > div:gt(0)").hide();

    setInterval(function() { 
        $('#slideshow > div:first')
        .fadeOut(5000)
        .next()
        .fadeIn(5000)
        .end()
        .next()
        .fadeIn(5000)
        .end()
        .next()
        .fadeIn(5000)
        .end()
        .appendTo('#slideshow');
    }, 5000);

Upvotes: 1

Hanzallah Afgan
Hanzallah Afgan

Reputation: 734

You just need to make the positions of your images absolute using CSS so that your images overlap on each other.

		$("#slideshow > div:gt(0)").hide();

		setInterval(function() { 
			$('#slideshow > div:first')
			.fadeOut(5000)
			.next()
			.fadeIn(5000)
			.end()
			.appendTo('#slideshow');
		}, 5000);
		#slideshow > div > img{
			Width: 100px; 
			height: 100px;
			position: absolute;
		}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
	<div id="slideshow">
		<div>
			<img src="http://avatarmaker.net/free-avatars/avatars/nature_217/plants_276/pinapple_fruit_avatar_100x100_70415.jpg" alt="Img 1">
		</div>
		<div>
			<img src="http://avatarmaker.net/free-avatars/avatars/nature_217/plants_276/big_fruit_avatar_100x100_94646.jpg" alt="Img 2">
		</div>
		<div>
			<img src="http://www.dhresource.com/albu_590477479_00/1.thumb.jpg" alt="Img 3">
		</div>
    </div>

Upvotes: 3

Related Questions