okay so i want if my counter reaches the maximum count, it starts over, with the default counter number which is 0 here is my code:
var picCount = 0; // global
var maxCount = 4;
//Pictures, to add more then 4 pics, add var picFive = "link to image here", var picSix ="bla", you get it.. add in picArray ,picFive and ,picSix
//To change the time delay, change it at the body onload and on the setTimeout
var picOne = "http://screenshots.nl.sftcdn.net/nl/scrn/3342000/3342167/modloader-for-minecraft-02-700x406.jpg"
var picTwo = "http://media.moddb.com/images/downloads/1/31/30912/minecraft_blox.png"
var picThree = "http://www.mupload.nl/img/rl6zeofbb.png"
var picFour = "http://www.mupload.nl/img/rl6zeofbb.png"
var picArray = [picOne, picTwo, picThree, picFour]
//
// gets next picture in array
function nextPic() { // check if adding 1 exceeds number of pics in array
if (picCount.length < maxCount.length) {
picCount = (picCount + 1 < picArray.length) ? picCount + 1 : 5000;
// build the image to write to page using the new pic reference
var build = '<img border="0" src="' + picArray[picCount] + '" width="649">\n';
document.getElementById("imgHolder").innerHTML = build;
// repeat this every 10 seconds.
setTimeout('nextPic()', 10 * 1000) //setTimeout is here
} else {
picCount = (picCount - maxCount < picArray.length) ? picCount + 1 : 5000;
// build the image to write to page using the new pic reference
var build = '<img border="0" src="' + picArray[picCount] + '" width="649">\n';
document.getElementById("imgHolder").innerHTML = build;
// repeat this every 10 seconds.
setTimeout('nextPic()', 10 * 1000) //setTimeout is here
}
}
okay so i hope you guys can help me with this..
That's a lot of messy code.
My fix for an implementation would probably look something like this:
var currentPic = 0;
var picOne = "http://screenshots.nl.sftcdn.net/nl/scrn/3342000/3342167/modloader-for-minecraft-02-700x406.jpg"
var picTwo = "http://media.moddb.com/images/downloads/1/31/30912/minecraft_blox.png"
var picThree = "http://www.mupload.nl/img/rl6zeofbb.png"
var picFour = "http://www.mupload.nl/img/rl6zeofbb.png"
var picArray= [picOne,picTwo,picThree,picFour]
function nextPic() {
if (currentPic < picArray.length) {currentPic++;}
else {currentPic = 0;}
var build='<img border="0" src="'+picArray[currentPic]+'" width="649">';
document.getElementById("imgHolder").innerHTML=build;
// repeat this every 10 seconds.
setTimeout('nextPic()',10 * 1000)//setTimeout is here
}
Despite many other issues which I am sure are present in your code, I believe this line is the cause of your particular problem addressed in the question:
if (picCount.length < maxCount.length) {
maxCount and picCount are just numbers. They do not have a length property. Change it to this:
if (picCount < maxCount) {
var currentPic = 0;
var picArray= ["http://screenshots.nl.sftcdn.net/nl/scrn/3342000/3342167/modloader-for-minecraft-02-700x406.jpg",
"http://media.moddb.com/images/downloads/1/31/30912/minecraft_blox.png",
"http://www.mupload.nl/img/rl6zeofbb.png",
"http://www.mupload.nl/img/rl6zeofbb.png"];
function nextPic() {
(currentPic < picArray.length) ? currentPic++ : currentPic = 0;
var build='<img border="0" src="'+picArray[currentPic]+'" width="649">';
document.getElementById("imgHolder").innerHTML=build;
}
setTimeout('nextPic()',10 * 1000);
I made a few changes that make your code cleaner.
Some tips:
No need to store your image URLs in vars before putting them in the array. Just initialize your array with them.
Don't repeat yourself. Whenever you find yourself using the exact same code in multiple places, you probably need to rethink how you are approaching the problem.
Look up the "ternary operator". In my opinion it makes simple conditional statements easier to read.
No need to use maxCount - the max count will be the length of your picArray.
Although not usually required, try to end all statements with a semicolon.
Don't mind the elitist attitude some people have, but at the same time, try to research as much as you can before asking a question.
Related
For the record, I'm not too great at Java yet, I'm just starting out with it. Currently, I'm working on a small personal project that randomly displays images from a folder for 5 seconds before transitioning to another one. I'd like to add as many images as possible, but once I make an array of over 100+ objects, managing it, as well as the files, becomes quite a chore, especially if I want to start rearranging files or add/remove some.
I've already had to start renaming the files to sequential numbers to get the random cycling to work, which has been a chore in it's own, so I was curious if there was a way to at least shorten the array and have it cycle through the files. Or maybe there's an easier solution that doesn't require the array at all since the files are named sequentially with numbers.
This is what the code looks like so far:
var delay=5000 //set delay in miliseconds
var curindex=0
var randomimages=new Array()
randomimages[0]="1.png"
randomimages[1]="2.jpg"
randomimages[2]="3.png"
randomimages[3]="4.png"
randomimages[4]="5.png"
randomimages[5]="6.png"
randomimages[6]="7.png"
randomimages[7]="8.jpg"
randomimages[8]="9.png"
randomimages[9]="10.png"
// Cut out the 100 extra lines
// Continues like this for multiple lines and variates between PNG and JPG images
randomimages[103]="104.jpg"
var preload=new Array()
for (n=0;n<randomimages.length;n++)
{
preload[n]=new Image()
preload[n].src=randomimages[n]
}
document.write('<div><img name="defaultimage" src="'+randomimages[Math.floor(Math.random()*(randomimages.length))]+'"></div>')
function rotateimage()
{
if (curindex==(tempindex=Math.floor(Math.random()*(randomimages.length)))){
curindex=curindex==0? 1 : curindex-1
}
else
curindex=tempindex
document.images.defaultimage.src=randomimages[curindex]
}
setInterval("rotateimage()",delay)
Any help is appreciated.
Try this code:
var delay = 5000, //set delay in miliseconds
count = 104,
curindex = Math.floor(Math.random() * count),
preload = [],
img;
for (var n = 1; n <= count; n++) {
img = new Image();
img.src = n + '.png';
preload.push(img);
}
document.write('<div><img name="defaultimage" src="' + (curindex + 1) + '.png"></div>')
function rotateimage() {
var tempindex = Math.floor(Math.random() * count);
if (curindex === tempindex) {
curindex = (curindex === 0 ? 1 : curindex - 1);
} else {
curindex = tempindex;
}
document.images.defaultimage.src = (curindex + 1) + '.png';
}
setInterval("rotateimage()", delay);
There's no need to have an array like you said.
I have 18 images from which I only wish to show 5 at any given time. I'm swapping out a new image every two seconds or so without showing duplicates. My HTML is hardcoded and pulling from an s3 bucket.
<img class="activeImg" src="img_1.jpg />
<img src="img_2.jpg />
<img src="img_3.jpg />
<img src="img_4.jpg />
...
<img src="img_9.jpg />
I have a recursive setTimeout function that is calling moveCounter. moveCounter simply increments by 1, and replaces an image, every time it gets called. I hook into the element by adding the activeImg class to the img, then remove it before moving onto the next image.
The end goal is to count from 0...5, then back down 5...0, infinitely. All I'm doing is appending the value to an image name, thereby replacing images without showing a duplicate.
The problem is there is overlap and I'm getting a duplicate whenever counter === imgId.
// my recursive settimeout function fires off and adds an activeImg class to a random image element, then also fires off the replaceImage function
var counter = 0;
var imgId = 18;
// increment counter and append new img
function replaceImage(imgId){
if (counter >= 9) {
counter--;
var imgId = imgId - counter;
} else {
counter++;
var imgId = imgId - counter;
}
jQuery('.activeImg').attr('src', "image/img_"+imgId+".jpg");
console.debug(counter)
console.debug(imgId)
}
I feel like there is a better way to approach this.
Seems that what you're looking for is a simple triangle wave.
You can generate one rather easily:
var a = 5;
var output = [];
for (var i = 0; i < 20; i++) {
output.push(a - Math.abs(i % (2 * a) - a));
};
out.innerHTML = output;
<span id="out"></span>
var counter = 1;
var imgId = 18;
var op = 1; // the operation -- 1 for addition, -1 for subtraction
function replaceImage(imgId) {
// increment or decrement the counter, depending
// on the current direction
counter += op;
// use the original poster's snippet to set the active image
var imgId0 = imgId + counter;
$('.activeImg').attr('src', 'image/img_'+imgId0+'.jpg');
// if we hit the upper or lower bound, reverse the direction
// by flipping the operation
if (counter === 5 || counter === 1)
op *= -1;
}
I have the current JavaScript problem. I have four divisions next to each other on my website that constantly rotate images on a 10 seconds interval. I need these intervals to keep rotating images at the current interval but start 5 seconds apart from each other in order to obtain a nice waterfall effect. How can I accomplish this using JavaScript?
image of how it looks on my websites' header
This is an example of the code I am currently using to display a single division and handle the rotation of the images.
<div class = "TestRotator">
<img src="http://bushveld.info/wp-content/uploads/2013/07/image1.png" alt="rotating" width="100" height="232" id="rotator">
<script type="text/javascript">
(function () {
var rotator = document.getElementById('rotator'); // change to match image ID
var imageDir = 'http://bushveld.info/wp-content/uploads/2013/07/';
var delayInSeconds = 5;
// set number of seconds delay
// list image names
var images = ['image2.png', 'image3.png', 'image4.png'];
var num = 0;
var changeImage = function () {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
</script>
</div>
I've fiddled it a lot! (I changed it big time.)
chenged setInterval() with setTimeout() and many others.
Is this what you wanted?
PS: state holds the 1st image to which the imgs change. and the difference in the timeout (200 milliseconds is in order to just to make some difference in between them, yuo can change it to a round number if you want to).
If I've understood your question correctly, you need something like this:
window.onload = function () {
var // Customable parameters
imageDir = 'http://bushveld.info/wp-content/uploads/2013/07/',
interval = 2, // Interval between "flushes" in seconds. Must be > speed * maxScreens
speed = 0.1, // "Flush" speed in seconds
maxScreens = 4, // amount of used image tags
images = 4, // amount of image sources, can be > maxScreens
dir = 1, // 1 = from left to right, -1 = from right to left
// Program
flush,
target = (dir > 0) ? 1 : maxScreens,
targetOrigo = target,
changeImage = function() {
var img = document.getElementById('rotator' + target),
id = parseInt(img.src.substr(img.src.length - 5, 1), 10) - dir;
if (id < 1) {
id = images;
}
if (id > images) {
id = 1;
}
img.src = imageDir + 'image' + id + '.png';
if (target !== maxScreens - targetOrigo + 1) {
target += dir;
setTimeout(changeImage, speed * 1000);
} else {
target = targetOrigo;
setTimeout(runRotation, interval * 1000);
}
return;
},
runRotation = function () {
setTimeout(changeImage, speed * 1000);
};
setTimeout(runRotation, 1000);
}
A live demo at jsFiddle
Notice, that I've put the function at window.onload, looks better when all the images are already loaded, before the rotation starts.
The snippet doesn't use setInterval() at all, instead it's based on nested setTimeout()s. This way you can avoid a mess, which you might get (depends on used browser), if user visits at other tab and then comes back to your site.
You can play with interval, "flush" speed, number of images you have on the rotation and even how many different images you like to use (max. = 9). You can also switch the direction of the rotation.
If you want to avoid two similar images to be shown at the same time, you can add image5.png to your image folder, and set images = 5.
Also version using an image source array available.
Thanx alot for the input. I solved this issue by adapting the code in this manner...
(function() {
var rotator3 = document.getElementById('rotator3'); // change to match image ID
var imageDir = 'http://bushveld.info/wp-content/uploads/2013/07/';
// set number of seconds delay
// list image names
var images = ['image2.png', 'image3.png', 'image4.png', 'image1.png'];
// don't change below this line
var num = 0;
var changeImage = function()
{
var len = images.length;
rotator3.src = imageDir + images[num++];
if (num == len)
{
num = 0;
}
};
function SwImg() {
var rotate = setInterval(changeImage, 20000);
}
setTimeout(SwImg,15000);
})();
This tweak basically creates an initial delay of 5++ seconds at each division with the standard 20 seconds delay interval between switches, rotating each image in each division 5 seconds after the other. Here is a link to the website , will be done end of this week. Thanks again for the input, really awesome and creative ways of solving this issue!
Cheers
I have a JSON array(?) of pairs of every state and a value associated with that state, it looks like the following below:
var states = [{"STATE":"AL","AMOUNT":"6"}, {"STATE":"AK","AMOUNT":"3"}]
I need the page to shuffle through them without reloading the page
"AL 6" [wait x seconds] then "AK 3" [wait x seconds] then etc...
I need this to run continuously.
I never use any of these languages but was told that they were my best bet.
Could someone give me some guidance on this please.
Thank you in advance.
Here's a jsfiddle with setInterval execting a function that alternates between each state and displays it in a div:
http://jsfiddle.net/WD5Qj/1/
var states = '[{"STATE":"AL","AMOUNT":"6"}, {"STATE":"AK","AMOUNT":"3"}]';
json = jQuery.parseJSON(states);
var i = 0;
var cycle = function(){
$("#state").html(json[i].STATE + json[i].AMOUNT);
i = (i+1)%json.length;
}
var loop = setInterval(cycle, 500);
Alright, you'd need a function that does the rotation through the array, and a variable for keeping the current state (in both meanings of the word):
var stateIndex = 0;
function rotate() {
stateIndex++;
if(stateIndex >= states.length)
stateIndex = 0;
displayState(states[stateIndex]);
}
And you'd need an interval to perform the rotation:
var stateRotation = window.setInterval(rotate, 3000); // 3000ms = 3 sec
The stateRotation variable is an identifier of your interval. You may use that if you ever want to stop: window.clearInterval(stateRotation);
Now, the above code anticipates a function displayState which takes a state object and displays it. How that would look depends entirely on how you want your state to displayed. In its simplest form, something like this:
function displayState(state) {
$('#state-name').html(state.STATE);
$('#state-amount').html(state.AMOUNT);
}
As per your description, it might perhaps be something more like
$('#state-text').html(state.STATE + ' ' + state.AMOUNT);
var states = [{"STATE":"AL","AMOUNT":"6"}, {"STATE":"AK","AMOUNT":"3"}];
var i = 0;
setInterval(function(){
var array_index = i % states.length;
$('#state').html( states[ array_index ]['STATE'] );
$('#state').html( states[ array_index ]['AMOUNT'] );
i++;
}, 2000);
Here's a fiddle.
function displayNextItem(index){
if (index === states.length)
displayNextItem(0);
$("#someDiv").text(states[index]["STATE"] + " " + states[index]["AMOUNT"]);
setTimeout(function() { displayNextItem(index + 1); }, 1000);
}
And then
displayNextItem(0);
var i = 0, l = states.length, timer, intervalLength = 5000;
timer = setInterval(function(){
if(i >= l){
clearInterval(timer);
}else{
alert(states[i++].STATE);
}
},intervalLength);
This implementation is waiting the AMOUNT number of seconds. If you want constant number of seconds then other answers are better :).
JavaScript:
var states = [{"STATE":"AL","AMOUNT":"6"}, {"STATE":"AK","AMOUNT":"3"}];
function iterate(index) {
var time = states[index].AMOUNT;
// replace the text with new one
$("#output").text(states[index].STATE + " " + time);
setTimeout(function() {
var next = (index + 1) % states.length;
iterate(next);
}, time * 1000);
}
iterate(0);
HERE is the code.
How to set interval or may be timeout through the array, to produce effects for the element every 2 sec for example the 1-st idea is to programm something like this:
for (photoKey in arrBigPhotoes) {
setInterval(function() {
// alert(arrBigPhotoes[photoKey]);
document.getElementById("big_photo").src='/upload/images/'+arrBigPhotoes[photoKey];
}, 2000);
}
But it didn't work properly. May be someone can help me with this task I'll be extremely glad.
I'm also have a jQuery - the resolution may be through this library, but without any plug-ins.
Thanks.
Try something like this -
var photos = ['1.jpg', '2.jpg', '3.jpg'];
var photo_index = 0;
function switchPhoto() {
photo_index = (photo_index + 1) % photos.length;
document.getElementById('big_photo').setAttribute('src', '/upload/images/' + photos[photo_index]);
}
setInterval(switchPhoto, 2000);
You should probably put this inside some kind of document ready event handler
I would suggest you pre-load the images you are trying to display. If the user is on a slow connection, your approach would fail.
var images = new Array();
var counter = 0;
var image = document.createElement("img");
image.onload = function() {
counter++;
};
image.src = <url>;
images.push(image);
The counter is there so that you can determine when all images are properly loaded. Let's say you have six images, then, in your "intervaled" function, you would immediately return if counter < 6.
Your "switcher" function could look this way
var i = 0;
setInterval(function() {
if (counter < 6) return;
i = (i+1) % images.length;
document.getElementById("big_photo").src = images[i].src;
}, 2000);