SunnyShah
SunnyShah

Reputation: 30467

Why consecutive show and hide behaves buggy in this code?

Demo: http://jsfiddle.net/sunnycpp/fMXyP/5/

Consecutive show,hide calls produces a bug, Animation stops and does not resume sometimes. Is this jQuery bug or bug in my code?

Here is the code copy-pasted from jsfiddle.

myButtonManual.on("click", function() {
  isVisible = !isVisible;      
  myHero.stop(true,false);      
  if(isVisible) {        
    myHero.show('slow');
    myButtonManual.text("Manual Hide");
  } else {        
    myHero.hide('slow');
    myButtonManual.text("Manual Show");
  }   

enter image description here

Upvotes: 2

Views: 158

Answers (1)

Fabrício Matté
Fabrício Matté

Reputation: 70139

That isn't a bug.

Taking a look at this line:

myHero.stop(true,false);

When you stop a .hide() at the middle of it without jumping to the end of animation, an element that is visible will stay visible.

Your logic isVisible = !isVisible will be broken then as .stop()ing a hide() leaves the element still visible, meaning that the next call to the handler will execute .show() on a visible element that will have absolutely no effect.

Workarounds include:

  • Remove the .stop(), this will queue the show() and execute it after the hide() concludes;

  • Use .stop(true) - equivalent to .stop(true, true) -, this will be rather bluntly as it will force the animation to conclude as it suddenly starts the next;

Edit: The closest way to reproduce a .toggle()-like behavior using the .show() and .hide() methods is to simply add a .css('display', 'none') before calling .show(), this will ensure that .show() has the desired effect:

isVisible = !isVisible;
myHero.stop(true, false);
if (isVisible) {
  myHero.css('display', 'none').show('slow');
} else {
  myHero.hide('slow');
}

Fiddle

If the element is already hidden, the .css will have no effect; if the element is partially shown, it will hide it ensuring that .show() executes instead of being ignored due to the element being considered visible.

This has the same effect as the .stop(true, false).toggle(), but works using the 2 different .show()/.hide() methods as requested.

Upvotes: 2

Related Questions