I've written a small function that moves/bouces a button every 5 seconds like so:
HTML:
Text
JS:
var interval;
function buttonShake(){
var times = 5;
var speed = 300;
var distance = '15px';
for(var i = 0; i < times; i++) {
twitterButton.animate({
left: '-='+distance
}, speed).animate({
left: '+='+distance
}, speed);
}
}
interval = setInterval(buttonShake, 4000);
What the button does it when clicked, it slides out a hidden box from the right hand side of the page. What I'm trying to do is prevent the button from bouncing once it has been clicked.
So I tried using the following
button.on('click', function(e){
// do the slideout animation
// add "open" class to the box
if(box.hasClass('open')){
clearInterval(interval);
}
});
The button and box elements have been defined correctly and the open class is appended to the box once it slides out, however clearing the interval doesn't appear to be working. It still continuously calls the buttonShake() function every 5 seconds.
Here is a JSFiddle with the full code for a live preview:
http://jsfiddle.net/30tsype8/3/
Am I doing something wrong here?
I noticed that if you leave it for a while, the animation seems to go into overdrive and rather than running for around 3 secs and pausing for a second before starting again, it just constantly bounces. I think jQuery is overlapping its calls and getting confused and stuck in a loop.
As you want to stop bouncing the button when they expand the panel, I would immediately finish the animation after the panel has expanded using finish():
twitterWrapper.animate({
right: right
}, function() {
twitterButton.finish();
});
Updated fiddle
I'm creating a small quiz, mobile app using jQuery Mobile, and I'm displaying a 3 second GIF at certain points. Though, because it is shown many times, I don't want to bother the user each time, and if he/she clicks anywhere on the page it goes to the next page, but I also have set up a setTimeout, which waits for three seconds, meaning of the GIF to display completely and then moves to the next page. As you can see this makes a problem. If I click the GIF, it moves to the next page, and then if I again move to the other page, after three seconds are passed it sends me back to the previous page, due to the setTimeout. I have the following code:
EDIT :
$(document).on("pagechange", function(event, ui) {
var clicked = false;
// Here comes some if-else statements checking which page is currently active
else if ($.mobile.activePage[0].id == "correctGIF") {
correct++;
nextpage = hashtag.concat(page, 'Correct');
$('#correctGIF').append('<img src="images/Correct1.gif">');
$('#correctGIF').click(function() {
clicked = true;
$.mobile.navigate(nextpage);
alert("alert from click");
});
setTimeout(function() {
if (!clicked) {
$.mobile.navigate(nextpage);
alert("alert from timeout");
}
}, 3000);
}
So, I need to somehow synchronize it. If there is a click it should ignore the setTimeout part, and if there is no click it should wait for three seconds for the GIF to finish, meaning should activate the setTimeout part. Also please note that this GIF is displayed many times during the quiz, not just once. Any ideas about this?
Have you tried this approach:
$(document).ready(function () {
$('#correctGIF').off('click').on('click', function () {
alert('navigate from click');
console.log('navigate from click');
if (!$('#correctGIF').hasClass('clickedImageClass')) {
$('#correctGIF').addClass('clickedImageClass');
}
});
setTimeout(function () {
if (!$('#correctGIF').hasClass('clickedImageClass')) {
alert('navigate from timeout');
console.log('navigate from timeout');
}
}, 3000);
});
JsFiddle demo here: http://jsfiddle.net/e35pn/13/
I have made a carousel and using JavaScript setInterval() function for rotate image with fixed interval in carousel. Here's the script that I had used:
var timeOut = 4000;
function showSlide() {
//....script for showing image
}
function pauseSlide() {
setInterval(function(){showSlide();}, timeOut);
}
jQuery(document).ready(function() {
pauseSlide();
});
Now the problem is when I have change the browser tab and after few minute back again to carousel browser and what I seen carousel running too faster rather than default time interval, images going to change fast suppose 0 time interval. Please help me with how I can sort this out.
You must get rid of the first interval before starting another, or you start getting more than one interval working simultaneously (i.e. why you start seeing it go "faster")
Do this
var timeOut = 4000;
var interval = 0;
function showSlide() {
//....script for showing image
}
function pauseSlide() {
clearInterval(interval);
interval = setInterval(function(){showSlide();}, timeOut);
}
jQuery(document).ready(function() {
//NOW you can do multiple pauseSlide() calls
pauseSlide();
pauseSlide();
pauseSlide();
pauseSlide();
pauseSlide();
});
From what I know in newer versions of both firefox and chrome, background tabs have setTimeout and setInterval clamped to 1000ms to improve performance. So I think that your issue might relate to that.
Maybe this will help : How can I make setInterval also work when a tab is inactive in Chrome?
Image changing faster than expected may indicate that you have more than one call to pauseSlide(), in one way or another.
Is document ready the only place you call the function ? Any code in showslide or anywhere triggering a document ready event ? If you put an alert() in pauseSlide(), does it popup more than once ?
I am using a mega menu script I got from here. It works perfectly except seeing as how I have a few of these on my page I would like there to be a delay that the user has to hold their mouse over the link before the menu opens.
I know I need to do this with a setTimeout() tag and a clearTimeout() for when the user does takes their mouse off the link. I just can not figure out where to put this. I've tried just guessing at it but no matter where I put this it seems to either break the function or not matter.
Thank you for any help anyone might be able to provide me with, it is much appreciated.
The basic idea is something like this?
var timeout;
$('#menuID').mouseenter(function(){
clearTimeout(timeout);
$(this).children().show();
}).mouseleave(function(){
timeout = setTimeout(function(){
$(this).children().hide();
},400);
});
Note that the maker used the same way as above:
"p.s: Inside the .js file, there are two variables you may wish to fine tune:"
effectduration: 300, //duration of animation, in milliseconds
delaytimer: 200, //delay after mouseout before menu should be hidden, in milliseconds
Use this function to add a delay on whatever you want
// Function declatation
var delay = (function()
{
var timer = 0;
return function(callback, ms)
{
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
usage:
delay(function()
{
// Do thing you want delayed
}, 1000 );
Replace 1000 with amount of ms you want to delay
EDIT
$("#menuitem").mouseenter(function()
{
delay(function()
{
if($(this).is(':hover'))
// Show menu
}, 1000 );
});
How can I reset the auto-scroll interval on my jCarouselLite carousel after some event so that it lets you look at the content for the full interval, regardless of how far along the timer was when you clicked next or previous? Right now, if I click next or previous after 9 seconds, it scrolls again after 1 second.
In the jCarouselLite source code on lines 274-277 is where the auto-scroll is implemented using setInterval. I know you can use clearInterval if you have the ID returned by setInterval, but there isn't one I can get outside of modifying the source code, and I don't want to do that.
Any ideas? Thanks!
jCarouselLite itself doesn't provide any easy way to stop the auto-scrolling, which is an easier problem then do what you seem to want (?did I understand this right: You just want the autoscroll to temporarily stop on click and then continue)
Hacky + potentially buggy way to stop the autoscroll altogether
var x; //hold interval id
$(function() {
var y = window.setInterval; //backup original setInterval function
//overwrite with new function which stores the id for us
window.setInterval = function() {
x = y(arguments[0], arguments[1]);
return x;
};
//now construct carousel
$(".anyClass").jCarouselLite({
btnNext: ".next",
btnPrev: ".prev",
auto: 500
});
//now restore original setInterval function
//as we only needed the custom one for the carousel to capture the hidden
//internal call to setInterval
window.setInterval = y;
});
$("#stopAutoScrollButton").click(function() {
clearInterval(x);
});
Real solution
As we can't get jCarouselLite to do this on its own we simulate the auto behavior ourself.
$(function() {
var autoTime = 5000; //5s
$(".anyClass").jCarouselLite({
btnNext: ".next",
btnPrev: ".prev"
});
//simulate autoscroll by simulating "click" on next link
var x = setInterval("$('.next').trigger('click');", autoTime);
//if stopAuto is clicked the autoscroll is suspended for autoTime
//no matter how far along the timer already was
$("#stopAuto").click(function() {
clearInterval(x);
x = setInterval("$('.next').trigger('click');", autoTime);
});
});
Here's a version with a pause on mouseover built-in. Works nicely.
http://github.com/cheald/jcarousel-lite
None of these answers were what I was looking for, but this is what comes up when I Google 'jcarousellite reset timer', so for the next person looking to:
Make the timer reset when you click your previous/next slide buttons
Pause the slideshow on hover
Then this is what I put together that works for me:
(function($){$.fn.jCarouselLite=function(o){o=$.extend({btnPrev:null,btnNext:null,btnGo:null,mouseWheel:false,auto:null,speed:200,easing:null,vertical:false,circular:true,visible:3,start:0,scroll:1,beforeStart:null,afterEnd:null},o||{});return this.each(function(){var running=false,animCss=o.vertical?"top":"left",sizeCss=o.vertical?"height":"width";var div=$(this),a=$("#featuredlistings a.next"),ul=$("ul",div),tLi=$("li",ul),tl=tLi.size(),v=o.visible;if(o.circular){ul.prepend(tLi.slice(tl-v-1+1).clone()).append(tLi.slice(0,v).clone());o.start+=v;}var li=$("li",ul),itemLength=li.size(),curr=o.start;div.css("visibility","visible");li.css({overflow:"hidden",float:o.vertical?"none":"left"});ul.css({margin:"0",padding:"0",position:"relative","list-style-type":"none","z-index":"1"});div.css({overflow:"hidden",position:"relative","z-index":"2",left:"0px"});var liSize=o.vertical?height(li):width(li);var ulSize=liSize*itemLength;var divSize=liSize*v;li.css({width:li.width(),height:li.height()});ul.css(sizeCss,ulSize+"px").css(animCss,-(curr*liSize));div.css(sizeCss,divSize+"px");if(o.btnPrev)$(o.btnPrev).click(function(){resetAuto(); return go(curr-o.scroll);});if(o.btnNext)$(o.btnNext).click(function(){resetAuto(); return go(curr+o.scroll);});if(o.btnGo)$.each(o.btnGo,function(i,val){$(val).click(function(){return go(o.circular?o.visible+i:i);});});if(o.mouseWheel&&div.mousewheel)div.mousewheel(function(e,d){return d>0?go(curr-o.scroll):go(curr+o.scroll);});if(o.auto){autoScroll=setInterval(function(){go(curr+o.scroll);},o.auto+o.speed);function resetAuto(){clearInterval(autoScroll);autoScroll=setInterval(function(){go(curr+o.scroll);},o.auto+o.speed);};div.hover(function(){clearInterval(autoScroll);},function(){autoScroll=setInterval(function(){go(curr+o.scroll);},o.auto+o.speed);});}function vis(){return li.slice(curr).slice(0,v);};function go(to){if(!running){if(o.beforeStart)o.beforeStart.call(this,vis());if(o.circular){if(to<=o.start-v-1){ul.css(animCss,-((itemLength-(v*2))*liSize)+"px");curr=to==o.start-v-1?itemLength-(v*2)-1:itemLength-(v*2)-o.scroll;}else if(to>=itemLength-v+1){ul.css(animCss,-((v)*liSize)+"px");curr=to==itemLength-v+1?v+1:v+o.scroll;}else curr=to;}else{if(to<0||to>itemLength-v)return;else curr=to;}running=true;ul.animate(animCss=="left"?{left:-(curr*liSize)}:{top:-(curr*liSize)},o.speed,o.easing,function(){if(o.afterEnd)o.afterEnd.call(this,vis());running=false;});if(!o.circular){$(o.btnPrev+","+o.btnNext).removeClass("disabled");$((curr-o.scroll<0&&o.btnPrev)||(curr+o.scroll>itemLength-v&&o.btnNext)||[]).addClass("disabled");}}return false;};});};function css(el,prop){return parseInt($.css(el[0],prop))||0;};function width(el){return el[0].offsetWidth+css(el,'marginLeft')+css(el,'marginRight');};function height(el){return el[0].offsetHeight+css(el,'marginTop')+css(el,'marginBottom');};})(jQuery);
Just swap it out with your current jCarouselLite script and use it just the same.
If you are able/authorized to change the plugin code:
Add a variable to save the interval id to the plugins defaults
interval: null
Search for:
if(o.auto)
Take the code which is executed here and make an internal function with it like:
function runAuto() {
setInterval(function() {
go(curr+o.scroll);
}, o.auto+o.speed);
}
Now just save the interval to your defined variable but clear it first:
function runAuto() {
clearInterval(o.interval);
o.interval = setInterval(function() {
go(curr+o.scroll);
}, o.auto+o.speed);
}
Search for the go() function in the plugin and add a runAuto(), so each time the function go is called it resets the interval.
Of course you must also add the runAuto() call to if(o.auto) so the interval starts at first.