javascript setinterval using if condition showing images - javascript

I need to show three images one by one with using javascript setinterval function can you please any one help me.
Bellow is my html code.
<div class="imageHolder">
<img src="http://lorempixel.com/400/200/sports/" style="display:none;" class="image1" border="0" />
<img src="http://lorempixel.com/400/200/sports/1" style="display:none;" class="image2" border="0" />
<img src="http://lorempixel.com/400/200/" style="display:none;" class="image3" border="0" />
</div>

<head>
<script type="text/javascript">
function start() {
var images = document.querySelectorAll('.imageHolder img');
var images_count = images.length;
var image_index = false;
var delay = 3000; // 3 seconds delay
function animateImageHolder() {
if (false !== image_index) {
images[image_index].style = 'display:none';
image_index++;
image_index = (image_index < images_count ? image_index : 0);
} else {
image_index = 0;
}
images[image_index].style = 'display:inline';
}
animateImageHolder();
setInterval(animateImageHolder, delay);
}
</script>
</head>
<body onload="start()">
<!-- ... -->

This question is pretty much like "do my job for me" but you are honest in your english.
You did not say how long each image should be visible so I set it to 3 seconds (interval = 3000).
I recommend you to set the style attribute of the first image to be style="display:block" and the rest to style="display:none".
function slider(element) {
var next_image = 0
, interval = 3000
, images = Array.prototype.filter.call(element.children, function(child) {
return child.tagName === "IMG";
})
;
setInterval(function() {
images.forEach(function(image, i) {
image.style.display = i === next_image ? "block" : "none";
})
next_image = (next_image + 1) % images.length;
}, interval);
}
slider(document.querySelector("div.imageHolder"))

Related

Need to cycle images with setInterval ( ) using start and stop buttons. (only using javascript0

Sorry for being a total newb. This is my 1st week on this javascript crashcourse and I know noobs are annoying as hell. Anyway, I couldn't get your suggestions to work. I tried some different things and got it to work, but now, once I press "Stop Slideshow," I can't get the slideshow to start again from where it left off (or at all). Any ideas?
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<img src="http://joemiller.us/wp-content/uploads/beautiful-birds-wallpapers_blue-bird-wallpaper-free.jpg" alt="Birds" id="image" style="height: 200px; width: 200px">
<br>
<button type="button" onclick="startShow()">Start Slideshow</button>
<button type="button" onclick="stopShow()">Stop Slideshow</button>
</div>
<script>
var images = [
'http://joemiller.us/wp-content/uploads/beautiful-birds-wallpapers_blue-bird-wallpaper-free.jpg',
'http://www.hgsitebuilder.com/files/writeable/uploads/hostgator172932/image/exoticbirds2.jpg',
'http://melleum.com/data/uploads/6/280423-birds.jpg',
'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTBew8yyadE865lI-dSdg2XgNIREm1RZVhQpzjN3HzmmLwuR0_j',
'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSvo3Aew9HAc2PXVaHz9ghtr-_F9D7ZqySzRLbvPwG6mzmMsBaVHQ'
];
var img = document.getElementById('image');
var i = 0;
var start = setInterval("cycleImages ()", 3000);
function cycleImages () {
if (i < images.length-1) {
i++;
} else {
i=0;
}
img.src = images[i];
}
function startShow () {
start;
}
function stopShow () {
clearInterval(start);
}
</script>
</body>
</html>
Despite you appearing to be a bit of a giverupper, here's one way of doing it:
var images = [
'http://joemiller.us/wp-content/uploads/beautiful-birds-wallpapers_blue-bird-wallpaper-free.jpg',
'http://www.hgsitebuilder.com/files/writeable/uploads/hostgator172932/image/exoticbirds2.jpg',
'http://upic.me/i/z2/birds-bird_928268.jpg',
'http://melleum.com/data/uploads/6/280423-birds.jpg',
'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTBew8yyadE865lI-dSdg2XgNIREm1RZVhQpzjN3HzmmLwuR0_j',
'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSvo3Aew9HAc2PXVaHz9ghtr-_F9D7ZqySzRLbvPwG6mzmMsBaVHQ'
];
var imageIndex = 0;
var delay = 1000;
var slideshowImage = document.getElementById('slideshow-image');
var startButton = document.getElementById('start');
var stopButton = document.getElementById('stop');
var timer;
startButton.addEventListener('click', start);
stopButton.addEventListener('click', stop);
function start() {
clearInterval(timer);
slideshowImage.setAttribute('src', images[imageIndex]);
timer = setInterval(function () {
imageIndex = imageIndex >= (images.length - 1) ? 0 : ++imageIndex;
slideshowImage.setAttribute('src', images[imageIndex]);
}, delay);
}
function stop() {
clearInterval(timer);
}
#slideshow-image {
max-width: 320px;
}
<div class="controls">
<button id="start">Start</button>
<button id="stop">Stop</button>
</div>
<img id="slideshow-image" src="">
You could use a function*'s next in a setInterval's function after the element <img src="" id="image" /> exists,
var tag = document.getElementById('image'),
srcs = ['http://google.com/favicon.ico', 'http://www.yahoo.com/favicon.ico', 'http://www.bing.com/favicon.ico'];
function* loop(tag, srcs) {
var i = 0;
while (1) {
yield tag.src = srcs[i++ % srcs.length];
}
}
var gen = loop(tag, srcs);
setInterval(gen.next.bind(gen), 500);
DEMO

Radio Button and Image-Slider

I made an Image-Slider based on Radio Buttons (thanks to some advice of user A.V) as you can see here:
Now, there is one last thing that I would love to do but I have no idea how. I would like to be able to switch to the next image by clicking on the image itself (of course with the selection jumping to the next button, too).
Would be awesome if someone could help. Thanks in advance!
JSFiddle
http://jsfiddle.net/v4phdL3p/8/
Add class "sliderImage" to your image placeholders and then use this code:
$(".sliderImage").click(function(){
var name = $(this).attr("name")
var selector = "input[checked][name='" + name +"']"
currrentRadio = $(selector)
currrentRadio.removeAttr("checked")
if (currrentRadio.next().attr("name") === name) {
currrentRadio.next().attr('checked', 'checked').prop("checked",true).trigger("click")
} else {
var nextRadio = "input[name='" + name + "']"
firstRadio = $(nextRadio)[0]
$(firstRadio).attr('checked', 'checked').prop("checked",true).trigger("click")
}
})
*EDIT* change changeImage to this (to allow clicking of object to not affect functionality):
Here is the working fiddle:
http://jsfiddle.net/xhmrwhtv/3/ **NEW modified Working Fiddle**
function changeImage(imgName, obj)
{
image = document.getElementById(obj.name);
image.src = imgName;
var name = obj.name;
var selector = "input[checked][name='" + name +"']";
currrentRadio = $(selector);
currrentRadio.removeAttr("checked");
$(obj).attr('checked', 'checked').prop("checked",true).trigger("click");
}
Have you tought about a simple JavaScript or jQuery script? This would not be hard to do, here is an example:
jQuery:
function slideSwitch() {
var $active = $('#slideshow IMG.active');
if ($active.length == 0) $active = $('#slideshow IMG:last');
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
$active.addClass('last-active');
$next.css({ opacity: 0.0 })
.addClass('active')
.animate({ opacity: 1.0 }, 1000, function () {
$active.removeClass('active last-active');
});
}
$(function () {
setInterval("slideSwitch()", 3000);
});
html:
<div style="width: 100%; position: absolute; margin-top:5%;">
<div id="slideshow" style="display: inline-block; position:relative;">
<img src="pictures/coinWars/1.jpg" class="active" />
<img src="pictures/coinWars/2.jpg" />
<img src="pictures/coinWars/3.jpg" />
<img src="pictures/coinWars/4.jpg" />
<img src="pictures/coinWars/5.jpg" />
<img src="pictures/coinWars/6.jpg" />
<img src="pictures/coinWars/7.jpg" />
<img src="pictures/coinWars/8.jpg" />
<img src="pictures/coinWars/9.jpg" />
<img src="pictures/coinWars/10.jpg" />
</div>
That will make a simple slide show of pictures, you can change it to allow it to change on click, instead on on the interval.
This is my code, but feel free to use it and modify it as necessary.
First change you function to access the name not the object
function changeImage(imgName, name)
{
image = document.getElementById(name);
image.src = imgName;
}
Then then add to img onclick:
<img src="http://placehold.it/100x100" name="image1" id="image1" onclick="changeImageClick(1);"><br>
Then I added variables (just for the first set of changes:
var images1 = ["http://placehold.it/100x100","http://placehold.it/200x200","http://placehold.it/300x300"];
var images1num = 0;
images1num is for what current image src you are on. Starting at 0 to 2.
Then you have to modify the radio buttons onclick to:
changeImage('http://placehold.it/200x200','image1'); images1num = 1;
Here is the function:
function changeImageClick(num)
{
if(num == 1)
{
images1num = (images1num + 1) % images1.length;
changeImage(images1[images1num],'image1');
var input = document.getElementsByTagName('input');
var nextInput = false;
for(var i = 0; i < input.length; i++)
{
if(input[i].checked == true && input[i].name == 'image1')
{
nextInput = true;
if(nextInput)
{
input[(i+1)%images1.length].click();
nextInput = false;
break;
}
}
}
}
}
Again this is only for your 100x100,200x200,300x300 but the concept works for all 3.
Here is JSFiddle: http://jsfiddle.net/v4phdL3p/44/
Replicating the other two sliders is a good learning experience.
There are many javaScript sliders. You just need to search google to get your answer. However, following code may be helpful.
Working Fiddle....
<img id = "img" src = "http://www.menucool.com/slider/prod/image-slider-1.jpg" width = 200; onclick = "changeImage()">
<br>
<input type="radio" name = "rdo" id = "radio1" onclick = "changeSlide(this)" checked />
<input type="radio" name = "rdo" id = "radio2" onclick = "changeSlide(this)"/>
<input type="radio" name = "rdo" id = "radio3" onclick = "changeSlide(this)"/>
JavaScript:
function changeImage(){
if(document.getElementById("img").src == "http://www.menucool.com/slider/prod/image-slider-1.jpg" ){
document.getElementById("img").src = "http://www.menucool.com/slider/prod/image-slider-3.jpg";
document.getElementById("radio2").checked = true;
}
else if(document.getElementById("img").src == "http://www.menucool.com/slider/prod/image-slider-3.jpg"){
document.getElementById("img").src ="http://www.userinterfaceicons.com/80x80/minimize.png";
document.getElementById("radio3").checked = true;
}
else if(document.getElementById("img").src == "http://www.userinterfaceicons.com/80x80/minimize.png"){
document.getElementById("img").src = "http://www.menucool.com/slider/prod/image-slider-1.jpg";
document.getElementById("radio1").checked = true;
}
}
function changeSlide(id){
if(document.getElementById("radio1")==id){
document.getElementById("img").src = "http://www.menucool.com/slider/prod/image-slider-1.jpg";
}
else if(document.getElementById("radio2")==id){
document.getElementById("img").src = "http://www.menucool.com/slider/prod/image-slider-3.jpg";
}
else if(document.getElementById("radio3")==id){
document.getElementById("img").src ="http://www.userinterfaceicons.com/80x80/minimize.png";
}
}

jquery fade in images

I am trying to fade in and out images with jquery but it's not working, I am missing something out.
see the script below:
var count = 1;
setInterval(function() {
count = (jQuery(".slideshow :nth-child("+count+")").fadeOut().next().length == 0) ? 1 : count+1;
//alert (count);
jQuery(".slideshow :nth-child("+count+")").fadeIn();
}, 2000);
And here is the HTML code.
<div class="slideshow">
<div class="hover">
<a href="#">
<img src="#" />
<div class="mainportfo_title">title</div>
</a>
</div>
<div class="hover">
<a href="#">
<img src="#" />
<div class="mainportfo_title">title</div>
</a>
</div>
</div>
You can use JQuery get() and works on this code, taht is definitely improvable:
var i = 0;
setInterval(function() {
var target = $("img").get(i);
var next = $("img").get(++i);
$(target).fadeIn( "slow", function() {
$(target).fadeOut( "slow", function() {
$(next).fadeIn();
});
});
if(i >= $("img").size()) {
i = 0;
}
}, 3000);
do you want to do this?: jsfiddle demo
var count = 1;
setInterval(function() {
count = (jQuery(".slideshow:nth-child("+count+")").fadeOut().next().length == 0) ? 1 : count+1;
jQuery(".slideshow:nth-child("+count+")").fadeIn();
}, 2000);
You have to target your .hover elements otherwise the .nth-child will select the wrong element.
var count = 1;
setInterval(function () {
count = ($(".slideshow .hover:nth-child(" + count + ")").fadeOut().next().length == 0) ? 1 : count + 1;
console.log(count);
$(".slideshow .hover:nth-child(" + count + ")").fadeIn();
}, 2000);
fiddle

Slider image id

I have a small problem with a small jQuery script that my slide images. The script itself works very well, its purpose being to scroll through the images indeed "fade", a classic.
The problem is that if I want to use it for another block on the page, well it no longer works properly .. The problem is certainly located at the id, but can not make it work.
Here is the script:
function slider() {
function animate_slider(){
$('.slider #'+shown).animate({
opacity:0 // fade out
},1000);
$('.slider #'+next_slide).animate({
opacity:1.0 // fade in
},1000);
//console.log(shown, next_slide);
shown = next_slide;
}
function choose_next() {
next_slide = (shown == sc)? 1:shown+1;
animate_slider();
}
$('.slider #1').css({opacity:1}); //show 1st image
var shown = 1;
var next_slide;
var sc = $('.slider img').length; // total images
var iv = setInterval(choose_next,3500);
$('.slider_nav').hover(function(){
clearInterval(iv); // stop animation
}, function() {
iv = setInterval(choose_next,3500); // resume animation
});
$('.slider_nav span').click(function(e){
var n = e.target.getAttribute('class');
//console.log(e.target.outerHTML, n);
if (n=='prev') {
next_slide = (shown == 1)? sc:shown-1;
} else if(n=='next') {
next_slide = (shown == sc)? 1:shown+1;
} else {
return;
}
animate_slider();
});
}
window.onload = slider;
Any idea ? Thank you all :)
i am not sure of what u want to do, but if you want reusibality :
EDIT : i ve modified assuming that your 2 slides are independant
this is a quick solution, as mentioned #David Barker, it would be more clean to do a jQuery plugin
JS :
var sliderTop = "#slider.top";
var sliderBottom = "#slider.bottom";
function slider(el) {
function animate_slider(el){
$(el + shown).animate({
opacity:0 // fade out
},1000);
$(el + next_slide).animate({
opacity:1.0 // fade in
},1000);
//console.log(shown, next_slide);
shown = next_slide;
}
function choose_next(el) {
next_slide = (shown == sc)? 1:shown+1;
animate_slider(e);
}
$(el + ' #1').css({opacity:1}); //show 1st image
var shown = 1;
var next_slide;
var sc = $(el + ' img').length; // total images
var iv = setInterval(choose_next,3500);
$(el + '_nav').hover(function(){
clearInterval(iv); // stop animation
}, function() {
iv = setInterval(choose_next,3500); // resume animation
});
$(el + '_nav span').click(function(e){
var n = e.target.getAttribute('class');
//console.log(e.target.outerHTML, n);
if (n=='prev') {
next_slide = (shown == 1)? sc:shown-1;
} else if(n=='next') {
next_slide = (shown == sc)? 1:shown+1;
} else {
return;
}
animate_slider(el);
});
}
window.onload = function() {
slider(sliderTop);
slider(sliderBottom);
}
HTML :
<div id="slider" class="top">
<h2>Nos partenaires</h2>
<img id="1" src="" alt="">
<img id="2" src="" alt="">
<img id="3" src="" alt="">
</div>
<div class="slider_nav">
<span class="prev">Précédent</span><!--
--><span class="next">Suivant</span>
</div>
<div id="slider" class="bottom">
<h2>Nos partenaires</h2>
<img id="1" src="" alt="">
<img id="2" src="" alt="">
<img id="3" src="" alt="">
</div>
<div class="slider_nav">
<span class="prev">Précédent</span><!--
--><span class="next">Suivant</span>
</div>

Custom image shuffler not working?

Basically, what I'm trying to do is shuffle through images using some JavaScript code. All it does is change the display style of the current image to block, and at the same time change the previous one to none.
The HTML code:
<body>
<img src="http://bit.ly/yOqqbg" id="image1" style="display: block;">
<img src="http://bit.ly/dezBUZ" id="image2" style="display: none;">
<img src="http://bit.ly/IvM5HE" id="image3" style="display: none;">
</body>​
The JavaScript code:
var id = ["image1", "image2", "image3"]; //Array with the id's in the document you want
to shuffle through
var i = 0; //Set inital array element
initiateTimer(); //Get the loop going
function initiateTimer() {
if (i > id.length) {
i = 0;
initiateTimer();
}
setTimeout(function() { changeElement(); }, 2000); //2000 = 2 seconds
}
function changeElement() {
if (id === 0) {
document.getElementById(id[2]).style.display = 'none';
document.getElementById(id[i]).style.display = 'block';
} else {
document.getElementById(id[i - 1]).style.display = 'none';
document.getElementById(id[i]).style.display = 'block';
}
i += 1;
initiateTimer();
} ​
when i === 3 you will have problems
if (i > id.length) {
should become
if (i >= id.length) {
UPDATE: http://jsfiddle.net/HgNuc/

Categories

Resources