Search code examples
jqueryjquery-selectorstoggleclass

Jquery - Toggle class if only first instance


Here's my fiddle: http://jsfiddle.net/SBAE8/

Here's my problem. I have a series of 3 items, the top most item is preceded by a headline whose visibility has been toggled by the script. If the user deletes item 1, then the headline for item 2 appears and then if item 2 is deleted then the headline for item 3 appears. The issue is - if they delete item 2 first, the headline for item 3 appears and I only want one headline for each set at anytime, and it should always be the first item's headline no matter which item is at the top. I've tried several methods of checking if the deleted item has a higher sibling but I cannot seem to figure this one out.

The jQuery (also see fiddle linked above):

    $(".doDelete").click(function () {
        var $el = $(this).closest("div.payload-container");
        var id = $(this).attr("id");
        // Alert callback (removed from this example)
            // Success
                $el.next("div.payload-container").find(".headline").toggleClass("hide");
                $el.slideUp(200, function () {
                    $el.remove();
                });
    });

Any help would be appreciated. Thanks!


Solution

  • You don't check whether there are any other headlines visible (or will be visible) first.

    I check in the callback:

    if (!$(".headline:visible").length) {
        $el.next("div.payload-container").find(".headline").toggleClass("hide");
    }
    $el.remove();
    

    This doesn't show the next headline until after the slideUp has completed. If that's no good, then you have to check whether it's $el's .headline that is visible.

    http://jsfiddle.net/SBAE8/1/

    Update: Final working version http://jsfiddle.net/uE5Ap/2/