0

I'm trying to animate using jQuery but on IE7/8/9 it's not working before I show the element.

function callback() {
    $('#content').animate([...]);
    [...]
}

$('#content').hide();
[...]
$('#content').show();
callback();

It only works to me when a do setTimeout(function() { callback(); }, 300);, maybe I need to wait the IE to recognize the element that has been shown, before execute the callback. What is the problem here?

1
  • Can you make a JSFiddle that demonstrates this? Commented Oct 11, 2011 at 15:49

2 Answers 2

1

You need to wait for the element to exist within the page before you can select it with jQuery.

wrap your script with:

jQuery(function($){
  //your code here
});

It's a shortcut for the document.ready event listener.

Sign up to request clarification or add additional context in comments.

Comments

0

Since JS is single-threaded just because you call show() doesn't mean it's actually showing; you need to return control to the parent to allow it to draw and update the DOM before that happens. setTimeout allows your JS to yield to the parent, making it's updates before you continue with execution. setTimeout with 0 will most likely also work.

3 Comments

This is somewhat misleading. While it is true that doing something in a hard loop and not yielding will usually prevent the page from redrawing, that does not mean that you need to yield for the DOM to 'update'. Any DOM manipulation function will not return until the browser has completely updated its internal data structures; the next script statement will see the DOM as updated internally, even if those changes haven't yet been drawn to the screen. Thus, calling hide and show in succession without yielding won't generate a visible result, but it will be logically consistent.
He's talking about the animation not working without the setTimeout and I believe this is why. In the given context I don't think my answer is misleading - I'm not mentioning that because it didn't seem relevant as the hide/show isn't where his problem is.
If we first .hide() an element, call .show(), and then call .animate(...), it simply doesn't matter whether the script yields between calling show and animate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.