user1556158
user1556158

Reputation: 23

JQuery callback...?

thanks for any help.. here is my problem: The code below, when clicking on the Read More... link is supposed to show the div under the link, but only after all other possible divs are hidden... I need to use it in the callback as is, but when used as such, the first link displays correctly, and the last three show, then hide, then show... help!

Javascript:

var more_text="Read More...";
var less_text="Read Less...";

jQuery(document).ready(function() {
    $j(".dropdown").click( function () {
        if ($j(this).html() == more_text){
            var that = $j(this);
            $j(".extra").slideUp( function () {
                $j(".dropdown").html(more_text);
                that.html(less_text);
                that.next(".extra").slideDown();
            });
        }
    });
});

HTML:

<div class="dropdown">Read More...</div>
<div class="extra" style="display: none;">Here is more text!!</div>

<div class="dropdown">Read More...</div>
<div class="extra" style="display: none;">Here is more text!!</div>

<div class="dropdown">Read More...</div>
<div class="extra" style="display: none;">Here is more text!!</div>

<div class="dropdown">Read More...</div>
<div class="extra" style="display: none;">Here is more text!!</div>

Upvotes: 2

Views: 130

Answers (2)

jeff
jeff

Reputation: 8338

You must filter the elements to slide up. You should use this:

jQuery(document).ready(function() {
    $j = jQuery;
    $j(".dropdown").click( function () {
        if ($j(this).html() == more_text){
            var that = $j(this);
            if ($j(".extra").filter(":visible").length > 0) {
                $j(".extra").filter(":visible").slideUp( function () {
                    $j(".dropdown").html(more_text);
                    that.html(less_text);
                    that.next(".extra").slideDown();
                });
            }
            else {
                $j(".dropdown").html(more_text);
                that.html(less_text);
                that.next(".extra").slideDown();
            }
        }
    });
});

This also has a conditional which checks whether or not the any .extra elements are visible, and doesn't slide any elements up if none are visible.

http://jsfiddle.net/vExYL/

Upvotes: 0

MrOBrian
MrOBrian

Reputation: 2189

The problem is that when you call $j(".extra").slideUp(... some of the elements with class extra are already hidden, so those cause the callback to fire immediately, then when the one that needs to close is done closing you get the callback fired again. Change that line to:

$j(".extra").slideUp().promise().done( function () {

and I think it will work the way you are expecting it to.

Upvotes: 1

Related Questions