Is there a way to make this slideshow move automatically? - javascript

This is the slideshow that we used:
http://www.littlewebthings.com/projects/blinds/
and this is the JS file:
http://www.littlewebthings.com/projects/blinds/js/jquery.blinds-0.9.js
However, this slideshow doesn't have a setting that makes it go through each image automatically. You still have to click on the numbers below it to see the images. Does anybody know what to add into the javascript code to make it go through each image automatically?
Thanks!

This solution uses closures and recursion.
var SlideChanger = function(seconds_each) {
var index = -1;
// on the first cycle, index will be set to zero below
var maxindex = ($(".change_link").length) - 1;
// how many total slides are there (count the slide buttons)
var timer = function() {
// this is the function returned by SlideChanger
var logic = function() {
// this is an inner function which uses the
// enclosed values (index and maxindex) to cycle through the slides
if (index == maxindex)
index = 0; // reset to first slide
else
index++; // goto next slide, set index to zero on first cycle
$('.slideshow').blinds_change(index); // this is what changes the slide
setTimeout(logic, 1000 * seconds_each);
// schedule ourself to run in the future
}
logic(); // get the ball rolling
}
return timer; // give caller the function
}
SlideChanger(5)(); // get the function at five seconds per slide and run it
What we are doing here is exposing the inner function timer outside of the function in which it was defined (SlideChanger). This function (timer) has access to the variables defined inside of SlideChanger (index and maxindex).
Now that we have set up the variables in the enclosing environment and a function to return to the caller, we can set up the logical engine in logic. When logic is run, it uses index and maxindex to determine which slide should be shown next, shows the slide, and schedules itself to be run again in the future.
When called, the returning function calls logic to get the ball rolling. Then logic repeats indefinitely by scheduling itself to run in the future each time it is run.
So, to summarize, we call SlideChanger with a numeric argument x. It returns a function that, after being called, will change the slide every x seconds.
Another way to write the same concept.
(function(seconds_each) {
var index = -1;
// on the first cycle, index will be set to zero below
var maxindex = ($(".change_link").length) - 1;
// how many total slides are there (count the slide buttons)
return function() {
// this is the function returned by SlideChanger
var logic = function() {
// this is an inner function which uses the
// enclosed values (index and maxindex) to cycle through the slides
if (index == maxindex)
index = 0; // reset to first slide
else
index++; // goto next slide, set index to zero on first cycle
$('.slideshow').blinds_change(index); // this is what changes the slide
setTimeout(logic, 1000 * seconds_each);
// schedule ourself to run in the future
}
logic(); // get the ball rolling
}
})(5)(); // get the function at five seconds per slide and run it
JavaScript is a nice language with many functional programming constructs such as higher order functions (functions that either create functions or accept functions as parameters) and anonymous functions. For more info see http://www.ibm.com/developerworks/web/library/wa-javascript.html

ecounysis's solution would work but it's unnecessarily complicated. Here's a simpler way using setInterval, modulo, and not wrapping it in an extra function:
function startSlideshow(ms) {
var index = -1;
var count = $(".change_link").length - 1;
return setInterval(function() {
index = (index + 1) % count;
$('.slideshow').blinds_change(index);
}, ms);
}

After a quick scan through the source, I didn't see a built-in API for auto-advancing the slides. However, you could use an alternative slideshow, like this one:
http://jquery.malsup.com/cycle/

All you need is to include a timer on it and call the blinds_change event. That works for me.

Related

Appending Different Random Number To URL In Javascript Array On Each Loop

I'm trying (without much success) to create an array which contains slides being loaded into an iframe. One of these frames (/Events.php) uses PHP to query a WordPress database and show 1 post chosen at random. This slide needs to show a different random post every time the array loops through.
My code at them moment is...
<script type="text/javascript">
var frames = Array(
'http://www.example.com/Slide01.php', 5,
'http://www.example.com/Slide02.php', 5,
getRandomUrl(), 5,
'http://www.example.com/Slide04.php', 5
);
var i = 0, len = frames.length;
function getRandomUrl()
{
return "http://www.example.com/Events.php?=" + (new Date().getTime());
}
function ChangeSrc()
{
if (i >= len) { i = 0; } // start over
document.getElementById('myiframe').src = frames[i++];
setTimeout('ChangeSrc()', (frames[i++]*1000));
}
window.onload = ChangeSrc;
</script>
The only trouble is everytime /Events.php is shown it has the same number appended to it so therefore shows the same post in each loop.
I need to append a different number to the /Events.php slide on each loop so it generates different content each time.
I'm starting to think I'm approaching this in totally the wrong way so any help or pointers in the right direction would be appreciated!
Cheers,
Mark.
The issue is you are only calling getRandomUrl() once which is when you defined your array, this means the value will always be the same as its only returned once.
One solution would be to store the function itself in your array like so:
var frames = Array(
'http://www.example.com/Slide01.php', 5,
'http://www.example.com/Slide02.php', 5,
getRandomUrl, 5,
'http://www.example.com/Slide04.php', 5
);
And then call it in ChangeSrc() if its a function
function ChangeSrc()
{
if (i >= len) { i = 0; } // start over
var frame = frames[i++],
isFnc = typeof(frame) == "function";
if(isFnc){
frame = frame();
}
document.getElementById('myiframe').src = frame;
setTimeout(function(){
ChangeSrc()
}, frames[i++]*1000);
}
http://jsfiddle.net/redgg6pq/
A tip would be that you are only calling 'getRandomUrl' once, hence why it's always the same image. You want to call it each time you are in the loop.
I would suggest removing it from the static array, and calling it in the loop - does that make sense? :)
HTH

JavaScript Automated Clicking

So, here's my issue.
I need to write a script to be run in the console (or via Greasemonkey) to automate clicking of certain links to check their output.
Each time one of these links is clicked, they essentially generate an image in a flash container to the left. The goal here is to be able to automate this so that the QC technicians do not have to click each of these thumbnails themselves.
Needless to say, there needs to be a delay between each "click" event and the next so that the user can view the large image and make sure it is okay.
Here is my script thus far:
function pausecomp(ms) {
ms = ms + new Date().getTime();
while (new Date() < ms){}
}
var itemlist, totalnumber, i;
itemlist = document.getElementsByClassName("image");
totalnumber = parseInt(document.getElementById("quickNavImage").childNodes[3].firstChild.firstChild.nodeValue.replace(/[0-9]* of /, ""));
for(i = 0; i < totalnumber; i = i + 1) {
console.log(i);
itemlist[i].childNodes[1].click();
pausecomp(3000);
}
Now, totalnumber gets me the total number of thumbnails, obviously, and then itemlist is a list of get-able elements so I can access the link itself.
If I run itemlist[0].childNodes[1].click() it works just fine. Same with 1, 2, 3, etc. However, in the loop, it does nothing and it simply crashes both Firefox and IE. I don't need cross-browser capability, but I'm confused.
There is a built-in JS function "setInterval(afunction, interval)" that keeps executing a given function every "interval" miliseconds (1000 = 1s).
This fiddle shows how to use setTimeout to work through an array. Here is the code:
var my_array = ["a", "b", "c", "d"];
function step(index) {
console.log("value of my_array at " + index + ":", my_array[index]);
if (index < my_array.length - 1)
setTimeout(step, 3000, index + 1);
}
setTimeout(step, 3000, 0);
Every 3 seconds, you'll see on the console something like:
value of my_array at x: v
where x is the index in the array and v is the corresponding value.
The problem with your code is that your pausecomp loop is a form of busy waiting. Let's suppose you have 10 items to go through. Your code will click an item, spin for 3 seconds, click an item, spin for 3 seconds, etc. All your clicks are doing is queuing events to be dispatched. However, these events are not dispatched until your code finishes executing. It finishes executing after all the clicks are queued and (roughly) 30 seconds (in this hypothetical scenario) have elapsed. If the number of elements is greater that's even worse.
Using setTimeout like above allows the JavaScript virtual machine to regain control and allows dispatching events. The documentation on setTimeout is available here.
People were correct with SetInterval.
For the record, here's the completed code:
/*global console, document, clearInterval, setInterval*/
var itemlist, totalnumber, i, counter;
i = 0;
function findmepeterpan() {
"use strict";
console.log("Currently viewing " + (i + 1));
itemlist[i].scrollIntoView(true);
document.getElementById("headline").scrollIntoView(true);
itemlist[i].style.borderColor = "red";
itemlist[i].style.borderWidth = "thick";
itemlist[i].childNodes[1].click();
i = i + 1;
if (i === totalnumber) {
clearInterval(counter);
console.log("And we're done! Hope you enjoyed it!");
}
}
function keepitup() {
"use strict";
if (i !== 0) {
itemlist[i - 1].style.borderColor = "transparent";
itemlist[i - 1].style.borderWidth = "medium";
}
findmepeterpan();
}
itemlist = document.getElementsByClassName("image");
totalnumber = parseInt(document.getElementById("quickNavImage").childNodes[3].firstChild.firstChild.nodeValue.replace(/[0-9]* of /, ""), 10);
counter = setInterval(keepitup, 1500);

Using shift() and push() to loop array values vs. using a counter variable, what is the best approach?

I'm looping through a set of images within an array of animation frames. There are 7 images, and looping from 1-7 completes the animation. I need this animation to loop indefinitely, but I was wondering which of these is the best approach:
Loop by modifying array
/* Pull image from start of array. */
var image = frames.shift();
/* Process image. */
...
/* Add image back to end of array. */
frames.push(image );
Loop using counter variable
/* Pull image by counter offset. */
var image = frames[counter];
/* Process image. */
...
/* Increment or reset counter value. */
counter + 1 === frames.length ? counter = 0 : counter = counter + 1;
Is there a reason I'd chose one over the other? Alternatively, is there a better approach to this?
Modifying the array is going to be more expensive than simply using a variable to keep track of your position in the array. The better way to do this, if you're looping indefinitely, seems to just be to use a while loop (rather than using a for loop where you reset the counter inside):
var i = 0;
while (true) {
doSomething to array[i];
i = (i+1) % array.length;
}
However if your goal really is having an animation proceed indefinitely every time a given interval elapses, a loop isn't ideal at all. Use setInterval instead.
var frames = ...; //your images
var i = 0;
function animate() {
do something to frames[i];
i = (i+1) % array.length;
}
setInterval(animate, time_between_runs);
where time_between_runs is how much time should elapse before the function is called again.
Alternatively a circular linked list also can be used I think. To turn an array of objects into a circular linked list:
frames.forEach(function(elem, index) {
elem.next = frames[index + 1] || frames[0];
});
And now you can do something like this:
setInterval(function() {
frame = frame.next;
....
}, delay);
One possibility is to ditch the array and use a linked list.
Make each frame an object that points to the next object. The last one then points to the first. Then all you need to do is reference the next object.
var curr = first; // reference to first frame object
setInterval(function() {
// process image
curr.image.doSomething();
// proceed to next
curr = curr.next;
}, 1000);
No counters to mess with this way.
Setting up the linked list is usually pretty simple, and can likely be done with just a little modification to the current code that's setting up the Array.
var first = new Frame(); // This is your entry point
var current = first; // This holds the current frame during setup
for (var i = 0; i < totalFrames; i++) {
current.next = new Frame(); // Make the current reference a new frame
current = current.next; // Make the new frame current
}
current.next = first; // circular reference back to the first.
function Frame() {
// set up this frame
}
Then first is your starting point.
Or the linking could be done within the Frame constructor.
var first = new Frame(null);
var current = first;
for (var i = 0; i < totalFrames; i++) {
current = new Frame(current);
}
current.next = first;
function Frame(currFrame) {
// link this frame to the given one
if (currFrame)
currFrame.next = this;
// set up the rest of this frame
}

Javascript stopwatch incrementing by powers of two

I have the following code for my simple stopwatch, which only counts the number of seconds with no formatting whatsoever:
function countDown(from, interval, callback) {
interval = interval || 1000;
var current = 0;
var onCount = function() {
current++;
if (current <= from) {
callback(current, from);
setInterval(onCount, interval);
}
}
onCount();
}
This is called with an onclick, with the following code:
countDown(600, 1000, function(current, from) {
time_out.innerHTML = current;
});
Putting in a console.log(current), I can see two problems. First, though it does go through every number, it seems to get faster and faster, by powers of two. In the output div, the first tick will be 1, the second will be 2, the third will be 4, the fourth will be 8, and so on. Furthermore, it does not actually stop counting when it hits 600, even though it stops updating the div. What did I do wrong here?
You use setInterval which will call the callback at a set interval every time the function is called, resulting many many calls to countDown()
Maybe you wanted to use the setTimeout function instead, which will only call the function once after the delay.

Where to put this block of script so that this slideshow can move automatically?

I asked a question before on how to make the jQuery Blinds slideshow move automatically and somebody answered on this page (the one with 12 votes):
Is there a way to make this slideshow move automatically?
Seems like the code is working for most people but I can't get it to work for me. I used the original demo file and placed the code at the very bottom of jquery.blinds-0.9.js, right after "})(jQuery);" but still the slideshow isn't moving. What am I doing wrong? I checked the class names and they are correct.
This is that block of script:
var SlideChanger = function(seconds_each) {
var index = -1;
// on the first cycle, index will be set to zero below
var maxindex = ($(".change_link").length) - 1;
// how many total slides are there (count the slide buttons)
var timer = function() {
// this is the function returned by SlideChanger
var logic = function() {
// this is an inner function which uses the
// enclosed values (index and maxindex) to cycle through the slides
if (index == maxindex)
index = 0; // reset to first slide
else
index++; // goto next slide, set index to zero on first cycle
$('.slideshow').blinds_change(index); // this is what changes the slide
setTimeout(logic, 1000 * seconds_each);
// schedule ourself to run in the future
}
logic(); // get the ball rolling
}
return timer; // give caller the function
}
SlideChanger(5)(); // get the function at five seconds per slide and run it
Try wrapping the last line SlideChanger(5)(); in a document.ready, like this:
$(function(){SlideChanger(5)();})
Otherwise $(".change_link").length will prob return 0

Categories

Resources