Add and Remove a css image class on toggle using jquery

I am trying to toggle the menu when the user clicks the artcile's h3 element, much like an accordion but a little different.

What I am unable to achieve is that the image does not display nor does it change when the element's slideToggle function is called. However, the slideToggle is working fine, it is just the image I need assistance with.

HTML:-

<div class="pages">
    <article class="collapsible expanded collapsed">
        <h3><?php echo $lang->xlate('presentation-b');?></h3>
    </article>

    <div class="content">
        <ul>
            <li>
                <?php echo $lang->xlate('presentation-c');?> </li>



            <li>
                <?php echo $lang->xlate('presentation-d');?> </li>



            <li>
                <?php echo $lang->xlate('presentation-e');?> </li>
        </ul>
    </div>
</div>

CSS

#paragraph .pages .collapsible {
  padding: 2px;
  cursor: pointer;
  font-weight: bold;
}
#paragraph .pages .collapsible .expanded  {background: url('../img/list.png') no-repeat left top;}
#paragraph .pages .collapsible .collapsed {background: url('../img/pagination.gif') no-repeat left top;}

jQuery:-

        $('.collapsible').click(function(){
        $coll = $(this);
        $content = $coll.next();
        $content.slideToggle(500, function () {
         //execute this after slideToggle is done
         //change text of header based on visibility of content div
                    if($(this).hasClass('expanded'))
                    {
                        $(this).toggleClass('collapsed expanded');
                    }
                    else
                    {
                        $(this).toggleClass('expanded collapsed');
                    } 
        });
    });

Answers 1

  • Remove . before class name on adding and removing classes.

    $(this).addClass('expanded').removeClass('collapsed');
    

    Also you can use toggleClass() to toggle between classes.

    $(this).toggleClass('collapsed expanded');
    

    like :

    $('.collapsible').click(function() {
        $coll = $(this);
        $content = $coll.next();
        $content.slideToggle(500, function() {
            //execute this after slideToggle is done
            //change text of header based on visibility of content div
            $(this).toggleClass('collapsed expanded');
        });
    });
    

Related Articles