0

I have written a plugin for collapsing content and when the content is greater than the desired height of the item being collapsed. When 'Continue Reading' is clicked it then uses the original height of the content to expand out.

I am having trouble however getting this to work when the screen resizes. What happens is as the container begins to resize the content inside neutrally reformats and becomes longer. This means when I click on 'Continue Reading' it expands out but only to the height of the div when the page first loaded.

How could I make it so this would update when the page was resized?

Here is an example here.

(function($){
  $.fn.toggleCollapse = function() {
    return this.each(function () {
      var $content = $(this);
      var $contentHeight = $content.height();
      var $collapseHeight = $(this).data('collapse-height');
      $content.height($collapseHeight);

      if (parseInt($collapseHeight) < $contentHeight) {
        $content.append('<div class="gradient"></div>');
        $content.append('<a href="#" class="collapse-toggle">Continue Reading</a>');

        $content.find('.collapse-toggle').click(function(){
          $content.toggleClass('expanded');
          if ($content.hasClass('expanded')) {
            $content.height($contentHeight);
            $(this).html("Collapse");
          } else {
            $content.height($collapseHeight);
            $(this).html("Continue Reading");
          }
        });
      }
    });
  };
})(jQuery);

I am using this in my code to handel all other resize actions:

var resizeTimeout;
window.onresize = function() {
  clearTimeout(resizeTimeout);
  // handle normal resize
  checkWidth();

  resizeTimeout = setTimeout(function() {
    // handle after finished resize
  }, 250);
};

function checkWidth () {
  var width = $(window).width();
  if (width > 1023) {

  }
  if (width < 1023) {

  }
}
Daimz
  • 3,243
  • 14
  • 49
  • 76
  • After `// handle after finished resize` add `$('.class').toggleCollapse()`? You might have to play with it to get it to work how you want it. Like only adding `.collapse-toggle` & `. gradient` if they're not there already. and `$content.find('.collapse-toggle').off('click').click`. – Adam Merrifield Sep 03 '14 at 03:24
  • I have updated the Fiddle so now it doesn't duplicate the '.gradient' & '.collapse-toggle'. I also tried setting the expanded height to auto. which gives me the right height but it's doesn't animate. I tried using this http://stackoverflow.com/a/13701487/1031184 but I couldn't get it to work. – Daimz Sep 03 '14 at 05:56

1 Answers1

0

I have solved this.

Rather than changing height in the JS. Set the height on the '#collapse-content' to height: auto and then change the JS form .height() to css.('max-height', $collapseHeight) This will animate and expanded and collapse. There will be some issues in IE8 with max-height I am sure but this is a good solution for what I need now.

Daimz
  • 3,243
  • 14
  • 49
  • 76