jquery animate background images in an infinite loop - javascript

What would be the best way to have an array of background images and loop through them using js/jquery in an infinite loop?
this is what I have so far:
//ANIMATE JUMBOTRON BACKGROUND IMAGE
$(document).ready(function() {
var backgroundImage = [
'url(/static/images/slideshow/slide0.jpg)',
'url(/static/images/slideshow/slide1.jpg)',
'url(/static/images/slideshow/slide2.jpg)',
'url(/static/images/slideshow/slide3.jpg)',
'url(/static/images/slideshow/slide4.jpg)'
];
$('.jumbotron').css('background-image', backgroundImage[0]);
})
this is obviously just the array and simple css, but I am a bit lost on how to loop through the array?

A counter variable and a window.setInterval should do you. Increment the counter every time the interval'd function runs - once you hit the length of the background image array reset it back down to 0.
var backgroundImages = [
'url(/static/images/slideshow/slide0.jpg)',
'url(/static/images/slideshow/slide1.jpg)',
'url(/static/images/slideshow/slide2.jpg)',
'url(/static/images/slideshow/slide3.jpg)',
'url(/static/images/slideshow/slide4.jpg)'
],
backgroundImageCounter = 0,
jumbotron = $('.jumbotron');
window.setInterval(function() {
jumbotron.css('background-image', backgroundImages[backgroundImageCounter]);
backgroundImageCounter++;
if(backgroundImageCounter >= backgroundImages.length) {
backgroundImageCounter = 0;
}
}, 5000);

There is this thing called setInterval.
var count = 0;
var div = document.getElementById('a');
var btn = document.getElementById('b');
var interval = setInterval(function(){
div.innerText = count;
count++;
}, 1000);
btn.addEventListener('click', function(){
clearInterval(interval);
});
<div id="a">0</div>
<button id="b">Stop</button>

Related

Preint one specific array element, when I click stop button

I am repeatedly looping through an array, my aim is to stop the loop and printout a specific element in the array and display it through span id="fruit". please see code below :
var title = ['233249864597', '233209425159', '233201112221', '233546056136', '233266549303', '233209409846', '233501345825', '233248446422', '233546112136', '233541006033', '233502089334', '233552476293', '233268222280', '233202240898'];
var i = 0; // the index of the current item to show
var animate = setInterval(function() {
// setInterval makes it run repeatedly
document
.getElementById('fruit')
.innerHTML = title[i++];
// get the item and increment
if (i == title.length) i = 0;
// reset to first element if you've reached the end
}, 15);
function stop() {
clearInterval(animate);
}
<h1>THE WINNER IS : </h1>
<h1><span id="fruit"></span></h1>
<center><button onclick="stop()">STOP</button></center>
You mean
const title = ['233249864597', '233209425159', '233201112221', '233546056136', '233266549303', '233209409846', '233501345825', '233248446422', '233546112136', '233541006033', '233502089334', '233552476293', '233268222280', '233202240898'];
const winner = title[3]; // for example
var i = 0; // the index of the current item to show
var animate = setInterval(function() {
// setInterval makes it run repeatedly
document
.getElementById('fruit')
.innerHTML = title[i++];
// get the item and increment
if (i == title.length) i = 0;
// reset to first element if you've reached the end
}, 15);
function stop() {
clearInterval(animate);
document
.getElementById('fruit')
.innerHTML = winner;
}
<h1>THE WINNER IS : </h1>
<h1><span id="fruit"></span></h1>
<center><button onclick="stop()">STOP</button></center>
var title = ['233249864597', '233209425159', '233201112221', '233546056136', '233266549303', '233209409846', '233501345825', '233248446422', '233546112136', '233541006033', '233502089334', '233552476293', '233268222280', '233202240898'];
var i = 0; // the index of the current item to show
var animate = setInterval(function() {
// setInterval makes it run repeatedly
//document.getElementById('fruit').innerHTML = title[i++];
// get the item and increment
if (i == title.length) i = 0;
// reset to first element if you've reached the end
}, 15);
function stop() {
clearInterval(animate);
document.getElementById('fruit').innerHTML = title[i++];
}
<h1>THE WINNER IS : </h1>
<h1><span id="fruit"></span></h1>
<center><button onclick="stop()">STOP</button></center>
How about this?
I changed the numbers to fruits because.. well... I just wanted to write out some fruits.
But they can be changed back to numbers ofc.
var fruits = ['Apple', 'Banana', 'Pineapple', 'Orange', 'Kiwi', 'Watermelon'];
var i = 0; // the index of the current item to show
var animate = setInterval(function() {
i++
document
.getElementById('fruit')
// use modulus operator to stay inside array
.innerHTML = fruits[i % fruits.length];
}, 15);
function stop() {
clearInterval(animate);
}
<h1>THE WINNER IS : </h1>
<h1><span id="fruit"></span></h1>
<center><button onclick="stop()">STOP</button></center>

Fade text using jQuery/Javascript with infinite loop

I am currently building a website and want to fade several words at certain interval and certain fading time with infinite loop. This is exactly what I'm trying to achieve:
I've come up with this but don't know how to extend the time each word is displayed independently of fading time, so that it looks like on gif.
var text = ['fade1', 'fade2', 'fade3'];
var counter = 0;
var elem = document.getElementById("fade");
function change() {
jQuery(elem).fadeTo(1400, 0, function() {
this.innerHTML = text[counter];
counter = ++counter % text.length;
jQuery(this).fadeTo(1400, 1, change)
})
}
change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text <span id="fade"></span></p>
You can use jQuery.delay to pause the code for a certain number of milliseconds before moving to the next one:
var timeOnEachText = 2000; // Milliseconds to spend on each before moving to next
var text = ['fade1', 'fade2', 'fade3'];
var counter = 0;
var elem = document.getElementById("fade");
function change() {
jQuery(elem).delay(timeOnEachText).fadeTo(1400, 0, function() {
this.innerHTML = text[counter];
counter = ++counter % text.length;
jQuery(this).fadeTo(1400, 1, change)
})
}
change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text <span id="fade"></span></p>
If you just want to change the interval, you could convert your text array to an array-object and add some values to it, like this:
var text = [
{
text: 'fade1',
fadeIn: 1000,
fadeOut: 500,
timeout: 100,
},
{
text: 'fade2',
fadeIn: 1100,
fadeOut: 1500,
timeout: 1000,
},
{
text: 'fade3',
fadeIn: 500,
fadeOut: 300,
timeout: 3000,
}
];
var counter = 0;
var fadeTimeout = 0;
var elem = document.getElementById("fade");
function change() {
var currentTextItem = text[counter];
setTimeout( () => {
jQuery(elem).fadeTo(currentTextItem.fadeIn, 0, function() {
this.innerHTML = currentTextItem.text;
counter = ++counter % text.length;
jQuery(this).fadeTo(currentTextItem.fadeOut, 1, change)
});
// Set new timeout because in this set up the next item
// controls the timeout of the previous one.
fadeTimeout = currentTextItem.timeout;
}, fadeTimeout );
}
change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text <span id="fade">initial text</span></p>
I don't know if it'll work for you but have you thought about using #keyframes and just hiding showing the images at different intervals? If you know what the data is before hand and the number of images, you can set up key frames and it'll display much nicer.

jQuery nicescroll is not working with dynamic content and other JavaScript function that makes random effect

So here is the thing, I have a sidebar that has big height due the lots of navigation links. And I'm using jQuery nicescroll plugin to make it look fine. In the sidebar I also have h3 tag which makes a random effect of showing letters (see the code) every 4 seconds. So, when it's on - scroll is not working at all for these 4 seconds and you can't do any scrolling. I tried to use $("#sidebar").getNiceScroll().resize() but it doesn't work either. Is there any way to make it work?
<div id="sidebar">
<h3 id="output">Random</h3>
</div>
//Calling for nicescroll function for my sidebar
$(function(){
$("#sidebar").niceScroll({ cursorcolor:"#66aee9", cursorfixedheight: 400 });
})
//Random effect for my h3 tag
setInterval(function(){
$(document).ready(function(){
var theLetters = "abcdefghijklmnopqrstuvwxyz#%&^+=-"; //You can customize what letters it will cycle through
var ctnt = "Random"; // Your text goes here
var speed = 50; // ms per frame
var increment = 8; // frames per step. Must be >2
var clen = ctnt.length;
var si = 0;
var stri = 0;
var block = "";
var fixed = "";
//Call self x times, whole function wrapped in setTimeout
(function rustle (i) {
setTimeout(function () {
if (--i){rustle(i);}
nextFrame(i);
si = si + 1;
}, speed);
})(clen*increment+1);
function nextFrame(pos){
for (var i=0; i<clen-stri; i++) {
//Random number
var num = Math.floor(theLetters.length * Math.random());
//Get random letter
var letter = theLetters.charAt(num);
block = block + letter;
}
if (si == (increment-1)){
stri++;
}
if (si == increment){
// Add a letter;
// every speed*10 ms
fixed = fixed + ctnt.charAt(stri - 1);
si = 0;
}
$("#output").html(fixed + block);
block = "";
}
});
}, 4000);
I change to rows and check it in jsfiddle, looks like working scroll fine.
Before:
setInterval(function(){
$(document).ready(function(){
...
});
}, 4000);
After:
$(document).ready(function(){
setInterval(function(){
...
}, 4000);
});

Jquery: Infinite loop and pause

I have this code
var timeout = 0;
$('#container td').each(function(){
var td = this;
setTimeout(function() {
var new_text = $(td).find(text).html();
popup_text.html(new_text);
popup.fadeIn('fast').delay(1000).fadeOut('slow');
}, timeout);
timeout += 1000 + 1000;
});
I get text from table cells and is displayed in the layer with a delay.
1 question: How do I make this code to run in an endless loop?
2 question: How to do that when you hover the mouse over popop cycle temporarily stopped and then continue?
Thanks a lot!
One way is to put the code to be repeated in a function, and have the function repeat itself at the end:
var timeout = 1000;
var action = function() {
// Do stuff here
setTimeout(action, timeout);
};
action();
However, as ahren suggested, setInterval might be better:
var timeout = 1000;
var action = function() {
// Do stuff here
};
setInterval(action, timeout);
The difference is slight, but if the machine is running slowly for some reason, the setInterval version will run the code every second on average, whereas the setTimeout version will run the code once each second at most.
Neither of those methods really work well with each(), however, so you'll need to store the sequence of popups somewhere and step through them:
var timeout = 1000;
var tds = $('#container td');
var index = 0;
var action = function() {
var td = tds[index];
var new_text = $(td).html();
popup.html(new_text);
popup.fadeIn('fast').delay(1000).fadeOut('slow');
if(++index >= tds.length)
index = 0;
};
setInterval(action, timeout);
action();
Finally, to avoid moving to the next popup while the popup is hovered, you can add a check for that at the start of the function. It's also necessary to rearrange the animations so that they go "check for hover - fade out - change text - fade in".
var timeout = 1000;
var tds = $('#container td');
var index = 0;
var action = function() {
if(popup.is(':hover'))
return;
var td = tds[index];
var new_text = $(td).html();
popup.fadeOut('slow', function() {
popup.html(new_text);
}).fadeIn('fast');
if(++index >= tds.length)
index = 0;
};
setInterval(action, timeout);
action();
jsFiddle: http://jsfiddle.net/qWkYE/2/
If you like the short clean way, then use the jquery-timing plugin and write:
$.fn.waitNoHover = function(){
return this.is(':hover') ? this.wait('mouseleave') : this;
};
$('#popups div').repeat().each($).fadeIn('fast',$)
.wait(200).waitNoHover().fadeOut('slow',$).all()
​
See this on http://jsfiddle.net/creativecouple/fPQdU/3/

jquery background image rotating script doesn't work

I'm writing this script to rotate a background Image every 3 seconds but it doesn't work at all and i'm stumped as to why not.
$(document).ready(function() {
var inc = 0;
var bgImages = new Array();
bgImages.push("Images/backgroundDog-small.jpg");
bgImages.push("Images/backgroundDog1-small.jpg");
bgImages.push("Images/backgroundDog2-small.jpg");
bgImages.push("Images/backgroundDog3-small.jpg");
setInterval(change, 3000);
function change() {
//if we're not at the end of the array
if (inc < (bgImages.length)) {
var image = bgImages[inc];
$('body').css('backgroundImage', image);
console.log(image);
inc++;
//reset the counter inc and go through the array again
} else {
inc = 0;
}
}
});
The background-image attribute in CSS doesn't expect just the image URL; you need to write it like you actually would in a stylesheet: url("example.png")
$('body').css('backgroundImage', 'url("'+image+'")');

Categories