I have a site that has an image gallery that changes images every few seconds using JavaScript; however, I want to know how to STOP the images from changing when a user clicks on one of the images.
So far, the images are rotating as planned, but I can't seem to get the "onClick" scripting to STOP the rotation when the user clicks on an image. I don't need to have an alert popup or need it to do anything, I just need it to STOP the image rotation when someone clicks on one of the pictures.
Here's the HTML code I have:
else (getValue=='STOP')
{
alert("STOPPED");
}
That won't do what you probably want it to do. It should be:
else if (getValue=='STOP')
{
alert("STOPPED");
}
First of all, you missed out on the keyword "IF" in one of the lines of your code.
However, the way to create a terminable repetitive action is to setInterval and then use clearInterval to terminate the repetition.
semaphore = setInterval(somefunction, someinterval);
clearInterval(semaphore);
Example (I wrote this off-the-cuff, so there might be some errors, but you shd get the idea):
<img src="./images/image1.jpg" id="imageGallery" name="imageGallery"
onclick="chooseImg(this)" />
<script>
var turn = setInterval(function(){imgTurn()},5000);
var images = function2CreateImgArray();
var imageN = 0;
function chooseImg(img){
clearInterval(turn);
function2DisplayImg(imageN); // or do whatever
}
function imgTurn(){
if (imageN++ >= images.length) imageN = 0;
function2DisplayImg(imageN++);
}
</script>
You could replace the setInterval with setTimeout.
var turn = setTimeout(function(){imgTurn()},5000);
But then you need to use clearTimeout to stop it:
clearTimeout(turn);
But if you use setTimeout, you would need to setTimeout for the next image display, so you would not even need to clearTimeout to stop the rotation.
<img src="./images/image1.jpg" id="imageGallery" name="imageGallery"
onclick="chooseImg(this)" />
<script>
setTimeout(function(){imgTurn()},5000);
var images = function2CreateImgArray();
var imageN = 0;
var turn = 1;
function chooseImg(img){
turn = 0;
function2DisplayImg(imageN); // or do whatever
}
function imgTurn(){
if (turn==0) return;
if (imageN++ >= images.length) imageN = 0;
function2DisplayImg(imageN++);
}
</script>
Related
im implementing a game (this is my first game ever) so Imagine this.
I have 4 images (html5)
onclick they call a function that makes all the game to work!
So, in the game you have turns, the turn says to me how many clicks I will need in that turn.
So how to do it if I always click the image and calls the function and the user is just able to do one click while clicks should be equal that the turn.
Something like this:
<img onclick="myFunction()"/>
<script>
var clickCounter = 0;
var turnNum = 1;
function myFunction () {
clickCounter++;
if (clickCounter == turnNum) {
// do stuff
turnNum++;
clickCounter = 0;
}
}
</script>
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>
I'm currently making a game in JS, and I faced a problem.
I got an 2D array that stores an image, now I want some random pic to be changed every 1 second, everything is working but, I don't know how I can change the picture.
Do I have to print all the other images if I want to change the random cell in the array?
I'm almost sure that there's another way to change it without doing it.
I'll be glad for help, if anyone needs other explanation I'll be glad to.
You can try using something like this in your header. It should call changePic() every second, incrementing through your picture array, and setting the new picture on an image element.
//know your array sizes
var max_x = picArr.length;
var max_y = picArr[0].length;
var current_x = 0;
var current_y = 0;
function changePic()
{
if(current_y == max_y-1)
{
if(current_x == max_x-1)
{
current_x = 0;
current_y = 0;
}
else
{
current_x++;
current_y = 0;
}
}
else
current_y++;
var pic = picArr[current_x][current_y];
getElementById('randomImage').setAttribute('src', pic);
window.setTimeout(changePic, 1000);
}
setTimeout(changePic, 1000);
https://developer.mozilla.org/en/DOM/window.setTimeout
I would start out with something like
var ImageOne = new Image();
ImageOne.src = "UrlToImage";
And so on just to make sure all the images are loaded when the game starts
Thereafter I would be using jQuery:
$("#IdOfImg").attr("src", ImageOne);
You might want to try using a css class for the elements with a background image rather dan adding images to the DOM. I think a css class for back.png and one for the 1.png should do the trick.
Toggle the classes on the td elements every second.
Hope this helps.
I'm working on making a JS script that will go in the header div and display a few pictures. I looked into JQuery Cycle, but it was out of my league. The code I wrote below freezes the browser, should I be using the for loop with the timer var?
<script type="text/JavaScript" language="JavaScript">
var timer;
for (timer = 0; timer < 11; timer++) {
if (timer = 0) {
document.write('<img src="images/one.png">');
}
if (timer = 5) {
document.write('<img src="images/two.png">');
}
if (timer = 10) {
document.write('<img src="images/three.png">');
}
}
</script>
Thanks!
Assuming you want a script to rotate images and not just write them to the page as your code will do, you can use something like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="target"></div>
<script>
var ary = ["images/one.png","images/two.png","images/three.png"];
var target = document.getElementById("target");
setInterval(function(){
target.innerHTML = "<img src=\""+ary[0]+"\" />";
ary.push(ary.shift());
},2000);
</script>
</body>
</html>
Of course the above code has no effects (like fading) which jQuery will give yous, but it also doesn't require loading the entire jQuery library for something so basic.
How about just running the script after the page loads?
<script>
// in <head> //
function load() {
var headDiv = document.getElementById("head");
var images = ["images/one.png", "images/two.png"];
for(var i = 0; i<images.length; i++) {
image = document.createElement("img");
image.src = images[i];
headDiv.appendChild(image);
}
}
</script>
Then use <body onload="load();"> to run the script.
Edit
To add in a delay loading images, I rewrote the code:
<script>
// in <head> //
var displayOnLoad = true; // Set to true to load the first image when the script runs, otherwise set to false to delay before loading the first image
var delay = 2.5; // seconds to delay between loading images
function loadImage(url) {
image = document.createElement("img");
image.src = images[i];
headDiv.appendChild(image);
}
function load() {
var headDiv = document.getElementById("head");
var images = ["images/one.png", "images/two.png"];
for(var i = 0; i<images.length; i++) {
setTimeout(loadImage(images[i]), (i+displayOnLoad)*(delay*1000));
}
}
</script>
Set displayOnLoad = false; if you want to wait the specified delay before loading the first image. The delay is set in seconds. I recommend waiting over a single second between images, as they may take some time to download (depending on the user's internet speed).
As with the first snippet, I haven't tested the code, so please tell me if an error occurs, and I will take a look.
Since you used the jquery tag on your question, I assume you are OK with using jQuery. In which case, you can do something like this:
In your static HTML, include the img tag and set its id to something (in my example, it's set to myImg) and set its src attribute to the first image, e.g.:
<img id="myImg" src="images/one.png">
Next, use jQuery to delay execution of your script until the page has finished loading, then use setTimeout to create a further delay so that the user can actually spend a few seconds looking at the image before it changes:
<script>
var imgTimeoutMsecs = 5000; // Five seconds between image cycles
$(function() {
// Document is ready
setTimeout(function() {
// We will get here after the first timer expires.
// Change the image src property of the existing img element.
$("#myImg").prop("src", "images/two.png");
setTimeout(function() {
// We will get here after the second, nested, timer expires.
// Again, change the image src property of the existing img element.
$("#myImg").prop("src", "images/three.png");
}, imgTimeoutMsecs);
}, imgTimeoutMsecs);
});
</script>
Of course, that approach doesn't scale very well, so if you are using more than three images total, you want to modify the approach to something like this:
var imgTimeoutMsecs = 5000; // Five seconds between image cycles
// Array of img src attributes.
var images = [
"images/one.png",
"images/two.png",
"images/three.png",
"images/four.png",
"images/five.png",
];
// Index into images array.
var iCurrentImage = 0;
function cycleImage() {
// Increment to the next image, or wrap around.
if (iCurrentImage >= images.length) {
iCurrentImage = 0;
}
else {
iCurrentImage += 1;
}
$("#myImg").prop("src", images[iCurrentImage]);
// Reset the timer.
setTimeout(cycleImages, imgTimeoutMsecs);
}
$(function() {
// Document is ready.
// Cycle images for as long as the page is loaded.
setTimeout(cycleImages, imgTimeoutMsecs);
});
There are many improvements that can be made to that example. For instance, you could slightly simplify this code by using setInterval instead of setTimer.
The code you've provided simply iterates through the for loop, writing the images to the browser as it does so. I suggest you take a look at JavaScript setTimeout function.
JS Timing
I'm using the following script and the later onclick-event. If I use the onclick my rotating banner loses it and starts displaying pictures at random intervals. I think I should override the "setTimeout" at the end of the first piece of code. Question is how exactly?
<script language="JavaScript" type="text/javascript">
<!--
var RotatingImage1_Index = -1;
var RotatingImage1_Images = new Array();
RotatingImage1_Images[0] = ["images/ban_image1.png","",""];
<!-- 15 Images in total-->
RotatingImage1_Images[14] = ["images/ban_image2.png","",""];
function RotatingImage1ShowNext(){
RotatingImage1_Index = RotatingImage1_Index + 1;
if (RotatingImage1_Index > 14)
RotatingImage1_Index = 0;
eval("document.RotatingImage1.src = RotatingImage1_Images[" + RotatingImage1_Index + "][0]");
setTimeout("RotatingImage1ShowNext();", 4000);}
// -->
</script>
<img src="images/ban_image1.png" id="ban_img1" name="RotatingImage1">
This part works as it should.
<div id="ban_next" align="left">
<a href="#" onclick="RotatingImage1ShowNext();return false;">
<img src="images/ban_next.png" id="ban_nxt1"></a></div>
This part works as well, but only correctly if I set the 'setTimeout' to '0'. I am sorry, I'm compleatly new to this. I was looking at this stackoverflow.com question, but I don't know how to implement that here.
I thank you in advance.
Edit:
The rotating image starts automaticly. It displays a new image every 4 seconds. The images have text on them, or better insider jokes. Readers should be tempted to read them, but if the automated rotation cought there antention, the have to keep that antention for a full minute to see all images. That's probably to long. So I thought to implement a button to overwrite the timer and show the next image 'on click'. But after the click the rotation-time should turn back to auto-rotation. That's the plan.
Thank you Prusse, for now it bedtime, I will try to grasp your answer tomorrow ;)
You don't need eval, just do document.RotatingImage1.src = RotatingImage1_Images[RotatingImage1_Index][0].
The described behavior happens because there is more then one timer firing. There is one set on the first time RotatingImage1ShowNext is called, more one each time its called from your onclick handler. To fix this declare a global for your timer and before another timeout is set clear it if set. Like:
var global_timerid;
function RotatingImage1ShowNext(){
//RotatingImage1_Index = RotatingImage1_Index + 1;
//if (RotatingImage1_Index > 14) RotatingImage1_Index = 0;
RotatingImage1_Index = (RotatingImage1_Index + 1) % RotatingImage1_Images.length;
//document.RotatingImage1.src = RotatingImage1_Images[RotatingImage1_Index][0];
document.getElementById('ban_img1').src = RotatingImage1_Images[RotatingImage1_Index][0];
if (global_timerid) clearTimeout(global_timerid);
global_timerid = setTimeout(RotatingImage1ShowNext, 4000);
}