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
Related
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/
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
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)
});
I have a problem, I have 3 button lets say it's called #pos1, #pos2 and #pos3.
I want to makes it automatically click #pos1 button in 2 seconds, after that click the #pos2 after another 2 seconds, and #pos3 after another 2 seconds,
after that back to the #pos1 in another 2 seconds and so on via jQuery.
HTML
<button id="pos1">Pos1</button>
<button id="pos2">Pos2</button>
<button id="pos3">Pos3</button>
Anyone can help me please?
Try
$(function() {
var timeout;
var count = $('button[id^=pos]').length;
$('button[id^=pos]').click(function() {
var $this = $(this);
var id = $this.attr('id');
var next = parseInt(id.substring(4), 10) + 1;
if( next >= count ){
next = 1
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
$('#pos' + next).trigger('click');
}, 2000);
})
timeout = setTimeout(function() {
$('#pos1').trigger('click');
}, 2000);
})
var posArray = ["#pos1", "#pos2", "#pos3"];
var counter = 0;
setInterval(function() {
$(posArray[counter]).triggerHandler('click');
counter = ((counter<2) ? counter+1 : 0);
}, 2000);
That should do the trick, though you did not mention when you want it to stop running.
Well I don't know what you already have but technically it could be done via triggerHandler()
var currentPos = 1,
posCount = 3;
autoclick = function() {
$('#pos'+currentPos).triggerHandler('click');
currentPos++;
if(currentPos > posCount) { currentPos = 1; }
};
window.setInterval(autoclick,2000);
If I have understood you question right, you need to perform click in a continuous loop in the order pos1>pos2>pos3>pos1>pos2 and so on. If this is what you want, you can use jQuery window.setTimeout for this. Code will be something like this:
window.setTimeout(performClick, 2000);
var nextClick = 1;
function performClick() {
if(nextClick == 1)
{
$("#pos1").trigger("click");
nextClick = 2;
}
else if(nextClick==2)
{
$("#pos2").trigger("click");
nextClick = 3;
}
else if(nextClick == 3)
{
$("#pos3").trigger("click");
nextClick = 1;
}
window.setTimeout(performClick, 2000);
}
This is quite buggy but will solve your problem.
using setInterval()
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
var tempArray = ["pos1", "pos2", "pos3"]; //create an array to loop through
var arrayCounter = 0;
setInterval(function() {
$('#' + tempArray[arrayCounter ]).trigger('click');
arrayCounter = arrayCounter <2 ? arrayCounter +1 : 0;
}, 2000);
fiddle here
check your console for fiddle example
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); });