I'm trying to build a website that allows me to see my screen.
But I don't know how I can get the image it's displaying to constantly change.Thanks for the help
Here is my current JS code:
window.onload = refreshBlock();
function refreshBlock()
{
document.getElementById("video").innerHTML = "<img src='image1.jpg' width='1000' height='500'></img>"
setInterval("refreshBlock();",100);
}
First of all, there are two different built-in JavaScript functions to execute some code with a delay.
setInterval() will execute the code every X milliseconds automatically, while
setTimeout() will execute the code once after X milliseconds
What you're currently doing is calling refreshBlock() every 100 milliseconds, and in that function generating a new interval, so after a few iterations, you end up with hundreds of intervals growing exponentially.
You can either put setInterval() outside of the callback function or call setTimeout inside of the callback function to avoid this.
In addition to that,
window.onload = refreshBlock();
is not doing what you think it's doing. By calling the function via (), you are setting window.onload to the result of the execution of refreshBlock(). By that time, any elements referenced inside the function might not yet be in the DOM. Instead, you want to set merely the function reference as the onload callback on the window object:
window.onload = refreshBlock;
I suggest to only change the SRC of the image instead of the whole tag:
<html>
<body>
<div id="video">
<img src='image1.jpg' width='1000' height='500' id="image"></img>
</div>
<script>
window.onload = refreshBlock;
function refreshBlock()
{
document.getElementById("image").src="image4.jpg";
setTimeout("refreshBlock",1000);
}
</script>
</body>
</html>
Also "setTimeout" is more what you need than "setInterval".
you want o change the images constantly this is a simple example for three images it will keep switching between these images constantly so by another meaning the images will keep changing there are many example i have but i believe this is the easiest one
refreshBlock();
function refreshBlock() {
var x = 0;
//image 1
document.getElementById("v").innerHTML =" <img src='image1.jpg' width='1000' height='500'></img>";
setInterval(function() {
if (x == 0) {
//image 2
document.getElementById("v").innerHTML =" <img src='image2.jpg' width='1000' height='500'></img>";
} else if (x == 1) {
//image 3
document.getElementById("v").innerHTML =" <img src='image3.jpg' width='1000' height='500'></img>";
}
x++;
if (x == 2) {
x = 0;
}
}, 5000);
}
You don't need a window.onload event to start your updates. The code below start as soon as the page is loaded, loops every 100ms and terminates when you close or reload the page.
let handle = setInterval( () => {
document.getElementById("video").innerHTML = "<img src='image1.jpg' width='1000' height='500'></img>"
}, 100);
To terminate the setInterval loop at any time you can use clearInterval(handle)
Related
I'm trying to make an automated image gallery using javascript to paste img-statements (+ some extras for css) into html.
All the images are in the same folder and are named image (1), image (2), ... Apparently client side can't know the name of the files in the folder nor the amount of files.
The append-process works fine, but I can't find a way to stop without giving the amount of pictures myself.
I'm trying to stop the append-process using ".onerror" when the browser can't find the next image, but it is always skipped until the end (resulting in an infinite loop (I'm using a "i<=6" for testing)).
Thanks! Here is my code:
function showgallery() {
let flag = true;
let i = 1;
while (i <= 6 && flag) {
$("#fotos").append(`<div class="cssbox">
<a id="image${i}" href="#image${i}"><img id="picture${i}" class="cssbox_thumb" src="../photogallery/image (${i}).jpg">
<span class="cssbox_full"><img src="../photogallery/image (${i}).jpg" /></span>
</a>
<a class="cssbox_close" href="#void"></a>
<a class="cssbox_prev" href="#image${i-1}"><</a>
<a class="cssbox_next" href="#image${i+1}">></a>
</div>`);
document.getElementById(`picture${i}`).onerror = () => {
flag = false;
}
i++;
}
}
window.onload = showgallery;
The reason why it's skipping some is because it takes time to load each image and for onerror to be called, yet you are doing this all in a loop which executes all the code without waiting for the error, so even if there is an error the flag variable won't be changed until the error event is fired, which happens after the current loop cycle
The way to do this instead is use recursion, if a certain condition is not met yet. Also I would recommend using Image for testing then appending it to the document
Also you don't even need error you can just only append it if it loads successfully
So you can use recursion here like
var cur = 0
function getImg() {
var img= new Image ()
img.src = "image (" + (cur++) + ").jpg"
img.onload = () => {
fotos.appendChild(img)//or other span elements etc that have img as a child
getImg()
}
//if you want to know when it ended then you can use .onerror
img.onerror = () => console.log("done")
}
getImg()
I know there has been many topics on Javascript Timers however, my timers are in effect "Doubling" every time my mouse hovers over a div to call a command, they are not consistent.The divs below show the onmouseover event which calls the functions.
<div id="Team_Container2"><div id="Image1" onmouseover="area_hover1(this);area_hover2(this)"></div>
<div id="Team_Container2"><div id="Image2" onmouseover="area_hover1(this);area_hover2(this)"></div>
function area_hover1(obj) {
var interval;
clearInterval(interval);
href = $(obj).attr('href');
url = href.split('#');
url1 = url[1];
interval = setInterval(function() {setAreaOver(document.getElementById(url1), 'Seating_Plan_Image_canvas', '0,0,0', '0,0,0', '0.33', 0, 0, 0);}, 1000);
return;
}
function area_hover2(obj) {
var interval;
href = $(obj).attr('href');
url = href.split('#');
url1 = url[1];
clearInterval(interval);
interval = setInterval(function() {setAreaOver(document.getElementById(url1), 'Seating_Plan_Image_canvas', '0,0,0', '0,0,0', '0.0', 0, 0, 0);}, 2000);
return;
}
How could i adjust the timer or merge the two functions into one and perform one "setInterval" after the other one.
I need the area_hover2 set Interval to come like 500 milliseconds after the first Area_hover1 set interval if that makes sense.
Any help would be most appreciated!
Thanks
Aj
Every time you hover over your image, you kick off a new setInterval, since your clearInterval() command isn't really doing anything. You defined the variable holding the setInterval() pointer inside the hover function, so as soon as it exits, that variable is gone. What you need is:
var interval; // Defined in global scope
function area_hover1(obj) {
clearInterval(interval); // Abort any existing hover interval
// Set up variables
interval = setInterval(function() { /* doStuff */ }, 1000);
}
You may also need to capture the onMouseOut event to stop the interval as well, since right now it will keep running even after the mouse is no longer hovering over the element.
I need to send an alert to the user every time the z-index equals 2. Unfortunately it only occurs onload, or ready...whatever...
heres the html
<div id='slides'>
<img class='sliderImg' src='img.jpg'>
<img class='sliderImg' src='img.jpg'>
<img class='sliderImg' src='img.jpg'>
</div>
and the Javascript
document.ready=function(){
var theImage=$('.sliderImg')[0];
if(theImage.style.zIndex==2){
alert(theImage.style.zIndex);
}
}
You have two choices:
1) Run a timer and call your function periodically, using setInterval or setTimeout
2) Listen for DOM changes, then run your function.
You can use setInterval function after t time to check the z-index like this :
window.setInterval(function(){
var theImage=$('.sliderImg')[0];
if(theImage.style.zIndex==2){
alert(theImage.style.zIndex);
}
},10000);
It will be called on every 10 seconds.
jQuery style :
document.ready = function(){
checkZIndexOfImage(zIndex);
window.setInterval(checkZIndexOfImage, 10000);
}
function checkZIndexOfImage(zIndex) {
var theImage=$('.sliderImg').first(); //or $('.sliderImg').eq(0)
var tempzIndex = theImage.style('z-index');
tempzIndex = parseIng(zIndex);
if (isNaN(tempzIndex)) { //Let's check z-index is number
tempzIndex = 0;
}
if(tempIndex === zIndex){
alert(tempzIndex );
}
}
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>
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