Jquery hide / show does not work with animation

advertisements

I am trying to hide a result div. Modify it. Then Show it with animation.

I have the following:

$("#SearchButton").button().click(function() {
                $("#resultContainer").hide();
                $("#resultContainer").empty();
                searchResults();
                $("#resultContainer").show("slow");
});

Where searchResults() makes an ajax call to load some stuff into the div #resultContainer

However, even if I comment out the line //searchResults(); I still end up with a blank div when I click the button.

However if I switch $("#resultContainer").show("slow"); to $("#resultContainer").show(); It works fine. But I want the animation. .show("slow") works fine elsewhere...

Update: I now have:

$("#SearchButton").button().click(function() {
                $("#resultContainer").hide(0);
                searchResults();
            });

And searchResults does the ajax call with the following callback:

//appending something to the div here
$("#resultContainer").show(600);
alert("test");

I get the alert but the div never shows back up...


You code can be improved, try this:

$(function() {
    var $resultContainer = $("#resultContainer");
    $("#SearchButton").click(function() {
        $resultContainer.hide();
        //$resultContainer.empty(); // BTW, no need to empty since the ajax will replace its content anyway!
        searchResults();
    });

    function searchResults() {
        $.ajax({
            url: "yourRequest.php",
            success: function(resp) {
                $resultContainer.html(resp);
                $resultContainer.show("slow");
            }
        });
    }
});

  1. You don't need the empty the container since it's content will be replaced in the ajax call anyway and it's already hidden anyway!
  2. Remove your show method to the ajax success callback
  3. store the container in a var $resultContainer and use it for faster access.

And here's a live example.