1

Let me know if the title of this query is unclear. The below code excerpt instead makes the clicked image disappear.

I have reviewed code that toggles an element's height between a set number of pixels. I have reviewed Desandro's masonry toggle code. And I have reviewed the jquery documentation. Nonetheless I'm struggling to realise a solution.

I appreciate that this may be simple to experts but for a novice some direction would be appreciated.

i_stack

$grid.on('click', '.grid-item', function() {
  $(this).toggle(
    function() {
      $(this).height($(this).height() + 100);
    },
    function() {
      $(this).height($(this).height() - 100);
    }
  );
});
Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61
i_stack
  • 23
  • 1
  • 8
  • I think this has a wrong logic, as the [Toggle documentation](http://api.jquery.com/toggle/) doesn't accept 2 functions. The first parameter is expected to be the duration in ms. I think you should use [toggleClass](http://api.jquery.com/toggleclass/) instead. – Dimitris Damilos Feb 03 '19 at 10:24
  • 1
    Thanks Dimitris. I considered the toggleClass but struggled to apply it to my particular problem. Fortunately, Andy's answer seems to work below. – i_stack Feb 04 '19 at 00:03

1 Answers1

1

First off, toggle is meant to completely hide or show an element:

Description: Display or hide the matched elements.

Instead, consider animate using your own toggle logic.

var counter = 0;

$('.grid').on( 'click', '.grid-item', function() {
  // counter will toggle between 0 or 1
  let direction = ++counter % 2 === 1 ? "-=100px" : "+=100px";
  $(this).animate({ "height": direction }, "slow" );
});
.grid-item {
  background-color: blue;
  color: white;
  height: 150px;
  width: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="grid">
  <div class="grid-item"></div>
</div>

https://jsfiddle.net/qxb10rnv/

Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61
  • 1
    Thank you kindly, Andy - I was really battling. There's a complication in my design (I have overlays on the imgs to which I'll apply your code, but presumably that'll only work after reconfiguring the masonry so that it arranges the overlays rather than images) but I'm optimistic I'll be able to adapt your solution. Thanks again, i_stack – i_stack Feb 03 '19 at 23:59
  • In case of interest, the extension mentioned in my previous comment was simpler than anticipated - the code was adjusting grid-item heights on click but not rearranging the masonry to show this. The below code fixes this: var counter = 2; $grid.on( 'click', '.grid-item', function() { let direction = ++counter % 2 === 1 ? "+=100px" : "-=100px"; $(this).animate({ "height": direction }, "slow", function(){ $grid.masonry('layout') } ); }); – i_stack Feb 04 '19 at 01:06