0

I have this code to make a paragraph collapse but I would like to add the link (View More/Less) to the last visible line of the paragraph. Currently it is adding it after the collapsed paragraph.

$(document).ready(function() {
  var maxheight = 35;
  var showText = "More";
  var hideText = "Less";

  $('.text').each(function() {
    var text = $(this);
    if (text.height() > maxheight) {
      text.css({
        'overflow': 'hidden',
        'height': maxheight + 'px'
      });

      var link = $('<a href="#">' + showText + '</a>');
      var linkDiv = $('<span></span>');
      linkDiv.append(link);
      $(this).after(linkDiv);

      link.click(function(event) {
        event.preventDefault();
        if (text.height() > maxheight) {
          $(this).html(showText);
          text.css('height', maxheight + 'px');
        } else {
          $(this).html(hideText);
          text.css('height', 'auto');
        }
      });
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="text">
  <p>Photography has long been shaped by the desire to understand and explore the medium’s essential materials. Taking that spirit of invention and discovery as its point of departure, this exhibition features the work of seven artists—Matthew Brandt, Marco Breuer, John Chiara, Chris McCaw, Lisa Oppenheim, Alison Rossiter, and James Welling—who focus their investigations on the light sensitivity and chemical processing of photographic papers, challenging us to see the medium anew.</p>
</section>
Saeed Abbaspour
  • 329
  • 4
  • 16

1 Answers1

1

Here's a bin with my solution: http://jsbin.com/kovibo/2/edit?html,js,output

I repurposed the code from this answer to create a plugin that returns the first line of the paragraph: Use :first-line pseudo-element as a jQuery selector

I made a few changes to the way things are done; hopefully my comments will give you a good start. Let me know if you have any questions on anything within.

Community
  • 1
  • 1
whiterabbit25
  • 267
  • 3
  • 10