QUESTION
How can I prevent a jquery toggle function from running before the previous toggle animation is complete?
I have a simple script to show or hide data depending whether a checkbox is checked.
JQUERY
$('.a').hide();
$('#CB').change(function () {
if ($(this).is(':checked')) {
$('.b').fadeOut(100, function () {
$('.a').fadeIn();
});
} else {
$('.a').fadeOut(100, function () {
$('.b').fadeIn();
});
}
});
PROBLEM
When the event is fired consecutively both elements, in this case .a and .b become visible together. I assume this is because the previous request is not completed prior to firing the function again.
CLICK FOR DEMO
http://jsfiddle.net/keypaul/PbS33/5/
$('.a').hide();
$('#CB').change(function () {
if ($(this).is(":checked")) {
$('.b').stop().fadeOut(100, function () {
$('.a').stop().fadeIn();
});
} else {
$('.a').stop().fadeOut(100, function () {
$('.b').stop().fadeIn();
});
}
});
Using jquery stop()
http://api.jquery.com/stop/
You're right. Animations in jQuery work asynchronously so they could sometimes run at the same time.
To answer your question, I think you already answered it in your question title.
Use a queue.
Set up a flag, name it something like isFading, and when it's true when $("#CB") changes, you queue it instead.
var isFading=false;
var animationQueue = [];
$('#CB').change(function () {
if(isFading){
if ($(this).is(':checked')) {
animationQueue.push(fadeOutFadeIn);
}
else {
animationQueue.push(fadeInFadeOut);
}
}
else{
if ($(this).is(':checked')) {
fadeOutFadeIn();
} else {
fadeInFadeOut();
}
}
);
function fadeOutFadeIn(){
isFading=true;
//insert your fadeout fadein code here
isFading=false;
if(animationQueue.length > 0)
//you're now calling the queued animation to go through
animationQueue.splice(0,1)();
}
function fadeInFadeOut(){
isFading=true;
//insert your fadein fadeout code here
isFading=false;
if(animationQueue.length > 0)
//you're now calling the queued animation to go through
animationQueue.splice(0,1)();
}
Related
I got an element that is slided down by JQuery using .slideDown() method
$('#dropdown_shopping_cart').slideDown(800);
Now i want it to slide up after 6 seconds, but only if there is no hover on the element, if there is an hover, it should not .slideUp().
So far i worked with a timeout that added display:none to the element while i was giving the element´s hover display:block!important; in CSS so it would not get display: none until the hover is over.
JS
setTimeout(function () {
$('#dropdown_shopping_cart').css('display', 'none');
}, 6000);
_______________________________________________________
CSS
#dropdown_shopping_cart:hover {
display: block!important;
}
Now i want to add the .slideUp() to this.
Check this:
var myVar;
myVar = setTimeout(function() {
$('#dropdown_shopping_cart').slideUp(800)
}, 6000);
$("#dropdown_shopping_cart").hover(
function() {
clearTimeout(myVar);
},
function() {
myVar = setTimeout(function() {
$('#dropdown_shopping_cart').slideUp(800)
}, 6000);
}
);
By default shopping cart will slideUp() after 6 seconds, if mouse hover action occured, setTimeOut will be cleared, after mouse leave the shopping cart, setTimeOut will setted automatically
You can clear the timeout on mouseenter and reset it on mouseleave like this:
var hide_div_to;
function hideDiv(){
hide_div_to = setTimeout(function () {
$('#dropdown_shopping_cart').slideUp(800);
}, 6000);
}
$('#dropdown_shopping_cart').slideDown(800,hideDiv());
$('#dropdown_shopping_cart').mouseenter(function(){
clearTimeout(hide_div_to);
});
$('#dropdown_shopping_cart').mouseleave(function(){
hideDiv();
});
Here is a working JSFiddle
UPDATE
If you don't wan't to wait the timeout again when you leave, after the timeout is reached, you can do this:
$('#dropdown_shopping_cart').slideDown(800);
setTimeout(function () {
if(!$('#dropdown_shopping_cart').is(':hover')){
$('#dropdown_shopping_cart').slideUp(800);
}
else{
$('#dropdown_shopping_cart').mouseleave(function(){
$('#dropdown_shopping_cart').slideUp(800);
});
}
}, 3000);
And here is a JSFiddle and here is another one that shows how this can be triggered multiple times.
Id suggest you work with mouseover and a class:
$('#dropdown_shopping_cart').hover(function(){
if(!$('#dropdown_shopping_cart').hasClass('active'))
{
$(this).addClass('active');
}
else
{
$(this).removeClass('active');
}
},
function() {
var myVar = setTimeout(function() {
if(!$('#dropdown_shopping_cart').hasClass('active'))
{
$('#dropdown_shopping_cart').slideUp()
}
}, 6000);
})
And than in your setTimeout Function you add:
demo: http://jsfiddle.net/yo5gnvy3/7/
$('#dropdown_shopping_cart').hide().slideDown(800, function () {
var events = $._data($(this)[0], "events") || {};
if (events.mouseover === undefined) {
$(this).delay(1000).slideUp()
}
});
I inherited this modal/overlay/content close/empty method that works, but abruptly:
method.close = function () {
$modal.hide();
$overlay.hide();
$content.empty();
$(window).unbind('resize.modal');
};
To fade out gradually, I modified the method like below, but elements are left behind and subsequent clicks don't open new modals loaded with content, only the overlay:
method.close = function () {
$modal.fadeOut('slow', function() {
$(this).hide();
});
$overlay.fadeOut('slow', function() {
$(this).hide();
});
$content.fadeOut('slow', function() {
$(this).empty();
});
$(window).unbind('resize.modal');
};
What am I missing?
UPDATE: The solution is a single nested callback, based on garryp's answer, like this:
method.close = function() {
$overlay.fadeOut('slow', function() {
$overlay.hide();
$content.empty();
});
$modal.hide();
$(window).unbind('resize.modal');
};
Hide is asynchronous; the calls you have in your original code do not block while the transition occurs, execution moves immediately to the next. You need to use callbacks, like this:
var me = $(this); //Added to ensure correct this context
$modal.fadeOut('slow', function () {
me.hide(function () {
$overlay.fadeOut('slow', function () {
me.hide(function () {
$content.fadeOut('slow', function () {
me.empty();
});
});
});
});
});
Assuming the rest of your code is correct this should ensure the transitions fire one after the next.
Firstly, you do not need $(this).hide(). JQuery fadeOut automatically set display: none at the end of fading animation (read more: http://api.jquery.com/fadeout/).
That mean, in your case $content element will also have display: none after fadeOut animation. I expect you forgot to add $content.show() in modal open method.
Does anyone know if there's a way to preventDefault(), but on a timer, so default actions are restored after a certain time?
Here's what I have so far:
function setResetInterval(bool){
var el = $('article');
if(bool){
timer = setInterval(function(){
setTimeout(function(){
console.log('default prevented');
e.preventDefault();
}, 500);
},1000);
}else{
clearInterval(timer);
}
}
if(object.touch.touch){
object.header.menu_button.attr('href',null);
object.touch.articles = $('article');
object.content_blocks.on('click','article',{},function(e){
object.touch.articles.removeClass('on');
$(this).addClass('on');
e.stopPropagation();
setResetInterval(true);
setTimeout(
function() { setResetInterval(false); }, 500);
});
}
Problem is, the function is called after the clickthrough and the action is not prevented. The alternative is the prevent the default action on click, which stop scrolling on mobile devices.
Thinking about it more clearly, the real problem is the click tag in question is basically the entire screen width on mobile.
To build on what Cayce said, one way to approach this is to tie the functionality to a class you later remove.
Demo Fiddle:
In the example, the default will be prevented as long as the div has the .red class, the setTimeout will remove the class after 3 seconds.
JS:
$('body').on('click', '.red', function (e) {
e.preventDefault();
console.log('I only show up while default is prevented');
});
$('body').on('click', 'div', function () {
console.log('I will always show up');
});
setTimeout(function () {
$('div').removeClass('red');
},3000);
How can I hide the left control if the carousel is on the first item, and how can I hide the right control when the carousel is on the last item.
My code below hides the control successfully but on page load it is as if the carousel first item is in the middle and the user can either go all the way through via the left or right controls.
http://bootply.com/99354
thanks
Bootply link
$('#myCarousel').on('slid', '', checkitem); // on caroussel move
$('#myCarousel').on('slid.bs.carousel', '', checkitem); // on carousel move
$(document).ready(function(){ // on document ready
checkitem();
});
function checkitem() // check function
{
var $this = $('#myCarousel');
if($('.carousel-inner .item:first').hasClass('active')) {
$this.children('.left.carousel-control').hide();
$this.children('.right.carousel-control').show();
} else if($('.carousel-inner .item:last').hasClass('active')) {
$this.children('.left.carousel-control').show();
$this.children('.right.carousel-control').hide();
} else {
$this.children('.carousel-control').show();
}
}
The below code is an updated version of TheLittlePig's code for Bootstrap 3 that works both for multiple carousels on the same page and for indicator actions. The explained code is here
checkitem = function() {
var $this;
$this = $("#slideshow");
if ($("#slideshow .carousel-inner .item:first").hasClass("active")) {
$this.children(".left").hide();
$this.children(".right").show();
} else if ($("#slideshow .carousel-inner .item:last").hasClass("active")) {
$this.children(".right").hide();
$this.children(".left").show();
} else {
$this.children(".carousel-control").show();
}
};
checkitem();
$("#slideshow").on("slid.bs.carousel", "", checkitem);
Augmenting #TheLittlePig, it needs to be slightly different if you're using Bootstrap 3 because the event to attach the callback to is different: slid.bs.carousel. Also, if you have multiple carousels on one page you'll need to pass a unique css id for the carousel into the event handler. Here is a modified version that I use on my Rails site:
<script>
//<![CDATA]
id = '#carousel-<%=id%>';
$(id).on('slid.bs.carousel', { id: id }, bs_carousel_slid);
$(document).ready(function(){ $(id).trigger('slid.bs.carousel'); });
//]]>
</script>
That is repeated for each carousel. The <%=id%> is a ruby expression that is replaced by a unique id for the given carousel. Tweak that bit for your needs according to the language of your choice.
The difference is that the carousel's id is passed into the event handler function as event data so that the event handler can operate on the correct carousel. I also changed the ready event so that it triggers the slid.bs.carousel event (instead of calling the function directly) so it passes the correct event data to the event handler for each carousel.
The event handler is a function called bs_carousel_slid that I define elsewhere (those on Rails - it's in a file in app/assets/javascripts). The function is shown below:
function bs_carousel_slid(event)
{
var id = event.data.id;
var $this = $(id);
if($(id + ' .carousel-inner .item:first').hasClass('active')) {
$this.children('.left.carousel-control').hide();
} else if($(id + ' .carousel-inner .item:last').hasClass('active')) {
$this.children('.right.carousel-control').hide();
} else {
$this.children('.carousel-control').show();
}
}
IF YOU'RE USING BOOTSTRAP 3:
The event is 'slid.bs.carousel' not 'slid'
$('.carousel').carousel({
interval: false,
})
$(document).ready(function () { // on document ready
checkitem();
});
$('#myCarousel').on('slid.bs.carousel', checkitem);
function checkitem() // check function
{
var $this = $('#myCarousel');
if ($('.carousel-inner .item:first').hasClass('active')) {
$this.children('.left.carousel-control').hide();
} else if ($('.carousel-inner .item:last').hasClass('active')) {
$this.children('.right.carousel-control').hide();
} else {
$this.children('.carousel-control').show();
}
}
This function should fadeIn the id="Box" when class="display" is clicked if the Box is not animated and has a display value of none Or fadeOut if the #Box had a display value of is not none. What is wrong?
$(document).ready(function() {
$('.display').click(function() {
var currentDisplayValue = $('#Box').css('display');
if (':animated') {
stop()
};
else if (currentDisplayValue == 'none') {
$('#Box').fadeIn("slow");
};
else {
$('#Box').fadeOut("slow");
};
});
Thanks
Try:
$(function() {
$(".display").click(function() {
var box = $("#Box");
if (box.is(":animated")) {
box.stop();
} else if (box.is(":hidden") {
box.fadeIn("slow");
} else {
box.fadeOut("slow");
}
});
});
You've got some syntax errors (eg semi-colons after the curly braces) and stop() needs to be applied to a jquery set. Lastly, don't check the current display CSS value like you're doing. Use the :hidden selector instead.