I am trying to make a changing background. So what I am trying to do is using SetInterval to change my background but whenever it changes, it leaves a white background and then turn to the image like I intend. Any advices on how to fix it?
My code:
var image = new Array();
image.push("url('./1.png')");
image.push("url('./2.png')");
image.push("url('./3.png')");
image.push("url('./4.png')");
image.push("url('./5.png')");
var imagenum = 0;
function changeBackground () {
imagenum++;
if (imagenum==5) {
imagenum = 0;
}
document.getElementById("bodydiv").style.backgroundImage = image[imagenum];
}
function init () {
setInterval(function () {changeBackground()},1000);
}
Bonus: If I set the setInterval a little bit lower, I will have the whole blank site. It works perfectly due to the code, but the flash really irritates me. Can anyone help me with it?
I placed the init() function in the preloadImages() one because it forces init() to only ever run when all images are preloaded. There are other ways to do this however.
var images = new Array();
function preloadImages() {
i=1
foreach(preloadImages.arguments as img)
images[i] = new Image()
images[i].src = img
i++
}
init()
}
function changeBackground () {
imagenum++;
if (imagenum==5) {
imagenum = 0;
}
document.getElementById("bodydiv").style.backgroundImage = image[imagenum];
}
function init () {
setInterval(function () {changeBackground()},1000);
}
var image = [
'./1.png',
'./2.png',
'./3.png',
'./4.png',
'./5.png'
]
preloadImages(image);
Related
i'm trying to cycle through 3 images using a for loop in javascript. Here is my code:
<img name="slide" width="300" height="300">
var i=0;
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
function changeImage () {
for(i=0; i < images.length; i++) {
document.slide.src = images[i];
}
}
window.onload = changeImage;
Currently, only image 3 is displayed. Anyone know what i'm doing wrong here?
Yes - this is because your for loop run finishes instantly so there's no time for slides 1 and 2 to be shown.
Give this a try:
var currentImage = 0,
images = [
"https://unsplash.it/200/300?image=100",
"https://unsplash.it/200/300?image=101",
"https://unsplash.it/200/300?image=102"
];
function initSlideshow() {
setImage(0);
setInterval(function(){
nextImage();
},1000);
}
function nextImage() {
if(images.length === currentImage + 1){
currentImage = 0;
} else {
currentImage++;
}
setImage(currentImage);
}
function setImage(image) {
document.querySelectorAll('.slide')[0].src = images[image];
}
window.onload = initSlideshow();
Example: https://jsfiddle.net/vvbdwazc/
Currently, only image 3 is displayed. Anyone know what i'm doing wrong
here?
it's all being displayed but the reason why you can only see the 3rd image is because you're not pausing for a certain time before displaying the next image hence it seems like it's not working.
use setInterval() method to show each image after a specified time.
Example:
var i=0;
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
function changeImage () {
for(i=0; i < images.length; i++) {
document.slide.src = images[i];
}
}
var myVar = setInterval(function(){ changeImage() }, 1000);
You may later wish to prevent the setInterval() method from executing any longer in that case have a look at clearInterval().
window.onload = changeImage; tells me you want to change the image on page load event? In other words, the image changes only upon page load (or refresh).
Since state is not maintained by default (eg local storage or session storage or cookies) your best bet would be to use a random generator to choose randomly. See Generating random whole numbers in JavaScript in a specific range?
This is because the for works so fast it gets quickly to the third image. You could use instead some setInterval like this:
<img id="slide" width="300" height="300">
<script>
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
var i = 0;
setInterval(function() {
var slide = document.querySelector("#slide"); //Select the img element by ID
slide.src = images[i++];
if(i > images.length - 1)
i = 0;
}, 1000); //Time in milliseconds
</script>
This will change constantly back to the first image when it reaches the last one.
Edit: Forgot to mention. setInterval works like a "repeater", it will work indefinitely until you clear it. To clear it you need to asign it to a variable and then use clearInterval passing the variable.
var interval = setInterval(function(){}, 1000) //example
clearInterval(interval);
Like so.
I realize there are more than a few answers on here about this but this particular instance has a very individual problem. I need to, on click, replay this png sequence after clearInterval has been used.
var myImage = document.getElementById("myImage");
var animationArray = ['assets/calvin_hobbes_dance00.png',
'assets/calvin_hobbes_dance01.png',
'assets/calvin_hobbes_dance02.png',
'assets/calvin_hobbes_dance03.png',
'assets/calvin_hobbes_dance04.png',
'assets/calvin_hobbes_dance05.png',
'assets/calvin_hobbes_dance06.png',
'assets/calvin_hobbes_dance07.png',
'assets/calvin_hobbes_dance08.png',
'assets/calvin_hobbes_dance09.png',
'assets/calvin_hobbes_dance10.png'];
var animationIndex = 0;
function changeImage () {
myImage.setAttribute("src", animationArray[animationIndex]);
animationIndex++;
if (animationIndex >= animationArray.length) {
animationIndex = 10;
clearInterval(intervalHandler);
}
}
var intervalHandler = setInterval(changeImage, 100);
A secondary question, this is merely a code sample. How might I wrap this so I can use it for elements that have animations attached that when upon focus play the animation?
Thank you.
Just add an onclick handler to your image. In the onclick handler, reset the animationIndex to 0, call clearInterval to clear the interval if it is running, and call the setInterval function again.
var myImage = document.getElementById("myImage");
var animationArray = ['assets/calvin_hobbes_dance00.png',
'assets/calvin_hobbes_dance01.png',
'assets/calvin_hobbes_dance02.png',
'assets/calvin_hobbes_dance03.png',
'assets/calvin_hobbes_dance04.png',
'assets/calvin_hobbes_dance05.png',
'assets/calvin_hobbes_dance06.png',
'assets/calvin_hobbes_dance07.png',
'assets/calvin_hobbes_dance08.png',
'assets/calvin_hobbes_dance09.png',
'assets/calvin_hobbes_dance10.png'];
var animationIndex = 0;
function changeImage () {
myImage.setAttribute("src", animationArray[animationIndex]);
animationIndex++;
if (animationIndex >= animationArray.length) {
animationIndex = 10;
clearInterval(intervalHandler);
}
}
myImage.onclick = function() {
animationIndex = 0;
clearInterval(intervalHandler);
intervalHandler = setInterval(changeImage, 100);
};
var intervalHandler = setInterval(changeImage, 100);
To answer your secondary question, you might want to consider another approach because this could get kind of messy and be hard to maintain in the future. Consider learning how to do animations using HTML canvas. Here is a tutorial I found showing how you could create multiple animations: http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/
In fact, I would advise to change your implementation to use the canvas instead.
I am making a simple image slider that runs through a directory containing images. The images is called "img_1", "img_2" and "img_3", so the point is to just iterate through them. The thing I don't get is how to implement a interval though. I want the images appear for 3 seconds, then change. The function "imgSlider" is on body load.
Edit: I am looking for simple solutions (in pure JS) as I am currently learning JS. Sorry for not clarifying it in the question. Lots of good answers here though!
function changeImg(img, i){
img.setAttribute("src", "img/slider/img_" + i + ".jpg");
}
function imgSlider(){
var img = document.createElement("img");
var targetDiv = document.getElementById("slider");
img.setAttribute("width", "100%");
img.setAttribute("height", "70%");
targetDiv.appendChild(img);
for(i=1; i<4; i++){
setInterval(changeImg(img, i), 3000);
}
}
What you need to do is simple, you have to change the setInterval code like this:
$(function () {
var curImg = 1;
setInterval(function () {
$("img").attr("src", "//placehold.it/100?text=" + ++curImg);
}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="//placehold.it/100?text=1" />
Here, I have given an interval of 2 seconds for checking. I have used jQuery only for the updating of image. If you want it in plain JavaScript, it is possible through your code.
Pure JS Version
var curImg = 1;
setInterval(function () {
document.getElementsByTagName("img")[0].src = "//placehold.it/100?text=" + ++curImg;
}, 2000);
<img src="//placehold.it/100?text=1" />
You can do it this way.
Initialize a counter, that will keep a track of current image to being displayed. Now all we need to is call showImage function that will show the image corresponding to the current value of the counter.
Repeat this every 3sec.
var count = 0;
setInterval( function() {
showImage(count);
count = (count+1)%total_no_of_images
}, 3000)
setInterval takes a function, you need to pass it a reference to a function that it will run at the appropriate interval.
Also, note that as of this writing, the accepted answer assumes there are infinite images and has an "infinite loop" style of interval, which should be avoided if at all possible. Here, I stop the clock after the fifth image.
const changeImg = (img, i) => {
img.setAttribute('src', `img/slider/img_${i}.jpg`);
};
const imgSlider = () => {
const img = document.createElement('img');
const targetDiv = document.getElementById('slider');
img.setAttribute('width', '100%');
img.setAttribute('height', '70%');
targetDiv.appendChild(img);
let i = 0;
const interval = setInterval(
() => {
changeImg(img, i);
i += 1;
if (i > 4) {
clearInterval(interval);
}
},
3000
);
};
I have a masonry grid where the images are black and white and when you hover over them, the color images appear. They are not composite images. They are all separate. (I'm just sorting out bugs for someone else's code)
On initial hover after a fresh page load, there is a delay (and grey overlay) when hovering over. After the initial, it's of course instantaneous when it switches to the color photo.
So what I'm trying to do is pre load the images with some javascript, but I'm having trouble doing this. Below is what I have for code. Also, this is in Wordpress. Not sure if that matters.
All of the images are background images too, not hardcoded into the html. It's all background css. Thanks for any help!
<script language="JavaScript">
$('document').ready(function preloader() {
// counter
var i = 0;
// create object
imageObj = new Image();
// set image list
images = new Array();
images[0]="images/treatment_locations.jpg"
images[1]="images/community_news_events.jpg"
images[2]="images/success_stories.jpg"
images[3]="images/self_assessment.jpg"
images[4]="images/our_associates.jpg"
images[5]="images/treatment_programs.jpg"
images[6]="images/patient_portal.jpg"
images[7]="images/FAQ.jpg"
images[8]="images/what_to_expect.jpg"
// start preloading
for(i=0; i<=8; i++)
{
imageObj.src=images[i];
}
});
</script>
If you overwrite the src in each iteration, you're not giving the browser a chance to fetch the image. You probably only preload the last image.
Try:
var imageObjs = [];
$('document').ready(function preloader() {
// counter
var i = 0;
// set image list
images = new Array();
images[0]="images/treatment_locations.jpg"
images[1]="images/community_news_events.jpg"
images[2]="images/success_stories.jpg"
images[3]="images/self_assessment.jpg"
images[4]="images/our_associates.jpg"
images[5]="images/treatment_programs.jpg"
images[6]="images/patient_portal.jpg"
images[7]="images/FAQ.jpg"
images[8]="images/what_to_expect.jpg"
// start preloading
for(i=0; i<=8; i++)
{
var imageObj = new Image();
imageObj.src=images[i];
imageObjs.push(imageObj);
}
});
That's another aproach, where it stores only the images that were successfully loaded.
var imgObjs = [];
$(document).ready(function preloader() {
// images list
var images = [
'treatment_locations.jpg',
'community_news_events.jpg',
'success_stories.jpg',
'self_assessment.jpg',
'our_associates.jpg',
'treatment_programs.jpg',
'patient_portal.jpg',
'FAQ.jpg',
'what_to_expect.jpg'
];
for (var i in images) {
var img = new Image();
img.src = 'images/' + images[i];
// stores it on array after loading
img.onload = function() {
imgObjs.push(this);
};
}
});
I could not figure out how to stop image intervals when the mouse is over the image.
var myImage = document.getElementById("world");
var imageArray = ["imgs/worldGray.png","imgs/worldGreen.png","imgs/worldPink.png", "imgs/worldYellow.png", "imgs/world.png"];//html picture add here
var imageIndex=0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if(imageIndex >=imageArray.length){
imageIndex =0;
}
}
var intervalHandle=setInterval(changeImage,5000);
// the problem is in the below fucntions
myImage.onmouseover = function(){
clearInterval(intervalHandle);
}
myImage.onmouseout = function(){
setInterval(intervalHandle);
}
I'm not shure why you are setting the interval again using the "intervalHandler", and don't think there is such a use.
http://www.w3schools.com/jsref/met_win_setinterval.asp
You should write
intervalHandle=setInterval(changeImage,5000);
inside onmouseout handler to make it run correctly.
Try putting your script at the bottom of page. It worked for me