I want to replace the contents of a div with the values found in an array. I want to keep each value within the div for 3 seconds each. Here's my code so far:
var images = ['a.jpg', 'b.jpg', 'c.jpg'];
for (i = 0; i < images.length; i++) {
$('#slideShow').html("<img src='../"+images[i]+"' alt='' />");
}
This of course changes the images so fast that the human eye only sees one image being in the div at all times. I want to keep each image for 3 seconds before the next .html() is done on the div. How to do this?
Try this:
images = ["a.jpg", "b.jpg", "c.jpg"];
function change(i){
if(!images[i]){return false}
else{
$("#slideShow").src=images[i];
setTimeout( function(){ change(i+1) }, 3000);
}
}
change(0);
Haven't tested it but it should work.
This answer assumes that you want to loop. If not, comment and I'll rewrite.
<script>
var images = ['a.jpg', 'b.jpg', 'c.jpg'];
var curimage = 0;
function changeImage() {
$('#slideShow').html("<img src='../"+images[curimage]+"' alt='' />");
curimage++;
if (curimage > images.length) curimage = 0;
}
changeImage();
window.setInterval(changeImage, 3000);
</script>
I have tested this answer.
Related
I'm making an image carousel i'm bounded to use background-image property instead of using
<img src="Image">
tag. my carousel is working if I use img tag . But its not working when I use background-image property, how can I modify my code with background-image property.
see my fiddle :https://jsfiddle.net/korLasen/ and update it please thanks :)
or you can see code here
(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
function imageSliderSet(){
image.setAttribute('data-background', imageSet[index]);
index++;
if(index >= imageSet.length){
index = 0;
}
}
setInterval = (imageSliderSet, 2000);
})();
This is quite a strange question... however, I am not one to judge :)
Here is a jsfiddle based on your example. I ended up using jquery for this. I hope this is somewhere near what you were looking for!
This is based on changing every two seconds. To extend that, you can change line 18 in the jquery. Here is the jquery:
$( document ).ready(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
window.setInterval(function(){
image.css('background-image', "url('" + imageSet[index] + "')");
index++;
if(index >= imageSet.length){
index = 0;
}
//here you can adjust the time interval for each photo
}, 2000);
});
So basically i have made a PHP program that takes pictures from a folder and puts it into the "slideshow" in Gallery. The PHP code gives the images id's starting from "1" and so on.
Now with JavaScript i want it to automatically switch picture every 2,5 second. It actually runs as i want it to in my Firebug Script, but nothing happens in the browser. I already posted my JavaScript link in the bottom of the HTML body, and it doesn't help.
Any help would be appreciated.
<div id="gallery" class="grey">
<h3>Gallery</h3>
<div id="slideshow">
<?php
$path = "./img/gallery";
$all_files = scandir($path);
$how_many = count($all_files);
for ($i=2; $i<$how_many;$i++) {
$kubi=$i - 1;
echo "<img src=\"./img/gallery/$all_files[$i]\" id= \"$kubi\"/>";
}
?>
</div>
</div>
JavaScript code:
var picture = document.getElementById("1");
var i = 0;
function rotateImages() {
while (i < document.getElementById("slideshow").childNodes.length) {
picture.style.display = "none";
picture = picture.nextSibling;
picture.style.display = "inline";
i++;
};
};
window.onload = function(){
document.getElementById("1").style.display = "inline";
setInterval(rotateImages(), 2500);
};
What happens is that always uses the same first element picture, hides it and then shows the second image, it does not actually iterate through all the pictures.
In your code, picture always is the first element, next is always the second.
Also, it should not be a while loop since the callback is called once to change a picture, so change it to if, and reset to the first picture when it passes number of total elements.
It should be: (Javascript)
var firstPicture = document.getElementById("1");
var picture = firstPicture ;
var i = 0;
function rotateImages() {
// hide current element
picture.style.display = "none";
// choose who is the next element
if (i >= document.getElementById("slideshow").childNodes.length) {
i = 0;
picture = firstPicture;
} else {
picture = picture.nextSibling;
}
// show the next element
picture.style.display = "inline";
i++;
};
window.onload = function(){
var curImg = document.getElementById("1").style.display = "inline";
setInterval(rotateImages, 2500);
};
First Question on this site so I hope I do this right! I have a javascript function that I want to display an image (image1.jpg) when the page is loaded, and then every 2 seconds change the image by going through the loop. However only the first image is showing so it seems the JS function is not being called. Can anyone tell me if I am doing something wrong here because it looks fine to me so can't understand why it won't work. Thanks
<html>
<head>
<script type="text/javascript">
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var i = 1;
if(i>images.length-1){
this.src=images[0];
i=1;
}else{
this.src=images[i];
i++;
}
setTimeout("displayImages()", 2000);
}
</script>
</head>
<body onload="displayImages();">
<img id="myButton" src="image1.jpg" />
</body>
</html>
You need to move the line
var i = 1;
outside the displayImages -function or it will start from one each time!
EDIT: But using a global variable is not considered good practice, so you could use closures instead. Also as noted in other answers, you are referencing this which does not refer to the image object, so I corrected that as well as simplified the logic a bit:
<script type="text/javascript">
function displayImages( i ){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var img = document.getElementById('myButton');
img.src = images[i];
i = (i+1) % images.length;
setTimeout( function() { displayImages(i); }, 2000 );
}
</script>
<body onload="displayImages(0);">
You need the value of i to be available at each call, it can be kept in a closure using something like:
var displayImages = (function() {
var i = 0;
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
return function() {
document.getElementById('myButton').src = images[i++ % images.length];
setTimeout(displayImages, 2000);
}
}());
Also, since this isn't set by the call, it will default to the global/window object, so you need to get a reference to the image. That too could be held in a closure.
There are a couple of issues here that are stopping this from working.
First the var i = 1; needs to be moved outside the function to make the increment work. Also note that the first item in an array is 0, not 1.
Second you're using this to refer to change the image's src, but this is not a reference to the image. The best thing to do is use here is document.getElementById instead.
var i, button;
i = 0;
button = document.getElementById('myButton');
function displayImages() {
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if (i > images.length - 1){
button.src = images[0];
i = 0;
}
else{
button.src = images[i];
i++;
}
setTimeout(displayImages, 2000);
}
There's still some room for improvement and optimisation, but this should work.
You are reinitializing value of i every time, so change the following:
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if(!displayImages.i || displayImages.i >= images.length) displayImages.i = 0;
document.getElementById('myButton').src = images[displayImages.i];
displayImages.i++;
setTimeout(displayImages, 2000);
}
Functions are objects in JS and because of this:
you can pass them by reference and not as a string improving performance and readability
you can add fields and even methods to a function object like I did with displayImages.i
EDIT: I've realized that there was one more issue src was not being set for button.
Now I've fixed this and also made other improvements.
Here is the fiddle http://jsfiddle.net/aD4Kj/3/ Only image URLs changed to actually show something.
<script type="text/javascript">
var i = 1;
function displayImages(){
.......
........
Just make "i" Global. so that whenever displayImages being called it will not redefined to 1.
<html>
<head>
<script type="text/javascript">
var i = 1;
function displayImages() {
var images = ['img1.jpg', 'img2.jpg', 'img3.jpg'];
i++;
if (i > images.length - 1) {
i = 0;
}
$('#myButton').attr('src', images[i]);
setTimeout(displayImages, 2000);
}
</script></head>
<body onload="displayImages();">
<img id="myButton" src="img1.jpg" height="150px" width="150px"/>
</body>
</html>
Make i global.
here your are using displayImages() recursively and variable for index i. e i assign as local variable in function displayImages() , you need to assign it global variable i.e outside of the function also initialize it from i=0 as array index always start from 0,
your code become
var i = 0; // assign i global
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if(i>images.length-1){
document.getElementById('myButton').src=images[0]; //get img by id
i=0; // to get first image
}
else{
document.getElementById('myButton').src=images[i]; //get img by id
i++;
}
setTimeout("displayImages()", 2000);
}
This is my first ever question on here and I figure it must have a simple answer but it's frustrated me for a while, especially since I'm new to Javascript. So I have many images and would like to change to the next one by clicking on it on the webpage, starting with a certain image, obviously. Now I could do this with nested if else statements but if you have many images you get too many ones nested into each other and it can get too complex so I figured there must be a simpler way of doing it. Here's an example of the code I had:
function changeImage()
{
var image=document.getElementById("mainImage")
if (image.src.match("image1.jpg"))
{
image.src="image2.jpg";
}
else if (image.src.match("image2.jpg"))
{
image.src="image3.jpg";
}
else
{
if (image.src.match("image3.jpg"))
{
image.src="image4.jpg";
}
else
{
image.src="image1.jpg";
}
}
}
So you can see it's not the best way to do it. I tried to do it with a switch statement but I couldn't either (and would appreciate it if someone told me if it could be done with one and how). As a last try I tried this but for some reason it jumps from image1 to image4 at once:
function changeImage()
{
var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]
var myImage = document.getElementById("mainImage")
for (i=0; i < images.length; i++)
{
if (myImage.src.match(images[i]))
{
myImage.src = images[i+1]
}
}
}
So I could really appreciate some help. Thanks in advance.
Your last changeImage goes to #4 immediately because you're changing the image in the for loop which causes the check within the loop to keep being true and so it runs all the way to the last index, at which point the check finally fails. Instead, you'll want to maintain the current image index with a variable. Then, just change myImage.src to images[currentIndex + 1] on each click. Try something like below. You'll want to run showNextImage on page load and then run it once each time the image is clicked.
<script>
var currentImageIndex = 0;
//Cycle through images
showNextImage() {
var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]
var myImage = document.getElementById("mainImage")
myImage.src = images[currentImageIndex];
currentImageIndex++;
if(currentImageIndex >= images.length)
currentImageIndex = 0;
}
</script>
Basically I need the thumbnails to rotate every time the user hovers over an image. Here is my failed attempt:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('img').hover(function() {
theImage = $(this).attr('id');
otherImages = $(this).attr('class').split('#');
rotateThumbs(otherImages, theImage);
}, function() {
//
});
});
function rotateThumbs(otherImages, theImage) {
for (i=0; i < otherImages.length; i++) {
setInterval($('#'+theImage).attr('src', otherImages[i]), 1000);
}
}
</script>
<img id="myImage" src="http://www.google.com/images/logos/ps_logo2.png" class="http://www.google.com/images/logos/ps_logo2.png#http://l.yimg.com/a/i/ww/met/yahoo_logo_us_061509.png#http://dogandcat.com/images/cat2.jpg" width="174" height="130" />
Does anyone know how this may be accomplished?
Some issues here.
setInterval requires a function reference as it's first argument, but you are executing code that returns a jQuery object.
setInterval executes the first function repeatedly at the specified interval. Is that what you are trying to do? Swap images every second?
Depending on how you correct the first issue, you could run into an issue where i is otherImages.length and thus the src is set to undefined.
Assuming you worked around issue 3, you will have the problem that the image swaps will happen imperceptibly fast and it will appear as though the last image is always displayed.
Instead, don't use a loop. Increment a counter each time a new image is displayed. Try this:
function rotateThumbs(otherImages, theImage) {
var i = 0;
var interval = setInterval(function() {
$('#'+theImage).attr('src', otherImages[i++]);
if (i >= otherImages.length) {
clearInterval(interval);
}
}, 1000);
}
I've implemented a fully-functional example here. This addresses some of the issues that #gilly3 notes, but uses closures instead of an incrementing counter to keep track of the current image:
$(function() {
$('img').hover(function() {
// declaring these variables here will preserve
// the references in the function called by setInterval
var $img = $(this),
imageList = $img.attr('class').split('#'),
intervalId;
// start the cycle
intervalId = window.setInterval(function() {
var next = imageList.pop();
if (next) {
$img.attr('src', next);
} else {
// stop the cycle
intervalId = window.clearInterval(intervalId);
}
}, 1000);
}, function() {});
});
As you can see, using a closure is much easier when you declare the function passed to setInterval inline, rather than as a separate, named function. You could still have a rotateThumbs function if you wanted, but you might need to do some more work to ensure that the variables were being passed properly.
Edit: I made an updated version that continues to cycle as long as the mouse is hovering.
I have adjusted the answer for Sam, taking pre-loading the image into account, so that you won't have a possible deplay at the first rotation.
function rotateThumbs(otherImages, theImage) {
if(!$('#'+theImage).data('setup')){
$('#'+theImage).data('setup', true); // do not double pre-loading images
var $body = $('body');
for(var j = 0; j < otherImages.length; j++){
$body.append($('<img/>').attr('src', otherImages[j])
.css('display', 'none'));
}
}
var i= 0;
setInterval(function(){
$('#'+theImage).attr('src', otherImages[i++]);
if(i >= otherImages.length){i = 0}
}, 1000);
}