javascript - Adding fade function to JS script? -
so have basic script alternates between 3 images , i'd add simple fadein/fadeout/fadeto or whatever looks best it's not clunky. how can achieve this? or, there better way?
function displaynextimage() { x = (x === images.length - 1) ? 0 : x + 1; document.getelementbyid("img").src = images[x]; } function displaypreviousimage() { x = (x <= 0) ? images.length - 1 : x - 1; document.getelementbyid("img").src = images[x]; } function starttimer() { setinterval(displaynextimage, 3000); } var images = [], x = -1; images[0] = "assets/img/logo1.png"; images[1] = "assets/img/logo2.png"; images[2] = "assets/img/logo3.png";
you can set opacity of images before change src:
function displaynextimage() { x = (x === images.length - 1) ? 0 : x + 1; var imgvar = document.getelementbyid("img"); imgvar.classlist.add("fadeout"); settimeout(function() { imgvar.src = images[x]; imgvar.classlist.remove("fadeout"); }, 500); } function displaypreviousimage() { x = (x <= 0) ? images.length - 1 : x - 1; var imgvar = document.getelementbyid("img"); imgvar.classlist.add("fadeout"); settimeout(function() { imgvar.src = images[x]; imgvar.classlist.remove("fadeout"); }, 500); } function starttimer() { setinterval(displaynextimage, 3000); } var images = [], x = -1; images[0] = "assets/img/logo1.png"; images[1] = "assets/img/logo2.png"; images[2] = "assets/img/logo3.png";
and in css:
img { opacity: 1; transition: opacity 500ms ease-in-out; } img.fadeout { opacity: 0; }
note: added 500ms timeout in javascript because suspect otherwise animation wouldn't visible @ because instantly go visible invisible visible again.
wiki
Comments
Post a Comment