jquery toggle with loading span
I have a bunch of items with class dof that are shown and hidden with jquery toggle
I am currently using this code to show and hide it:
$('.dof').toggle();
which works great, but takes about 30 seconds to do the toggle.
I added this to show a loading image:
<a href="#" onclick="$('#loading').show();$('.dof').toggle();$('#loading').hide();">
Toggle DOF
</a>
<span id="loading" style="display:none;">
<img src="/assets/a开发者_如何学运维jax-loader.gif" />
</span>
This isn't showing the loading span. I can confirm that the loading image shows if I take out the display:none;
What am I doing wrong?
EDIT
I tried this from the suggestion of Josiah Ruddell
(forgive me I use coffescript, so I converted it all to coffescript then back for display here)
$('#toggledof').click(function() {
var $dofs, doflen, toggleComplete;
$("#loading").show();
toggleComplete = function() {
return $("#loading").hide();
};
$dofs = $(".dof");
doflen = $dofs.length;
return $dofs.each(function(i) {
$(this).toggle();
if (i === doflen - 1) {
return toggleComplete();
}
});
});
Then I changed the a tag to this:
<a href="#" id="toggledof">
Toggle DOF
</a>
The toggle function is not synchronous due to the animation duration option. You can specify a callback for the toggle.
$('.dof').toggle(function(){
$('#loading').hide();
});
However, if there are multiple .dof
elements on the page, the callback will happen for each one.
Update
You will want to keep track of where you are in the toggle progress. After all the items have been toggled, show the loader. As an aside, you may consider optimizing the selector to increase the speed of this operation. At the least you can add a node name before the .
e.g. div.dof
.
var toggleComplete = function(){
$('#loading').hide();
},
$dofs = $('.dof'),
doflen = $dofs.length;
$dofs.each(function(i){
$(this).toggle();
if(i == doflen -1) toggleComplete();
});
To determine the speed of toggle, you can use the overloaded function:
$(selector).toggle(speed);
where the speed parameter can take the following values: "slow", "fast", "normal", or time in milliseconds.
This will make your animation as per the speed you desire.
I fixed the issue with this code, I guess .toggle()
sucks when you are dealing with 1900 elements....
the html
<div id="testdof" style="display:none"></div> <!-- because the dof elements are hidden at page load -->
then the jquery
$('#toggledof').click(function() {
if ($('#testdof').css('display') === 'none') {
$(".dof").show();
$("#testdof").show();
} else {
$(".dof").hide();
$("#testdof").hide();
}
});
This runs fast enough to not care about a loading element.
精彩评论