0

I'm trying to do like http://css-tricks.com/text-fade-read-more/ -- but how do I get it to contact/expand both when clicking on the More button and on the body text?

Clicking on the body text works fine, but it only works the first time with the More button:

http://jsfiddle.net/frank_o/8ssrmxwp/10/

JS:

$.fn.truncate = function(container, maxHeight) {
  var totalHeight = 0,
    paragraph = container.find('p');

  container.css('max-height', maxHeight);

  paragraph.each(function() {
    totalHeight += $(this).outerHeight(true);
  });

  if(totalHeight > maxHeight) {
    container.append('<div class="fade_overlay"></div>');

    $('<a href="#" class="more">More</a>').insertAfter(container);

    var fadeOverlay = container.parent().find('.fade_overlay'),
      more = container.parent().find('.more'),
      duration = 100;

    // http://stackoverflow.com/questions/4911577/jquery-click-toggle-between-two-functions

    function firstClick() {
      container.css('height', container.height())
        .css('max-height', 9999);

      container.animate({
        'height': totalHeight
      });

      fadeOverlay.fadeOut(duration);
      // more.fadeOut(duration);

      container.one('click', secondClick);
    }

    function secondClick() {
      container.animate({
        'height': maxHeight
      });

      fadeOverlay.fadeIn(duration);
      // more.fadeIn(duration);

      container.one('click', firstClick);
    }

    container.one('click', firstClick);
    more.one('click', firstClick);
  }    
}

$('.article').each(function () {
    $.fn.truncate($(this), 220);
});

I've tried to lay out the functions differently but to no avail:

http://jsfiddle.net/frank_o/8ssrmxwp/12/

JS:

var oddClick = function(target) {
  target.one('click', function() {
    var target = $(this);

    target.css('height', container.height())
      .css('max-height', 9999);

    target.animate({
      'height': totalHeight
    });

    fadeOverlay.fadeOut(duration);
    // more.fadeOut(duration);

    target.one('click', evenClick);
  });
}

var evenClick = function(target) {
  target.one('click', function() {
    var target = $(this);

    target.animate({
      'height': maxHeight
    });

    fadeOverlay.fadeIn(duration);
    // more.fadeIn(duration);

    target.one('click', oddClick);
  });
}

oddClick(container);
oddClick(more);
Mark Boulder
  • 13,577
  • 12
  • 48
  • 78

1 Answers1

1

Through more.one('click', firstClick); the event handler gets removed after the first call. Change it to more.on('click', firstClick); and it works.

Florian Gl
  • 5,984
  • 2
  • 17
  • 30