Displaying image from array in Javascript in setTimeInterval method - javascript

I am having little bit difficulty time pausing the image, so it gets rendered. I have images stored in even index in an array (for example: 2, 4, 6). And using for loop, I want to change the image every 2 seconds. On the load of the HTML page, I call onLoad = executeOnLoad() in HTML. The image changes from default to the image that is in sixth index, but after that it is not changing. It stays on that same index although, the console says the i is changing.
function executeOnLoad(){
for(var i = 0; i < 7; i++){
if (i%2 == 0) {
console.log("started.."+i);
displayImage(i);
}
}
}
function displayImage(i){
console.log("displaying...." + i);
document.getElementById("initial_image").src = contentArray[i];
}
window.setInterval("executeOnLoad()", 1000);
This is the console output that repeats every 1 sec but image is not changing:
started..0
displaying....0
started..2
displaying....2
started..4
displaying....4
started..6
displaying....6 < ---- The image here is displayed but, not changing to other..
I appreciate your help. Thanks.

I've created a fiddle for you that shows even numbers.
I've used the if statement instead of the for loop you had because that would run all the loop in one go.
See it working here:
var contentArray = ["0.png","1.png","2.png","3.png","4.png","5.png","6.png","7.png","8.png"]
var i = 0;
var numberOfImagesToDisplay = 6;
var speedOfAnimation = 1000;
function executeOnLoad(){
if(i <= numberOfImagesToDisplay){
if (i%2 == 0) {
displayImage(i);
i = i+2;
} else {
i++;
}
} else {
i=0;
displayImage(i);
}
}
function displayImage(img){
document.getElementById("initial_image").src = "http://www.marcelogil.com/fiddle/jsloop/" + contentArray[img];
}
window.setInterval("executeOnLoad()", speedOfAnimation);
<img src="http://www.marcelogil.com/fiddle/jsloop/0.png" id="initial_image" />

There is no pause in your code. That loop just runs through all of your images and therefore only the last one will "stick".
You can fix this by using settimeout:
console.clear();
document.body.innerHTML = '';
//START
var contentArray = [
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg',
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg',
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg',
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg',
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg',
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg',
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg'
]
var initImg = document.createElement("img");
initImg.id = "initial_image";
initImg.src = '';
document.body.appendChild(initImg);
function executeOnLoad() {
for (var i = 0; i < 7; i++) {
if (i % 2 == 0) {
(function (a) {
setTimeout(function () {
console.log("started.." + a);
displayImage(a);
}, 1000 * (a + 1))
})(i);
}
}
}
function displayImage(i) {
console.log("displaying...." + i, contentArray[i]);
document.getElementById("initial_image").src = contentArray[i];
}
executeOnLoad();

See this code, with some small changes. The interval does not have a loop inside it, but a single action. Each time the setInterval callback is called (i.e every one second) it goes one step further, until reaching the maximum desired length (which is 7, but should probably be contentArray.length) and then the interval clears itself. Clearing the interval is possible thanks to saving a refernce to it when declaring it (var interval = window.setInterval(...) and using the clearInterval method.
var i = 0, interval;
function executeOnLoad(){
i++;
if (i%2 == 0) {
console.log("started.."+i);
displayImage(i);
}
if (i >= 7) {
clearInterval(interval);
}
}
function displayImage(i){
console.log("displaying...." + i);
document.getElementById("initial_image").src = contentArray[i];
}
interval = window.setInterval(executeOnLoad, 1000);

Check this:
var i = 0;
var contentArray = [];
contentArray.push('https://img.utdstc.com/icons/256/beautiful-life-quotes-android.png');
contentArray.push('https://img.utdstc.com/icons/monospace-android.png');
contentArray.push('https://img.utdstc.com/icons/cloud-print-android.png');
contentArray.push('https://img.utdstc.com/icons/120/desire-the-game-for-couples-android.png');
function displayImage(){
console.log("displaying...." + i);
if(i < ((contentArray.length) - 1)){
i++;
}else{
i = 0;
}
document.getElementById("initial_image").src = contentArray[i];
window.setTimeout( displayImage, 4000);
}
displayImage();
<img id="initial_image"/>
See a working example on JSFiddle

Related

Having real trouble combining 2 JS

I am struggling combining two JS into one… I try and try in the JSFiddle but can not really understand the console erros…
I am trying to have a background-color that changes combined with a changing background .svg in a div…
$(document).ready(function() {
//Initializing
var i = 0;
var images = []; //array
var time = 3000; // time in millie seconds
//images
images[0] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_1.svg)";
images[1] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_2.svg)";
images[2] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_3.svg)";
images[3] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_4.svg)";
//function
function changeImage() {
var el = document.getElementById('header');
el.style.backgroundImage = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout('changeImage()', time);
}
window.onload = changeImage;
$(function setbackground() {
window.setTimeout( "setbackground()", 2000);
var index = Math.round(Math.random() * 4);
var ColorValue = "FA89CB";
if(index == 1)
ColorValue = "FAED96";
if(index == 2)
ColorValue = "D27DFA";
if(index == 3)
ColorValue = "6CFA64";
if(index == 4)
ColorValue = "8370FA";
document.getElementsByTagName("body")[0].style.backgroundColor = "#" + ColorValue;
});
});
Here's my fiddle:
http://jsfiddle.net/gmck02ru/1/
does somebody have a clue – i guess I am not really understanding what I am doing here so far...
Help please!
The issue is because the syntax you've used to define the setbackground() function is incorrect. You've placed it inside a jQuery object. That function is also never called. You should define it as a standalone function and invoke it when the page loads.
In addition there's a few improvements you can make to the logic.
Use addEventListener() over setting the onclick or other onX event properties.
Declare the elements of the array at the same time as you define the array itself.
Use an array to hold the background colours instead of hard-coding an if statement.
Use the modulo operator when incrementing the counter to save having to write logic to reset to 0
If you want to repeatedly update the background colour, as you do for the images, place the setTimeout() call within the setbackground() function.
Use document.body directly instead of getting it by tag name
$(document).ready(function() {
let i = 0;
let images = [
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_1.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_2.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_3.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_4.svg)"
];
let backgroundColours = ['#FAED96', '#D27DFA', '#6CFA64', '#8370FA']
function changeImage() {
let el = document.getElementById('header');
el.style.backgroundImage = images[i];
i = ++i % (images.length - 1)
setTimeout(changeImage, 3000);
}
changeImage();
function setbackground() {
let index = Math.round(Math.random() * 4);
document.body.style.backgroundColor = backgroundColours[index];
setTimeout(setbackground, 2000);
}
setbackground();
});
Working jsFiddle - see the demo in the fiddle as the images are on an insecure domain so cannot be called from SO.

print javascript while loading

This is my code:
function myFunction(text, word){
var pos1;
do{
pos1 = text.indexOf(word);
if(pos1 !== -1){
document.getElementById("id1").innerText = pos1;
}
}while(pos1 == -1);
}
myFunction(text, "sun");
myFynction(text, "rain");
myFynction(text, "gold");
myFynction(text, "hello");
myFynction(text, "laptop");
myFynction(text, "tree");
I get text from file_get_contents of a page.
This page is continuously updating so, slowly, i will find those words through myFunction. What I want is to print those function meanwhile they finish
I really don't know if it's possible to use javascript to continuously monitor the HTML that is being loaded into the current page. It would require a few tests. However this would be my approach. (This function stops after finding one of the words in the array and displaying the pos)
var words = ['sun', 'rain', 'gold', 'HTML'];
function myFunc() {
var text = document.body.innerHTML;
var pos1;
for (var i=0; i < words.length; i++) {
pos1 = text.indexOf(words[i]);
if(pos1 !== -1){
document.getElementById("id1").innerText = pos1;
break;
}
}
if (pos1 === -1) {
// wait 1 second, try again
setTimeout(myFunc, 1000);
}
}
myFunc();
<div id='id1'></div>

How do I change div text using array values with Javascript?

I am building a website and the homepage will basically have 2 div's containing text. I want one of the divs to change every 2 seconds with values I've placed in an array
var skills = ["text1","text2","text3","text4"];
var counter = 0;
var previousSkill = document.getElementById("myGreetingSkills");
var arraylength = skills.length - 1;
function display_skills() {
if(counter === arraylength){
counter = 0;
}
else {
counter++;
}
}
previousSkill.innerHTML = skills[counter];
setTimeout(display_skills, 2000);
innerHTML is evil, use jQuery! (assuming because you have it selected as a tag)
Working fiddle
(function($) {
$(function() {
var skills = ["text1","text2","text3","text4"],
counter = skills.length - 1,
previousSkill = $("#myGreetingSkills"),
arraylength = skills.length - 1;
function display_skills() {
if (counter === arraylength) {
counter = 0;
}
else {
counter++;
}
previousSkill.html(skills[counter]);
}
display_skills();
setInterval(function() {
display_skills();
}, 2000);
});
})(jQuery);
You need to wrap display_skills inside a function in your setTimeout() and use setInterval() instead.
var myInterval = setInterval(function(){display_skills()}, 2000);
And make sure you call previousSkill.innerHTML = skills[counter]; inside your interval'd function - else it will run just once.
You can terminate your interval with window.clearInterval(myInterval);
Use array.join().
The syntax of this function is array.join(string), where3 string is the joining character.
Example:
[1, 2, 3].join(" & ") will return "1 & 2 & 3".
Hope this helps,
Awesomeness01

How to fade in divs in sequence with Javascript (jQuery)?

What i want is to fade in my sidebar boxes after each other on page load by adding a class.
I have tried the following:
var a = $(".sidebar-box"), delayTime = 2000;
for(var i = 0; i < a.length; i++) {
setTimeout(function(
var ai = $(a[i]);
ai.addClass("fade in");
console.log(ai);
), delayTime);
console.log(delayTime);
delayTime += 2000;
}
The problem is, by the time the class gets added the first time, i already is 4, so the class only gets added to the last box, when actually it should be added to the first one.
You need to create a separate function so that variable i is copied each time:
var a = $(".sidebar-box"), delayTime = 2000;
var func = function(i)
{
setTimeout(function() {
var ai = $(a[i]);
ai.addClass("fade in");
}, delayTime);
}
for(var i = 0; i < a.length; i++) {
func(i);
delayTime += 2000;
}
Instead of adding a class and animating via CSS, if you are okay with using jQuery's fadeIn() method, you can have it like:
var a = $(".sidebar-box"), delayTime = 2000, i = 0;
function animateSideBar() {
if(i >= a.length) return;
// call fadeIn, and pass this function itself as the completion callback
$(a[i]).fadeIn(delayTime, animateSideBar);
i++;
}
animateSideBar(); // start it

Change Attribute Every Second

I want an image to change every second. I'm having trouble with setInterval. Could someone post a quick snippet on how to do this
This is what I came up with.
var images = 'images/image_*.png';
for(var i = 1; i <= 5; i++){
function changeImg(){
var path = images.replace('*', i);
$('img').attr('src', path);
}
setInterval('changeImg()', 1000);
}
In your code you are calling the setInterval function 5 times which really is not necessary. Also as the loop will execute once, the value of i will always be 5 so it won't work as you expect. You may try this instead:
var images = 'images/image_*.png';
var i = 1;
setInterval(function() {
var path = images.replace('*', i);
$('img').attr('src', path);
i = i + 1;
if (i == 6) i = 1;
}, 1000);
Your loop was still continuing without waiting. Try writing it this way:
var images = 'images/image_*.png',
i = 1;
function changeImg(){
var path = images.replace('*', i);
$('img').attr('src', path);
i = (i == 5 ? 0 : i + 1);
}
window.setInterval(changeImg, 1000);
var images = 'images/image_*.png';
var i = 1;
function changeImg(i){
var path = images.replace('*', i);
$('img').attr('src', path);
}
setInterval('changeImg('+ ( (i++)%6 ) +')', 1000);
Maybe something like this ? I didn't test it though.

Categories

Resources