jQuery fadeToggle Displays Incoming Element Before Outgoing is Hidden
I have a some basic jQuery to toggle the text in a button as well as toggle between two divs. Problem 开发者_运维知识库is, the incoming element appears before the outgoing one is gone, and then the incoming slides up at the end of the animation. It looks kind of herky-jerky. Here's my fiddle.
For posterity, here's my html:
<button id='globalTicketsBtn'>Show Table</button>
<div class="toggle" id="globalTicketsByHour">This is where the chart will be</div>
<div class="toggle" style="display: none">This is where the table will be</div>
And my jQuery:
$("#globalTicketsBtn").click(function() {
$(".toggle").fadeToggle(function() {
$('#globalTicketsBtn').text($(this).is(':visible')? 'Show Chart' : 'Show Table');
});
});
Should I be firing the animations serially serially rather than in a single fadeToggle?
Thanks for any advice!
easy :) use callbacks. jquery gives that to you for free. Basically you pass a function as the last parameter and that is run after the animation. I had to do a quick DOM manipulation, but other than that it's pretty straight forward.
$("#globalTicketsBtn").click(function() {
$(".toggle:first").animate({ opacity: "toggle" }, 1000 ,function(){
$(".toggle:last").animate({ opacity: "toggle" }, 1000);
$(".toggle:last").insertBefore(".toggle:first");
});
$('#globalTicketsBtn').text($('#globalTicketsByHour').is(':visible')? 'Show Chart' : 'Show Table');
});
http://jsfiddle.net/qjjDc/2/
Rather than get involved with callbacks, why not use a visibility filter to put a delay on the hidden element(s):
Let all of your visible elements finish animating before toggling the hidden ones:
$("#globalTicketsBtn").click(function() {
$(".toggle:visible").fadeToggle(1000)
$(".toggle:hidden").delay(1000).fadeToggle(1000)
});
I tried it in your fiddle and there is no herky-jerky-ness. Just make sure if you change the interval, the delay interval is >=
the interval of the visible toggle.
The problem is that the javascript doesn't wait for the animation to finish before continuing. The easiest (although not very pretty) solution i can thing of is to first slide the first one, then sleep for a second and then slide the other one.
Try this
$("#globalTicketsBtn").click(function() {
//alert('jesus!');
$(".toggle").fadeToggle(function() {
$('#globalTicketsBtn').hide().text($(this).is(':visible')? 'Show Chart' : 'Show Table').fadeIn(10);
});
});
精彩评论