Search code examples
javascriptjquerycsslive

Why this jQuery code works only for one Iteration?


Basically I have a drop icon, which should expand and collpase an area beneath it. It changes the background position and points downwards and shows some content.On click again it collapses the content and changes the background position. below is what i have written but it doesn't work properly.

$(function() {
    $(".aclass").live('click' , function() {
        $(this).css("background-position","-156px -42px").addClass("new");

        $(".blockedDiv").hide();
        $(".mystery").css("max-height","189px");
    });

    $(".new").live('click', function() {
        $(this).css("background-position","0px 0px");
        $(".blockedDiv").show();
        $(".mystery").css("max-height","1007px");
    });
});

My two questions: 1: Why is this working only for one Iteration 2: Is there a better way to achieve this.


Solution

  • You're not removing the new class you added. Because of that, when you click on it again, the second event handler fires as well, reversing what the first event handler did.

    As a side note-slash-tip, what you want is to specify explicit CSS rules, which you can toggle with jQuery, so that you don't have to muck through (relatively) complicated logic.

    .mystery { max-height:10007px; }
    .mystery.flagged { max-height:189px; }
    
    .aclass { background-position:0 0; }
    .aclass.flagged { background-position:-156px -42px; }
    

    then in your jQuery:

    $('.aclass').live('click', function () {
        $('.mystery').toggleClass('flagged');
        $(this).toggleClass('flagged');
        $('.blockedDiv').toggle();
    });