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);
};
Related
I am busy making a memory game, where an image is to be displayed to the user, and after some 10 seconds of the image flashing, it should hide and four options are to be shown for the user to choose either the correct or incorrect answer.
So far, all I have accomplished is to load the images and cycle through all the puzzles that my code can find.
What I'm trying to do now is to make the image flash and hide after some time, while also just refreshing that section of the page, and not the entire page.
I am using C# and a user control on my page.
What I have tried so far is only
<script>
var x;
function BlinkImage() {
x = 1;
setInterval(change, 2000);
}
function change() {
if (x === 1) {
var image = document.getElementById('<%=imgMain.ClientID %>');
image.visible = false;
x = 2;
}
else {
var image = document.getElementById('<%=imgMain.ClientID %>');
image.visible = true;
x = 1;
}
}
</script>
And on loading my puzzle for that instance (in code behind)
Page.ClientScript.RegisterStartupScript(typeof(game), "Start", "<script language=javascript> BlinkImage(); </script>");
Which does fire, as I can step through the code in debugging on Firefox. But my image does not flash or blink. I understand I am just using visiblity as my "blinker". I don't know what else to use exactly.
What can I do to make the image flash or blink for, say 20 seconds, then hide the image after that time has passed? Then repeat the process once the user has made a choice.
You can try the following (comments in code):
var blinkInterval = setInterval(change, 2000), // set the interval into a variable
image = document.getElementById('test'), // replace test with your client id: <%=imgMain.ClientID %>
x = 1;
function change() {
if (x % 2 === 1) { // see if it is odd or even by modding by 2 and getting remainder
image.style.display = 'none';
} else {
image.style.display = 'block';
}
x++; // increment x
if (x === 10) { // should have happened 10 times (which is 20 seconds with your intervals being at 2 seconds)
clearInterval(blinkInterval); // clear the interval (should end hidden as odd is display none and we clear beforethe 20th is run)
}
}
<div id="test">test</div>
After the code has finished, wherever the user is making their selection, you just need to reset the blinkInterval variable:
blinkInterval = setInterval(change, 2000); // notice no need for the var declaration when you reset this
Use style attribute and change if visible/hidden
function change() {
var image = document.getElementById('<%=imgMain.ClientID %>');
//check if visible
if (image.style.visibility=="visible") {
image.style.visibility="hidden";
}
else {
image.style.visibility="visible";
}
}
;
Try this:
function flashAndHide(img_id){
var img = $("#"+img_id);
var x = 0;
var inter = setInterval(function(){
if(x % 2 == 0){
img.hide();
}else{
img.show();
}
x += 1;
}
},1000);
if(x === 20){
img.hide();
clearInterval(inter);
}
}
Haven't tested this, but it should work,
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);
}
<script src = "http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(){
var secs_time;
var timer2;
var arrayseq1 = [];
var secs_up = 0;
var timer1;
var secs_down = 0;
$("#pad").mousedown(function(){
$(this).css("background-color", "lightgrey");
clearInterval(timer2);
timer1 = setInterval(function(){
secs_down = secs_down + 1;
$("#pad").html(secs_down);
},1);
arrayseq1 = arrayseq1.concat([secs_down]);
}).mouseup(function(){
$(this).css("background-color", "grey");
clearInterval(timer1);
timer2 = setInterval(function(){
secs_up = secs_up + 1;
$("#pad").html(secs_up);
},1);
arrayseq1 = arrayseq1.concat([secs_up]);
});
$("#pad").mouseleave(function(){
clearInterval(timer2);
});
$("#done").click(function(){
arrayseq1.splice(1, 1);
arrayseq1.splice(0, 1);
var counter = 0;
var colors = ["#FF3E96", "#4169E1", "#7FFF00","#FF4500","#FF7F00", "black", "white"];
while(counter <= arrayseq1.length){
setTimeout(function(){
var color = colors[Math.floor(Math.random()*colors.length)];
$("body").css("background-color", color);
}, arrayseq1[counter]);
counter++;
}
});
});
</script>
<div style = "height:500px;width:600px;background-color:grey;border-radius:4px;margin:0 auto;margin-top:10%;" id = "pad"></div>
<input type = "button" id = "done" value = "play">
Hi all.
I am making a small program, that when you press, and press of a huge grey button, it records the time its held down, and up and all put into an array (read the code to get a better understanding, its not to hard to understand). Anyway, so it records the times to the array successfully, so the array "arrayseq1" does have a list of times e.g [106,144,114,152,122,161,130,311,148,357]. The problem comes when i try and loop through each number, and use each as a delay for the flash of the background. So, the specific problem is when i substitute "arrayseq1[counter]" in the setTimeout function. For some reason i do not understand, it is undefined. Why? How can i fix this?
in this jsfiddle: http://jsfiddle.net/5V4Lv/
I alert the value arrayseq1[counter] the line before i use it for the setTimeout function, and as you will see, it alerts "undefined"
so you can test this out successfully, click on the grey box fastly and randomly, and then when you are down, move your mouse off the box to stop recording. Then click play to start the flashing.
The original aim of this was for the background to flash in random colours in exact sync and beat to how you initially clicked the grey box.
Thanks!
I'm developing a simple slideshow system.
I've got the slideshow wrapped in a hidden div, which is shown when a thumbnail from the gallery is clicked.
The slideshow works through a function called commence(), which is executed when the play button is clicked.
At the moment I've got it set to hide to whole div again when stop is clicked, but I would like to keep the div shown, simply stop the slideshow, in other words, stop the commence() function.
Can anyone tell me how to do this?
Here is my JS:
function commence() {
hidden = document.getElementById("hidden");
hidden.style.display = 'block';
pause = document.getElementById("pause");
pause.style.display = 'block';
play = document.getElementById("play");
play.style.display = 'none';
pic = document.getElementById("picbox"); // Assign var pic to the html element.
imgs = []; // Assign images as values and indexes to imgs array.
/* --------------------------- IMAGE URLS FOR IMGS ARRAY -------------------------*/
imgs[0] = "/snakelane/assets/images/thumb/_1.jpg"; imgs[10] = "/snakelane/assets/images/thumb/_19.jpg";
imgs[1] = "/snakelane/assets/images/thumb/_2.jpg"; imgs[11] = "/snakelane/assets/images/thumb/_20.jpg";
imgs[2] = "/snakelane/assets/images/thumb/_3.jpg"; imgs[12] = "/snakelane/assets/images/thumb/_21.jpg";
imgs[3] = "/snakelane/assets/images/thumb/_4.jpg"; imgs[13] = "/snakelane/assets/images/thumb/_22.jpg";
imgs[4] = "/snakelane/assets/images/thumb/_5.jpg"; imgs[14] = "/snakelane/assets/images/thumb/_23.jpg";
imgs[5] = "/snakelane/assets/images/thumb/_6.jpg"; imgs[15] = "/snakelane/assets/images/thumb/_24.jpg";
imgs[6] = "/snakelane/assets/images/thumb/_7.jpg"; imgs[16] = "/snakelane/assets/images/thumb/_25.jpg";
imgs[7] = "/snakelane/assets/images/thumb/_8.jpg"; imgs[17] = "/snakelane/assets/images/thumb/_26.jpg";
imgs[8] = "/snakelane/assets/images/thumb/_9.jpg"; imgs[18] = "/snakelane/assets/images/thumb/_27.jpg";
imgs[9] = "/snakelane/assets/images/thumb/_10.jpg"; imgs[19] = "/snakelane/assets/images/thumb/_28.jpg";
/* -----------------------------------------------------------------------------------------------------*/
var preload = []; // New array to hold the 'new' images.
for(i = 0 ; i < imgs.length; i++) // Loop through imgs array
{
preload[i] = new Image(); // Loop preload array and declare current index as a new image object.
preload[i].src = imgs[i]; // Fill preload array with the images being looped from ims array.
}
i = 0; // Reset counter to 0.
rotate(); // Execute rotate function to create slideshow effect.
}
// Function to perform change between pictures.
function rotate() {
pic.src = imgs[i]; // Change html element source to looping images
(i === (imgs.length -1))?(i=0) : (i++); // counter equals imgs array length -1.
setTimeout( rotate, 4000); // Sets the time between picture changes. (5000 milliseconds).
}
function init() {
[].forEach.call(document.querySelectorAll('.pic'), function(el) {
el.addEventListener('click', changeSource);
});
function changeSource() {
hidden = document.getElementById("hidden");
hidden.style.display = 'block';
newpic = this.src;
var pic = document.getElementById("picbox");
pic.src = newpic;
}
}
document.addEventListener("DOMContentLoaded", init, false);
function stopSlide() {
var hidden = document.getElementById("hidden");
hidden.style.visibility = 'hidden';
pause.style.display = 'none';
var play = document.getElementById("play");
play.style.display = 'block';
}
The pause and play statements are not relevant to my question, they simply hide the play button and show the pause button if the slideshow is running, and vice versa.
It looks to me like you actually want to stop the rotate() function, rather then commence, since rotate is what is actually changing the images (ie running the slideshow).
There are two ways. The first, like thriqon posted, is to use the clearTimeout function. However I'd recommend doing it like this:
// somewhere in global space
var rotateTimeout;
// in commence
rotateTimeout = window.setInterval(rotate,4000); // this will tell the browser to call rotate every 4 seconds, saving the ID of the interval into rotateTimeout
// in stopSlide
window.clearInterval(rotateTimeout); // this will tell the browser to clear, or stop running, the interval.
The second, which is a bit messier, is to use a sentinel.
// somewhere in global space
var running;
// in commence
running = true;
rotate();
// in stopSlide
running = false;
// in rotate
if (running) {
setTimeout(rotate,4000);
}
You want to use window.clearTimeout using the id you get by call window.setTimeout.
But you should also consider switching to window.setInterval, which gives you an function call every 4 seconds (and not 4 seconds after the last call), the not-needing of repeated calls to re-set the timeout and a better handling of missed events.
See this jsFiddle: http://jsfiddle.net/D3kMG/ for an example on how to use these functions for a simple counter.
As mentioned by #thriqon you will want to use window.clearTimeout. To do this you need to save a "global" reference to the id returned by window.setTimeout, as follows:
var timeoutID;
//... function declarations
function rotate() {
//...
timeoutID = setTimeout( rotate, 4000);
}
Then in your stopSlide function you'll simply call clearTimout( timeoutID ) to stop the rotation.
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.