samedi 18 juin 2016

parallax.js change image every X seconds with jQuery

I've been trying to figure out the best way to change the image of my parallax.js div. I'm using parallax.js by Mike Greiling at http://pixelcog.github.io/parallax.js/

I'm trying to alter the div attribute 'data-img-src' every X seconds. All files are being correctly loaded.

I have this in my js file:

var images = [];
images[0] = "img/van2-unsplash.jpg";
images[1] = "img/van3-unsplash.jpg";
images[2] = "img/van4-unsplash.jpg";
images[3] = "img/van5-unsplash.jpg";
images[4] = "img/van6-unsplash.jpg";
var i = 0;
setInterval(fadePhoto, 3000);
function fadePhoto() {
    i = i < images.length ? i : 0;
    $('.parallax-window').fadeOut(200, function() {
        $('.parallax-window').attr('data-image-src', images[i]).fadeIn(200);
    });
    i++;
};

And this is the html:

<div id="parallax-hero" class="col-xs-12 parallax-window" data-parallax="scroll" data-image-src="img/van1-unsplash.jpg">

I am observing in dev tools that the attribute 'data-image-src' is changing to what it's supposed to be, yet nothing is happening visually on the page.

UPDATE 1 The text was also fading in and out but I fixed that by wrapping the '.parallax-window' and my '.parallax-text' (which had h1 and h2 tags in it) and separating the text from the parallax-window div. Not sure why I thought the text wouldn't fade in and out if I told it's parent div to fade in and out..

Updated html:

<div class="parallax-wrapper col-xs-12">
    <div id="parallax-hero" class="col-xs-12 parallax-window" data-parallax="scroll" data-image-src="img/van1-unsplash.jpg"></div>
    <div class="parallax-text">
        <h1>TEXT</h1>
        <h2>TEXT</h2>
    </div>
</div>

UPDATE 2: I also saw in dev tools that there was an element with the class name 'parallax-slider' that held a 'src' attribute so I removed

$('.parallax-window').attr('data-image-src', images[i]).fadeIn(200);

and added:

$('.parallax-slider').attr('src', images[i]).fadeIn(200);

To my fadeOut and now the image changes.

The main problem now is that the image does not fadeIn or fadeOut it just changes suddenly every 3 seconds. I changed fadeIn and fadeOut to 1000 just in case, but it didn't change anything.

Aucun commentaire:

Enregistrer un commentaire