I'm trying to learn jquery and I want to create fadein and fadeout effect which loops through image. I have used setInterval function to loop through images but it works only for first iteration.
$(document).ready(function() {
var newcount = 0;
var image = $(".image-store img");
image.hide();
var image_array = [];
image.each(function() {
image_array.push($(this).attr('src'));
});
var showimg = $(".image-disp img");
showimg.attr("src", image_array[newcount]);
setInterval(function() {
showimg.fadeOut(2000, function() {
newcount = newcount + 1;
showimg.attr("src", image_array[newcount]);
showimg.fadeIn(2000);
});
if (newcount == image_array.length) {
newcount = -1;
}
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image-store">
<img src="img/img1.jpg">
<img src="img/img2.jpg">
<img src="img/img3.jpg">
</div>
<div class="image-disp">
<img src="">
</div>
It works, but you're missing }); at the end of the code. Use the browser console to know if there is any error.
$(document).ready(function() {
var newcount = 0;
var image = $(".image-store img");
image.hide();
var image_array = [];
image.each(function() {
image_array.push($(this).attr('src'));
});
var showimg = $(".image-disp img");
showimg.attr("src", image_array[newcount]);
setInterval(function() {
showimg.fadeOut(2000, function() {
newcount = newcount + 1;
showimg.attr("src", image_array[newcount]);
showimg.fadeIn(2000);
});
if (newcount == image_array.length) {
newcount = -1;
}
}, 3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image-store">
<img width="50" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
<img width="50" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>
<div class="image-disp">
<img width="200" src="">
</div>
Related
I have this slideshow JS code that switches images in a div depending on the time we want. However, how can I add a fade in/fade out effect instead of a basic transition with no animation? I am doing this without jQuery, just plain javascript. Here is the link: https://en.khanacademy.org/computer-programming/js-library-exatreojs-slideshow-library/2950604004
here is the code:
var slideShow = function(container, time) {
container = document.getElementById(container);
this.images = [];
this.curImage = 0;
for (i = 0; i < container.childElementCount; i++) {
this.images.push(container.children[i]);
this.images[i].style.display = "none";
}
// Handle going to to the next slide
var nextSlide = function() {
for (var i = 0; i < this.images.length; i++) {
this.images[i].style.display = "none";
}
this.images[this.curImage].style.display = "block";
this.curImage++;
if (this.curImage >= this.images.length) {
this.curImage = 0;
}
window.setTimeout(nextSlide.bind(document.getElementById(this)), time);
// old code: window.setTimeout(nextSlide.bind(this), time);
};
nextSlide.call(this);
};
slideShow("slideshow", 1000);
// old code: slideShow(document.getElementById("slideshow"), 1000);
<div id="slideshow">
<img src="https://www.kasandbox.org/programming-images/animals/birds_rainbow-lorakeets.png" alt="Rainbow lorakeets" />
<img src="https://www.kasandbox.org/programming-images/animals/butterfly.png" alt="Butterfly" />
<img src="https://www.kasandbox.org/programming-images/animals/cat.png" alt="Cat" />
<img src="https://www.kasandbox.org/programming-images/animals/crocodiles.png" alt="Crocodiles" />
<img src="https://www.kasandbox.org/programming-images/animals/fox.png" alt="Fox" />
</div>
You could try this method, if you don't mind that display is always block and I just change opacity of image. So the container has to be relatively positioned and imgs should be absolute
var slideShow = function(container, time) {
container = document.getElementById(container);
this.images = [];
this.curImage = 0;
for (i = 0; i < container.childElementCount; i++) {
this.images.push(container.children[i]);
this.images[i].style.opacity = 0;
}
// Handle going to to the next slide
var nextSlide = function() {
for (var i = 0; i < this.images.length; i++) {
if (i!=this.curImage) this.images[i].style.opacity = 0;
}
this.images[this.curImage].style.opacity = 1;
this.curImage++;
if (this.curImage>=this.images.length) this.curImage=0;
window.setTimeout(nextSlide.bind(document.getElementById(this)), time);
// old code: window.setTimeout(nextSlide.bind(this), time);
};
nextSlide.call(this);
};
slideShow("slideshow", 1000);
// old code: slideShow(document.getElementById("slideshow"), 1000);
img {
transition: opacity 0.5s;
position:absolute;
top:0;
}
<div id="slideshow">
<img src="https://www.kasandbox.org/programming-images/animals/birds_rainbow-lorakeets.png" alt="Rainbow lorakeets" />
<img src="https://www.kasandbox.org/programming-images/animals/butterfly.png" alt="Butterfly" />
<img src="https://www.kasandbox.org/programming-images/animals/cat.png" alt="Cat" />
<img src="https://www.kasandbox.org/programming-images/animals/crocodiles.png" alt="Crocodiles" />
<img src="https://www.kasandbox.org/programming-images/animals/fox.png" alt="Fox" />
</div>
I have this snipped made by gilly3 (special thanks).
Is there any possibility to define and apply the desired number of cycles? As we can see, the code will repeat the sequences.
onload = function startAnimation() {
var frames = document.getElementById("animation").children;
var frameCount = frames.length;
var i = 0;
setInterval(function () {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
}, 100);
}
#animation img {
display: none;
}
#animation img:first-child {
display: block;
}
<div id="animation">
<img src="https://40.media.tumblr.com/fd2e0116f31a0fcdc8f3531dcaaa90dc/tumblr_o0w5avLZFM1rpy0r6o1_540.jpg" />
<img src="https://41.media.tumblr.com/13699ab5ac456da7712fae015ba3a7a5/tumblr_np0yulyrtz1tn6jt3o1_540.jpg" />
<img src="https://41.media.tumblr.com/6f0cea1195cfd37d468dcd51cb8ca5be/tumblr_nz0hywwevQ1s0x1p3o1_r2_540.jpg" />
<img src="https://40.media.tumblr.com/cfa4f49cfcd79b0afa997d9fb746d93e/tumblr_o0kwteTCVD1qzqavpo1_540.jpg" />
<img src="https://40.media.tumblr.com/81b9d21f1b15584cd75be63e3388aa15/tumblr_ni0eqtik0P1qgwfzao1_540.jpg" />
<img src="https://36.media.tumblr.com/605ce3769d8ca286454f1355749aead2/tumblr_ntx88hD8rP1spnyg9o1_500.jpg" />
<img src="https://40.media.tumblr.com/125a40e474d2d4a8eea6e0a28e24df83/tumblr_o11pefcs5m1sh1x48o1_540.jpg" />
<img src="https://41.media.tumblr.com/bb8ab516d0495bfc35e2413611472daa/tumblr_nycp9fWVTc1qcr6iqo1_540.jpg" />
</div>
I have to recognise that I've received a sugestion:
"setInterval returns an interval id. Store that id in a variable and, when you want to stop the animation, pass the id to clearInterval()" but it will be much appreciated a code update (I don't know how to write this in js).
You could do something like this where you clear the interval once it's run a certain number of times:
onload = function startAnimation() {
var frames = document.getElementById("animation").children;
var frameCount = frames.length;
var i = 0;
var numberOfCycles = 10; // Set this to whatever you want
var myInterval = setInterval(function () {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
if (i === numberOfCycles * frameCount) {
clearInterval(myInterval);
}
}, 100);
}
This requires the least code mutation, but you could also do something similar with setTimeout's.
Snippet here:
onload = function startAnimation() {
var frames = document.getElementById("animation").children;
var frameCount = frames.length;
var i = 0;
var numberOfCycles = 3; // Set this to whatever you want
var myInterval = setInterval(function () {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
if (i === numberOfCycles * frameCount) {
clearInterval(myInterval);
}
}, 100);
}
#animation img {
display: none;
}
#animation img:first-child {
display: block;
}
<div id="animation">
<img src="https://40.media.tumblr.com/fd2e0116f31a0fcdc8f3531dcaaa90dc/tumblr_o0w5avLZFM1rpy0r6o1_540.jpg" />
<img src="https://41.media.tumblr.com/13699ab5ac456da7712fae015ba3a7a5/tumblr_np0yulyrtz1tn6jt3o1_540.jpg" />
<img src="https://41.media.tumblr.com/6f0cea1195cfd37d468dcd51cb8ca5be/tumblr_nz0hywwevQ1s0x1p3o1_r2_540.jpg" />
<img src="https://40.media.tumblr.com/cfa4f49cfcd79b0afa997d9fb746d93e/tumblr_o0kwteTCVD1qzqavpo1_540.jpg" />
<img src="https://40.media.tumblr.com/81b9d21f1b15584cd75be63e3388aa15/tumblr_ni0eqtik0P1qgwfzao1_540.jpg" />
<img src="https://36.media.tumblr.com/605ce3769d8ca286454f1355749aead2/tumblr_ntx88hD8rP1spnyg9o1_500.jpg" />
<img src="https://40.media.tumblr.com/125a40e474d2d4a8eea6e0a28e24df83/tumblr_o11pefcs5m1sh1x48o1_540.jpg" />
<img src="https://41.media.tumblr.com/bb8ab516d0495bfc35e2413611472daa/tumblr_nycp9fWVTc1qcr6iqo1_540.jpg" />
</div>
This the html:
<div id = "slideshow">
<div id="slideshowWindow">
<div class="slide"><img src="slideshow.jpg" alt="" /></div>
<div class="slide"><img src="DSC_8185.jpg" alt="" /></div>
<div class="slide"><img src="DSC_8211.jpg" alt="" /></div>
<div class="slide"><img src="OrganicSoilad.jpg" alt="" /></div>
<div class="slide"><img src="DSC_8243.jpg" alt="" /></div>
<input style = "display: none;" value = "" id="hide"/>
</div>
Everything seems to work fine except for the prev() button. It just bugs out if you click it more than once. It gets all buggy. I'm relatively new to jquery and if anyone has any insight on how to stop the slider from sliding while on hover that would also be helpful.
the javascript:
$(document).ready(function() {
$(".content").mouseenter(function(){
$( ".arrows" ).fadeIn(100);
});
$('.content').mouseleave(function(){
$( ".arrows" ).fadeOut(700);
});
var currentPosition = 0;
var $hide = $('#hide');
$hide.val(currentPosition);
var slideWidth = 1140;
var slides = $('.slide'); var numberOfSlides = slides.length; var slideShowInterval;
var speed = 5000; slideShowInterval = setInterval(changePosition, speed);
slides.wrapAll('<div id="slidesHolder"></div>');
slides.css({ 'float' : 'left' });
$('#slidesHolder').css('width', slideWidth * numberOfSlides);
function changePosition() {
currentPosition = $('#hide').val();
if(currentPosition == numberOfSlides - 1)
{
currentPosition = 0; $hide.val(currentPosition);
} else {
currentPosition++; $hide.val(currentPosition);
}
moveSlide();
}
function moveSlide() {
$current = $('#slidesHolder').css('padding-left');
$current_num = $current.replace('px' , '');
$padding = $current_num;
$('#slidesHolder').animate({'paddingLeft': $padding});
/* alert($padding); */
/*alert($('#slidesHolder').css('padding-left')); */
$('#slidesHolder').animate({'marginLeft' : slideWidth*(-currentPosition)});
$('#media').html(currentPosition);
}
});
function next()
{
currentPosition = $('#hide').val();
slideWidth = 1140;
++currentPosition; if(currentPosition > 4){currentPosition =0;}
$('#slidesHolder').animate({'marginLeft' : slideWidth*(-currentPosition)});
$('#hide').val(currentPosition)
$('#media').html(currentPosition);
}
function prev()
{
currentPosition = $('#hide').val();
slideWidth = 1140;
$left = 1140;
if(currentPosition == 0)
{
currentPosition = 5;
}
else
{
if($('#slidesHolder').css('padding-left') == '1140px')
{
$left = $left + $left;
}
$('#hide').val(currentPosition);
$('#slidesHolder').animate({'paddingLeft' : $left});
if(currentPosition == 0)
{
currentPosition = 4;
}
else{
--currentPosition;
}
$('#hide').val(currentPosition);
$('#media').html(currentPosition);
}
}
Is there a way to make a function RandomSwapDown(x) randomly so that it shows one of the three images every time you click on it?
Thank you.
<script>
function RandomSwapDown(x) {
x.src = '4.gif';
}
function SwapBack(x) {
x.src = 'mouse_over.png';
}
function SwapOut(x) {
x.src = 'mouse_normal.png';
}
</script>
</html>
<div style='top: 200px; left: 175px; position: absolute;'>
<img src='mouse_normal.png' onMouseOver='SwapBack(this)' onMouseOut= 'SwapOut(this)' onMouseDown = 'RandomSwapDown(this)' width="121" height="146" >
<img src='mouse_normal.png' onMouseOver='SwapBack(this)' onMouseOut= 'SwapOut(this)' onMouseDown = 'RandomSwapDown(this)' width="121" height="146" >
<img src='mouse_normal.png' onMouseOver='SwapBack(this)' onMouseOut= 'SwapOut(this)' onMouseDown = 'RandomSwapDown(this)' width="121" height="146" >
</div>
DEMO
var picArr = []; // array of images to choose from
function RandomSwapDown(x) {
x.src = picArr[Math.floor(Math.random()*3)];
}
function SwapBack(x) {
x.src = picArr[Math.floor(Math.random()*3)];
}
function SwapOut(x) {
x.src = picArr[Math.floor(Math.random()*3)];
}
hi i don't now you can use this in javascript but in java you can
Random generator=new Random();
int rnd_number;
rnd_number=generator.nextInt(MaxRandom-MinRandom)+MinRandom;
I am trying to display 1 image after another in IE Mobile. The following code works in IE Desktop but I get an [Object error] If I run it in IE Mobile.
This is the code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var interval = 30;
var _timer;
var _index = 0;
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="#" title="Play Motion Clip from Beginning" onclick="test();">
<img alt="Play Motion" src="../Images/play_green_controls.png" style="border-style: none; width: 32px; height: 32px; background-color: #000000; cursor: pointer;" id="btnPlay" />
</a>
<img alt="" src="../0000.jpg" id="imgLive" />
<div id="divImage" style="width: 352px; height: 288px; display: none; background-image: url('Portal/Catalogues/000EC902F17F/3/2013/10/6/10/60b01a71-27f9-4122-ae8e-674e65a8b4dd/20131006102041027x75x0.04x0.40x.img00001.jpg');
background-repeat: no-repeat;">
</div>
<div id="divImageCache1" style="width: 352px; height: 288px; display: none;">
<img alt="" src="../0000.jpg" id="imgCached" />
</div>
</div>
</form>
<script type="text/javascript">
function test() {
try {
_timer = setInterval(swapImages(), interval);
}
catch (e) {
alert(e);
}
}
var imgCached = document.getElementById('imgCached');
var imgLive = document.getElementById('imgLive');
function OnImgLoaded() {
imgLive.src = imgCached.src;
}
function swapImages() {
imgCached.onload = OnImgLoaded();
imgCached.src = 'my irl/' + '0000' + _index + '.jpg';
_index = _index + 1;
if (_index == 10) {
_index = 0;
clearTimeout(_timer);
}
}
</script>
</body>
</html>
To debug I changed the javascript to this:
<script type="text/javascript">
function test() {
try {
alert('hi1');
_timer = setInterval(swapImages(), interval);
alert('hi2');
}
catch (e) {
alert(e);
}
}
var imgCached = document.getElementById('imgCached');
var imgLive = document.getElementById('imgLive');
function OnImgLoaded() {
imgLive.src = imgCached.src;
}
function swapImages() {
alert('hi3');
imgCached.onload = OnImgLoaded();
imgCached.src = 'http://www.url.co.uk/Cloud/test/' + '0000' + _index + '.jpg';
_index = _index + 1;
if (_index == 10) {
_index = 0;
clearTimeout(_timer);
}
alert('hi4');
}
</script>
What happened was that I got 'hi1', 'hi3', 'hi4' then object error. the image DID change once.
You are not assining a function to setInterval, you are calling the function and assigning what every it returns.
Your code
_timer = setInterval(swapImages(), interval);
is actually doing this
_timer = setInterval(undefined, interval);
Your code needs to drop the () so you are not calling the function.
_timer = setInterval(swapImages, interval);
You also did it here:
imgCached.onload = OnImgLoaded();
Personally I would not use an interval, your images are NOT going to load in 30 ms. You a timeout after the images are loaded. Something like this would work.
var isRunning,
timer,
intervalMS = 30,
imgLive = document.getElementById('imgLive');
function test() {
_index = 0;
isRunning = true;
if (timer) window.clearTimeout(timer);
swapImages();
}
function setImageSrc (src) {
imgLive.src = src;
if(isRunning) timer = window.setTimeout(swapImages, intervalMS);
}
function swapImages() {
var imgCached = new Image();
imgCached.onload = function() {
setImageSrc(this.src);
};
imgCached.onerror = function() {
setImageSrc("Error.jpg");
};
imgCached.src = 'http://www.informedmotion.co.uk/Cloud/test/' + '0000' + _index + '.jpg';
_index = _index + 1;
if (_index == 10) {
isRunning = false;
}
}