I'm trying to create a simple JQuery slider, and I'm having trouble with the .on('click') function, if I click the next or prev button too fast it exceeds the value I expect.
var currentSlide = 1;
var $slider = $(".slides");
var slideCount = $slider.children().length;
var slideSpeed = 500;
var slideMarginLeft = -900;
var slideMarginRight = 0;
$(".prev").on('click',function(){
if(currentSlide > 1){
$slider.animate({marginLeft : slideMarginLeft + 1800} , slideSpeed, function(){
slideMarginLeft +=900;
currentSlide--;
console.log(currentSlide);
});
}
});
$(".next").on('click',function(){
if(currentSlide < 5){
$slider.animate({marginLeft : slideMarginLeft} , slideSpeed, function(){
slideMarginLeft -=900;
currentSlide++;
console.log(currentSlide);
});
}
});
var currentSlide = 1;
var $slider = $(".slides");
var slideCount = $slider.children().length;
var slideSpeed = 500;
var slideMarginLeft = -900;
var slideMarginRight = 0;
function previousClickCallback(animationCallback){
return function(){
if(currentSlide > 1){
$slider.animate({marginLeft : slideMarginLeft + 1800} , slideSpeed, () => {
slideMarginLeft +=900;
currentSlide--;
console.log(currentSlide);
$(".prev").once('click',previousClickCallback);
});
} else {
$(".prev").one('click',previousClickCallback);
}
}
}
function nextClickCallback(){
return function(){
if(currentSlide < 5){
$slider.animate({marginLeft : slideMarginLeft} , slideSpeed, () => {
slideMarginLeft -=900;
currentSlide++;
console.log(currentSlide);
$(".next").once('click',nextClickCallback);
});
} else {
$(".next").one('click',nextClickCallback);
}
}
}
$(".prev").one('click',previousClickCallback);
$(".next").one('click',nextClickCallback)
This should do, click event gets registered only once and once the callback for animation is done then only click event is registered again and that will stop from continuously firing events
Make sure the .next class is assigned to only one button.
Related
I'm trying to make a carousel that runs automatically, but if a user interacts with the controls I want the carousel to reset its timer.
What ive built works to an extent, but if you interact with the control-dot the timer isnt reset so it throws some funny results...
Here's my JS
/* Js for carousel */
$('.steps__step-1').addClass('active');
$(function() {
var lis = $('.step'),
currentHighlight = 0;
N = 5; // Duration in seconds
setInterval(function() {
currentHighlight = (currentHighlight + 1) % lis.length;
lis.removeClass('active').eq(currentHighlight).addClass('active');
}, N * 1000);
});
$('.control-dot').on('click', function(e) {
e.preventDefault();
$('.active').removeClass('active');
var itemNo = $(this).index() - 1;
$('.step').eq(itemNo).addClass('active');
});
http://jsfiddle.net/tnzLha3o/1/
You should store interval id in a variable (let intervalId = setInterval(...)) and then use it to restart it.
Here is your updated fiddle: http://jsfiddle.net/gudzdanil/uzoydp6a/2/
So that your code will look like:
var duration = 5;
var lis = $('.step'),
currentHighlight = 0;
var intervalId = null;
$(function() {
$('.steps__step-1').addClass('active');
runCarousel();
});
$('.control-dot').on('click', function(e) {
e.preventDefault();
$('.active').removeClass('active');
var itemNo = $(this).index() - 1;
$('.step').eq(itemNo).addClass('active');
rerunCarousel();
});
function rerunCarousel() {
if(intervalId) clearInterval(intervalId);
intervalId = null;
runCarousel();
}
function runCarousel() {
intervalId = setInterval(function() {
currentHighlight = (currentHighlight + 1) % lis.length;
lis.removeClass('active').eq(currentHighlight).addClass('active');
}, N * 1000)
}
Add a variable to stop it.
var stop = false
$('.steps__step-1').addClass('active');
$(function() {
var lis = $('.step'),
currentHighlight = 0;
N = 5; // Duration in seconds
setInterval(function() {
if (!stop) {
currentHighlight = (currentHighlight + 1) % lis.length;
lis.removeClass('active').eq(currentHighlight).addClass('active');
}
}, N * 1000);
});
$('.control-dot').on('click', function(e){
e.preventDefault();
$('.active').removeClass('active');
var itemNo = $(this).index() - 1;
$('.step').eq(itemNo).addClass('active');
stop = !stop
});
http://jsfiddle.net/quvgxz63/
I want to try image slide show on mouseover and stop on mouse out
Following is my code: but with mouse over mouse out is also calling..its working fine on chrome...
default_image = '';
timer = 0;
jQuery('.sales-product-images').on('mouseover',function(){
var counter = 0;
var selector = jQuery(this);
var pd_id = jQuery(this).attr('id');
var imageArray = jQuery.parseJSON(images);
var product_images= imageArray[pd_id];
default_image = jQuery(this).attr('data-image');
console.log('default-image= ' + default_image);
timer = setInterval(function(){selector.fadeOut("fast", function () {
console.log(counter);
if (counter === product_images.length) {
console.log('==');
counter = 0;
}
console.log('localhost/product/' + product_images[counter]);
selector.attr('src', 'localhost/product/' + product_images[counter]);
selector.fadeIn(2500);
counter = counter+ 1;
});
}, 2000)});
jQuery('.sales-product-images').on('mouseleave', function() {
console.log('now end');
// var counter = 0;
clearInterval(timer);
)};
problem is: "now end" is also printed on mouseover in firefox.Which should not be.
Try this :
jQuery('.sales-product-images').on('mouseout', function() {
console.log('now end');
// var counter = 0;
clearInterval(timer);
)};
The problem is likely caused by using mouseover with mouseleave, when it's paired event should be mouseout. The pairings can be seen below.
mouseover / mouseout
$( ".sales-product-images" )
.mouseover(function() {
console.log("mouse over");
})
.mouseout(function() {
console.log("mouse out");
});
mouseenter / mouseleave
$( ".sales-product-images" )
.mouseenter(function() {
console.log("mouse enter");
})
.mouseleave(function() {
console.log("mouse leave");
});
The above methods are shortcuts for the .on("", function(){}) method.
You could rewrite your javascript as follows:
default_image = '';
timer = 0;
jQuery('.sales-product-images').mouseover(function(){
var counter = 0;
var selector = jQuery(this);
var pd_id = jQuery(this).attr('id');
var imageArray = jQuery.parseJSON(images);
var product_images= imageArray[pd_id];
default_image = jQuery(this).attr('data-image');
console.log('default-image= ' + default_image);
timer = setInterval(function(){
selector.fadeOut("fast", function () {
console.log(counter);
if (counter === product_images.length) {
console.log('==');
counter = 0;
}
console.log('localhost/product/' + product_images[counter]);
selector.attr('src', 'localhost/product/' + product_images[counter]);
selector.fadeIn(2500);
counter = counter+ 1;
});
}, 2000);
}).mouseout(function() {
console.log('now end');
// var counter = 0;
clearInterval(timer);
});
I cant get my head around this, been trying many many different ways but no luck.. Basically, I'm trying to pause the animation on mouseOver and resume it on mouseOut. I was able to make it pause by simply using clearTimeout() but I have no idea on how to resume it back on. Please kindly advise me with a correct solution and syntax.
Thank you in advance!
(function ($) {
$.fn.simpleSpy = function (interval, limit) {
limit = limit || 3;
interval = interval || 3000;
items = [];
return this.each(function () {
$list = $(this),
currentItem = 0,
total = 0; // initialise later on
var i = 0;
smplet = $list.clone();
smplet.css("display","none");
$("body").append(smplet);
total = smplet.find('> li').length;
$list.find('> li').filter(':gt(' + (0) + ')').remove();
$list.css("display","");
height = $list.find('> li:first').height();
$list.wrap('<div class="spyWrapper" />').parent().css({ height : 55, position:"relative", overflow:"hidden" });
$('.close').click(function(){
clearTimeout(timec);
if(currentItem == 0 && smplet.length != 1)
delitem=total;
else
delitem=currentItem - 1;
smplet.find('> li').eq(delitem).remove();
currentItem--;
var temp=smplet.find('> li').eq(currentItem).clone();
var $insert = temp.css({
"margin-top":-height-height/3,
opacity : 0
}).prependTo($list);
// fade the LAST item out
$list.find('> li:last').animate({ opacity : .5 ,"margin-top":height/3}, 500, function () {
$(this).remove();
});
$insert.animate({"margin-top":0,opacity : 1 }, 500).animate({opacity : 1},1000);
currentItem++;
total=smplet.find('> li').length;
if (currentItem >= total) {
currentItem = 0;
}
if (total == 1){
simpleSpy.stop();
}
else if(total == 0){
$("#topbar").hide();
}
timec=setTimeout(spy, interval);
});
currentItem++;
function spy() {
var temp=smplet.find('> li').eq(currentItem).clone();
var $insert = temp.css({
"margin-top":-height-height/3,
opacity : 0,
display : 'none'
}).prependTo($list);
$list.find('> li:last').animate({ opacity : .5 ,"margin-top":height/3}, 500, function () {
$(this).remove();
});
$insert.animate({"margin-top":0,opacity : 1 }, 500).animate({opacity : 1},1000);
$insert.css("display","");
currentItem++;
if (currentItem >= total) {
currentItem = 0;
}
timec=setTimeout(spy, interval);
}
timec=setTimeout(spy, interval);
});
};
$('ul.alerts')
.mouseover(function(){
clearTimeout(timec);
})
.mouseout(function(){
timec=setTimeout(spy, interval);
});
})(jQuery);
Call
$(document).ready(function() {
$('ul.alerts').simpleSpy();
});
jsfiddle with html and css
http://jsfiddle.net/1781367/3eK4K/3/
I changed the timeout, which you were setting over and over, to an interval, which you only need to set once. Then I added a "paused" property that is set to true on mouseover and back to false on mouseout.
var paused = false;
$list.mouseover(function() { paused = true; });
$list.mouseout(function() { paused = false; });
Then we just check that property before the rotation animation occurs:
if (paused) {
return;
}
http://jsfiddle.net/3eK4K/6/
I am having trouble creating a slider that pauses on hover, because I execute the animation function again on mouse off, if I flick the mouse over it rapidly (thereby calling the function multiple times) it starts to play up, I would like it so that the function is only called if the other function is complete, otherwise it does not call at all (to avoid queue build up and messy animations)
What's the easiest/best way to do this?
$(document).ready(function() {
//get variables
var slide_width = $('.slider_container').width();
var number_of_slides = $('.slider_container .slide').length;
var slider_width = slide_width*number_of_slides;
//set element dimensions
$('.slide').width(slide_width);
$('.slider').width(slider_width);
var n = 1;
$('.slider_container').hover(function() {
//Mouse on
n = 0;
$('.slider').stop(true, false);
}, function() {
//Mouse off
n = 1;
if (fnct == 0) sliderLoop();
});
//Called in Slide Loop
function animateSlider() {
$('.slider').delay(3000).animate({ marginLeft: -(slide_width * i) }, function() {
i++;
sliderLoop();
});
}
var i = 0;
var fnct = 0
//Called in Doc Load
function sliderLoop() {
fnct = 1
if(n == 1) {
if (i < number_of_slides) {
animateSlider();
}
else
{
i = 0;
sliderLoop();
}
}
fnct = 0
}
sliderLoop();
});
The slider works fine normally, but if I quickly move my mouse on and off it, then the slider starts jolting back and forth rapidly...been trying to come up with a solution for this for hours now..
Here's what fixed it, works a charm!
$(document).ready(function() {
//get variables
var slide_width = $('.slider_container').width();
var number_of_slides = $('.slider_container .slide').length;
var slider_width = slide_width*number_of_slides;
//set element dimensions
$('.slide').width(slide_width);
$('.slider').width(slider_width);
var n = 1;
var t = 0;
$('.slider_container').hover(function() {
clearInterval(t);
}, function() {
t = setInterval(sliderLoop,3000);
});
var marginSize = i = 1;
var fnctcmp = 0;
//Called in Doc Load
function sliderLoop() {
if (i < number_of_slides) {
marginSize = -(slide_width * i++);
}
else
{
marginSize = i = 1;
}
$('.slider').animate({ marginLeft: marginSize });
}
t = setInterval(sliderLoop,3000);
});
all. I am building a full screen jQuery gallery for a project I am working on, and am running in to a small hiccup.
to see a demo of what is happening, please visit http://www.idealbrandon.com/gallery.html.
Basically, I am loading the bg-image for each slide using a custom attribute, data-background. This works fine the first time through, however whenever a slide is loaded for a second time, it does not load. The HTML for a slide is:
<div class="slide" data-background="/img/gallery/2.jpg">
<div class="location">Magical Aqua Ducks</div>
<div class="verse"></div>
</div>
the Javascript in question is
for(var i = 0; i < totalSlides; i++){
$pagerList
.append('<li class="page" data-target="'+i+'"></li>');
if ($slides.eq(i).attr("data-background") != null){
$slides.eq(i).css("background-image", "url("+$slides.eq(i).attr("data-background")+")");
};
};
and the entire javascript file is
(function($){
function prefix(el){
var prefixes = ["Webkit", "Moz", "O", "ms"];
for (var i = 0; i < prefixes.length; i++){
if (prefixes[i] + "Transition" in el.style){
return '-'+prefixes[i].toLowerCase()+'-';
};
};
return "transition" in el.style ? "" : false;
};
var methods = {
init: function(settings){
return this.each(function(){
var config = {
slideDur: 7000,
fadeDur: 800
};
if(settings){
$.extend(config, settings);
};
this.config = config;
var $container = $(this),
slideSelector = '.slide',
fading = false,
slideTimer,
activeSlide,
newSlide,
$slides = $container.find(slideSelector),
totalSlides = $slides.length,
$pagerList = $container.find('.pager_list');
prefix = prefix($container[0]);
function animateSlides(activeNdx, newNdx){
function cleanUp(){
$slides.eq(activeNdx).removeAttr('style');
activeSlide = newNdx;
fading = false;
waitForNext();
};
if(fading || activeNdx == newNdx){
return false;
};
fading = true;
$pagers.removeClass('active').eq(newSlide).addClass('active');
$slides.eq(activeNdx).css('z-index', 3);
$slides.eq(newNdx).css({
'z-index': 2,
'opacity': 1
});
if(!prefix){
$slides.eq(activeNdx).animate({'opacity': 0}, config.fadeDur,
function(){
cleanUp();
});
} else {
var styles = {};
styles[prefix+'transition'] = 'opacity '+config.fadeDur+'ms';
styles['opacity'] = 0;
$slides.eq(activeNdx).css(styles);
//$slides.eq(activeNdx).css("background-image", "url("+$slides.eq(activeNdx).attr("data-background")+")");
var fadeTimer = setTimeout(function(){
cleanUp();
},config.fadeDur);
};
};
function changeSlides(target){
if(target == 'next'){
newSlide = (activeSlide * 1) + 1;
if(newSlide > totalSlides - 1){
newSlide = 0;
}
} else if(target == 'prev'){
newSlide = activeSlide - 1;
if(newSlide < 0){
newSlide = totalSlides - 1;
};
} else {
newSlide = target;
};
animateSlides(activeSlide, newSlide);
};
function waitForNext(){
slideTimer = setTimeout(function(){
changeSlides('next');
},config.slideDur);
};
for(var i = 0; i < totalSlides; i++){
$pagerList
.append('<li class="page" data-target="'+i+'"></li>');
if ($slides.eq(i).attr("data-background") != null){
$slides.eq(i).css("background-image", "url("+$slides.eq(i).attr("data-background")+")");
//alert($slides.eq(i).attr("data-background"));
};
};
$container.find('.page').bind('click',function(){
var target = $(this).attr('data-target');
clearTimeout(slideTimer);
changeSlides(target);
});
var $pagers = $pagerList.find('.page');
$slides.eq(0).css('opacity', 1);
$pagers.eq(0).addClass('active');
activeSlide = 0;
waitForNext();
});
}
};
$.fn.easyFader = function(settings){
return methods.init.apply(this, arguments);
};
})(jQuery);
Thanks in advance
Having had a look at your gallery.js file you have the following function that is called on your fade transition: cleanUp()
In this function you remove the style attribute from your $slides:
$slides.eq(activeNdx).removeAttr('style');
Which is removing the background-image style too. This is then never set again.
After the above line where you remove the styles you may want to then include:
$slides.eq(activeNdx).css("background-image", "url("+$slides.eq(activeNdx).data("background")+")");