Trying to change div by class every 5 seconds jquery - javascript

Good morning,
I am trying to create an array of classes and with a 5 second interval, I would like to add and remove class replacing the current div. This is for a carousel where I currently have the background image changing at this time. I would now like to make my descriptive text alternate in the same way. Can anyone help?
I was thinking an if statement checking the current background could work. Howver I get this error: 'unexpected token {'
$(document).ready(function(){
/* H E A D E R C A R O S U E L */
$(function() {
var headCarosuel = $(".headCarosuel");
var backgrounds = new Array(
"url('./img/backgroundVinny1.jpg')","url('./img/backgroundVinny2.jpg')"
);
var current = 0;
function nextBackground() {
$(".headCarosuel").css("background", backgrounds[current = ++current % backgrounds.length]);
setTimeout(nextBackground, 5000);
}
setTimeout(nextBackground, 5000);
$(".headCarosuel").css("background", backgrounds[0]);
if(backgrounds = $("url('./img/backgroundVinny1.jpg')").css() {
$('.headCarosuelText').removeClass('description2').addClass('description1');
}
else {
$('.headCarosuelText').removeClass('description1').addClass('description2');
}
});
});

To do something every 5 seconds in javascript, you can use setInterval, for instance:
setInterval(function(){
//your code
,5000);
This will run the code every 5000ms or 5s.

Maybe something like this:
var classes = [
'class1',
'class2',
'class3',
'class4',
'class5'
]
var classIndex = 0;
function loopClasses() {
var currentClass = classes[classIndex];
// loop through classes and remove from element
for (var i = 0; i < classes.length; i++) {
$('.element').removeClass(classes[i]);
}
// add current class to element
$('.element').addClass(currentClass);
// advance or reset loop counter
classIndex = (classIndex + 1) % classes.length
}
setInterval(loopClasses, 5000);

Related

Play Boostrap Popover on loop

DEMO: http://jsfiddle.net/0s730kxx/
I'm trying to open Bootstrap Popover to auto-open on loop but so far I've have manage only to auto-play once.
HTML:
<div class="container">
Hover Left |
Hover Right |
Click Me
</div>
JS:
$(document).ready(function(){
var time = 1000;
var len = $('.myclass').length;
var count = 0;
var fun = setInterval(function(){
count++;
if(count>len){
clearInterval(fun);
}
$('.p'+count).popover('show');
if(count>1){
var pre = count-1;
$('.p'+pre).popover('hide');
}
}, time);
});
Could anyone help? I want it on loop so it plays forever or atleast 10 or 20 times.
Modify javascript part of your fiddle like this:
$(document).ready(function(){
var time = 1000;
var len = $('.myclass').length;
var count = 0;
var fun = setInterval(function(){
count++;
if(count>len){
$('.p'+(count-1)).popover('hide');
count = 1;
//clearInterval(fun);
}
$('.p'+count).popover('show');
if(count>1){
var pre = count-1;
$('.p'+pre).popover('hide');
}
}, time);
});
Since you are not clearing the interval in this modified snippet, it will run forever as you expected.
Thats because you have added line
if(count>len){
clearInterval(fun);
}
After showing them 1 time count is 3 and clearInterval(fun) is called
which terminates further call to function fun().
Original comment: You can't clear the interval and expect the loop to continue! Instead of clearing set the count back to 0. But you'll also need to remember to hide the last popover.
var fun = setInterval(function(){
count++;
$('.p' + count).popover('show');
if(count > 1){
$('.p' + (count - 1)).popover('hide');
}
if(count > len){
count = 0;
}
}, time);
Here is a fiddle: http://jsfiddle.net/89gcqnfm/
Simplicity and modular arithmetic are your friends:
$(document).ready(function(){
var time = 1000;
var eles = $('.myclass');
var count = 0;
var fun = setInterval(function(){
if(eles.length < 1)
return (console.log("No elements found!")&&!1) || clearInterval(fun);
eles.eq(count%eles.length).popover('hide');
eles.eq(++count%eles.length).popover('show');
}, time);
});
https://jsfiddle.net/L2487dfy/

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

Trying to randomize words from an array and stop the loop after 5

I'm trying to write a script that will pick a random word from an array called words, and stop the loop after 5 times and replace the html with Amazing. so it always ends on amazing. Can't figure out best practice for something like this. My thinking is there just don't know where to put the script ender or how to properly implement this.
I feel like I need to implement something like this into my script, but can't figure out where. Please help.
if(myLoop > 15) {
console.log(myLoop);
$("h1").html('AMAZING.');
}
else {
}
Here is the Javascript that I'm using to loop and create bring new words in.
$(document).ready(function(){
words = ['respected​', 'essential', 'tactical', 'effortless', 'credible', 'smart', 'lucid', 'engaging', 'focussed', 'effective', 'clear', 'relevant', 'strategic', 'trusted', 'compelling', 'admired', 'inspiring', 'cogent', 'impactful', 'valued']
var timer = 2000,
fadeSpeed = 500;
var count = words.length;
var position, x, myLoop;
$("h1").html(words[rand(count)]);
function rand(count) {
x = position;
position = Math.floor(Math.random() * count);
if (position != x) {
return position;
} else {
rand(count);
}
}
function newWord() {
//clearTimeout(myLoop); //clear timer
// get new random number
position = rand(count);
// change tagline
$("h1").fadeOut(fadeSpeed, function() {
$("h1").slideDown('slow'); $(this).html(words[position]).fadeIn(fadeSpeed);
});
myLoop = setTimeout(function() {newWord()}, timer);
}
myLoop = setTimeout(function() {newWord()}, timer);
});
Here's my codepen
http://codepen.io/alcoven/pen/bNwewb
Here's a solution, which uses a for loop and a closure.
Words are removed from the array using splice. This prevents repeats.
I'm using jQuery delay in place of setTimeout:
var i, word, rnd, words, fadeSpeed, timer;
words = ['respected​', 'essential', 'tactical', 'effortless', 'credible', 'smart', 'lucid', 'engaging', 'focused', 'effective', 'clear', 'relevant', 'strategic', 'trusted', 'compelling', 'admired', 'inspiring', 'cogent', 'impactful', 'valued'];
fadeSpeed = 500;
timer = 2000;
for(i = 0 ; i < 6 ; i ++) {
if(i===5) {
word= 'awesome';
}
else {
rnd= Math.floor(Math.random() * words.length);
word= words[rnd];
words.splice(rnd, 1);
}
(function(word) {
$('h1').fadeOut(fadeSpeed, function() {
$(this).html(word);
})
.slideDown('slow')
.delay(timer)
.fadeIn(fadeSpeed);
}
)(word);
}
h1 {
text-transform: uppercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1></h1>
I added an iteration counter to check how many times it has changed.
Added this by other variables:
var iter = 1;
Added this in the newWord function:
iter = iter + 1;
if (iter > 5) {
return;
}
var word;
if (iter == 5) {
word = 'awesome';
}
else {
...
Here's my solution by changing your code:
http://codepen.io/anon/pen/YPGWYd

Change img src every second using Jquery and Javascript

I have been trying to write a script that changes an image src every two seconds based on a list.
So, everything is inside a forloop that loops over that list:
$(document).ready(function() {
var lis = {{dias|safe}}; <----- a long list from django. This part of the code works fine.
for (i=0; i<lis.length; i++){
src_img = lis[i][1];
var timeout = setInterval(function(){
console.log(src_img)
$("#imagen").attr("src", src_img);
}, 2000)
}
});
It doesn't work, the console logs thousands of srcs that correspond to the last item on the list. Thanks a lot for your help.
you don't need to run cycle in this case, you just save "pointer" - curentImage and call next array item through function ever 2 sec
var curentImage = 0;
function getNextImg(){
var url = lis[curentImage];
if(lis[curentImage]){
curentImage++;
} else {
curentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
var curentImage = 0;
var length = lis.length;
function NewImage(){
var url = lis[curentImage];
if(curentImage < length){
currentImage++;
}
else{
currentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
PS: Better than the previous one, Checks for lis length and starts from first if you reach end.
You need something like this
$(document).ready(function() {
var index = 0;
setInterval(function(){
src_img = lis[index++ % lis.lenght][1]; // avoid arrayOutOfBounds
$("#imagen").attr("src", src_img);
}, 2000)
});

How can I stop a repeating function when the mouse is clicked?

I could really use some help. I have a javascript / jquery slider below that repeats over and over. I would like it to stop repeating when a specific button is clicked if possible. I am a complete novice and it took a lot to get to this point! Any help would be greatly appreciated.
$(document).ready(function () {
var i = 0;
var z = 0;
delay = 5000;
var el = $('#scroll-script');
var ql = $('#info-box');
var classesb = ['fp-info-one', 'fp-info-two', 'fp-info-three', 'fp-info-four'];
var classes = ['fp-slide-one', 'fp-slide-two', 'fp-slide-three', 'fp-slide-four'];
var interval = setInterval(function () {
el.removeClass().addClass(classes[i]);
i = (i + 1) % 4;
ql.removeClass().addClass(classesb[z]);
z = (z + 1) % 4;
}, delay);
});
$(document).ready(function () {
var i = 0;
var z = 0;
delay = 5000;
var el = $('#scroll-script');
var ql = $('#info-box');
var classesb = ['fp-info-one', 'fp-info-two', 'fp-info-three', 'fp-info-four'];
var classes = ['fp-slide-one', 'fp-slide-two', 'fp-slide-three', 'fp-slide-four'];
var interval = setInterval(function () {
el.removeClass().addClass(classes[i]);
i = (i + 1) % 4;
ql.removeClass().addClass(classesb[z]);
z = (z + 1) % 4;
}, delay);
// code that stop repeat
$('#your_button').on('click', function() {
clearInterval(interval );
});
});
As, you're using setInterval() for repeating time, so to clear that timer you need to use clearInterval()..
Note
#your_button will be replace with appropriate selector for your target button.
You just need to use clearInterval():
$(".somebutton").click(function()
{
clearInteval(interval);
interval=null;
});
i think clearInterval() help you to achieve this.
just apply this on click() event.
something like:
$('#element').click(function(){
clearInterval(Interval_OBJECT);
});
Use clearInterval(interval) when you want to stop the repeating action.
something like :
$('#btn').on('click', function(){ clearInterval(interval); });

Categories

Resources