简体   繁体   中英

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

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 );
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM