Play Boostrap Popover on loop - javascript

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/

Related

jQuery - Increment number every second but onclick decrease

So I am trying to increase a number every second. So far this works fine but I have an additional condition that doesn't really works and I don't know why.
What I want is that after the value hits 10 or more you can click on a div and something happens with that div but also the value decreases by 10.
My Code:
var counter = 0;
var increment = 10;
var div = document.getElementById('number');
var st = setInterval(function(){
div.innerHTML = ++counter;
if (counter >= 10){
jQuery('#red-block').click(function(e) {
jQuery(this).css('border-radius','15px');
counter = counter -10;
});
}
},1000);
#red-block {
height: 40px;
width: 40px;
background-color: #ff0000;
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="number">1</div>
<div id="red-block"></div>
The problem is that after the counter hits 10 I click, the div changes but the value jumps for example to -17 and also I can click on the div as many times as I want and every times it decreases a big amount. This should only be possible each time the counter hits 10. Anybody has a solution for me what I am doing wrong? I believe it has something to do with setInterval
It happens because you are registering a new click event handler inside your setInterval functions. Move the click registration outside of the setInterval
function.
var counter = 0;
var increment = 10;
jQuery('#red-block').click(function (e) {
if (counter >= 10) {
jQuery(this).css('border-radius', '15px');
counter = counter - 10;
}
});
var div = document.getElementById('number');
var st = setInterval(function () {
div.innerHTML = ++counter;
}, 1000);
Separate this to your setInterval function and then put your if statement inside the click function
jQuery('#red-block').click(function(e) {
if (counter >= 10){
jQuery(this).css('border-radius','15px');
counter = counter -10;
}
});
var counter = 0;
var increment = 10;
var div = document.getElementById('number');
var st = setInterval(function(){
div.innerHTML = ++counter;
},1000);
jQuery('#red-block').click(function(e) {
if (counter >= 10){
jQuery(this).css('border-radius','15px');
counter = counter -10;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="number">1</div>
<div id="red-block">Click Me</div>
The issues are:
You are registering your click event handler every time the
timer function runs, so a single click will trigger the callback
function many times. Just register it one time and within that
callback, check to see if the count should be adjusted.
Even when decreasing the counter by 10, it still increases by one.
Instead, just track the amount you are changing the count by (1 or
-10) and update the output based on the current "change by" value.
Also, since you are using jQuery, go ahead and use it (you've already taken the plunge).
Also (FYI), don't use .innnerHTML when you aren't setting any HTML, use .textContent for that. And, since you are using jQuery, you can use .text() instead of .textContent.
// Here's the jQuery way to get a reference to elements by their id's:
var $div = $('#number');
var $block = $('#red-block')
var counter = 1; // This will be the amount to change by
var count = 0; // This will be the current count at any given time
// Just set up the click event handler once, not every time the interval runs
$block.on("click", function(e) {
// But only do something if the count is right
if (count >= 10){
$(this).css('border-radius','15px');
counter = -10;
}
});
var st = setInterval(function(){
// Now, just adjust the count by the counter
count = count += counter;
$div.text(count); // <-- The jQuery way to set the text of an element
}, 1000);
#red-block {
height: 40px;
width: 40px;
background-color: #ff0000;
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="number">1</div>
<div id="red-block"></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

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)
});

JQuery Auto Click

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

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