Search code examples
javascriptjquerypackery

Can't seem to find and toggle already expanded classes


I have found the following code in combination with Packery to expand and shrink blocks when being clicked on. I want to add to the code that when clicking a block, all other blocks that currently are expanded shrink to their original size, so that only 1 block is expanded at the time.

This is the code

$( function() {
  var $container = $('.packery').packery();

  $container.on( 'click', '.item', function( event ) {
    var $item = $( event.currentTarget );
    var isExpanded = $item.hasClass('is-expanded');
    $item.toggleClass('is-expanded');
    if ( isExpanded ) {
      // if shrinking, just layout
      $container.packery();
    } else {
      // if expanding, fit it
      $container.packery( 'fit', event.currentTarget );
    }
  });
});

this is the codepen I found http://codepen.io/anon/pen/myLbmP

I've been trying using the .not selector, but I can't seem to rewrite it to work properly. Thanks in advance


Solution

  • Change your code to this:

    $( function() {
      var $container = $('.packery').packery();
    
      $container.on( 'click', '.item', function( event ) {
        var $item = $( event.currentTarget );
        var isExpanded = $item.hasClass('is-expanded');
        //NEW LINE BELOW
        $(".is-expanded").removeClass("is-expanded");
        if ( isExpanded ) {
          // if shrinking, just layout
          $container.packery();
        } else {
           $item.addClass('is-expanded');
          // if expanding, fit it
          $container.packery( 'fit', event.currentTarget );
        }
      });
    });