Iggy's Pop
Iggy's Pop

Reputation: 599

Toggle all to original state before toggling clicked item

When I click an item it expands. When I click another item it also expands but leaves the first one expanded too. I only want one item expanded at any time ie: the one I click on. So I need to basically toggle everything to it's original state and then only expand the one I actually click on. There is a codepen for the example I am using.

// external js: masonry.pkgd.js

var $grid = $('.grid').masonry({
  columnWidth: 120,
  itemSelector: '.grid-item'
});

$grid.on( 'click', '.grid-item-content', function( event ) {
  $( event.currentTarget ).parent('.grid-item').toggleClass('is-expanded');
  $grid.masonry();
});

See the Pen Masonry - animate item size by Dave DeSandro (@desandro) on CodePen.

Upvotes: 3

Views: 48

Answers (1)

Arg0n
Arg0n

Reputation: 8423

Try changing the code like this:

var $grid = $('.grid').masonry({
  columnWidth: 120,
  itemSelector: '.grid-item'
});

$grid.on( 'click', '.grid-item-content', function( event ) {
  var parent = $(event.currentTarget).parent('.grid-item'); //Fetch only parent once
  parent.siblings().removeClass('is-expanded'); //Remove class from others
  parent.toggleClass('is-expanded'); //Set class on clicked item
  $grid.masonry();
});

This will remove the class from all items (the items parents siblings) before applying it to the item you clicked.

Upvotes: 1

Related Questions