0

The below function is used on the html page to show/hide more details about a comment. The issue is that when the read more link is clicked, the page always scrolls up to the top, therefore taking the user away from the actual comment they are trying to view.

Would it be correct to try and use return false; in the code block below? if so where?

var collapseIt = function(){

     var collapsedSize = '25px';
   $('.item').each(function() {

    var h = this.scrollHeight;

    console.log(h);
    var div = $(this);

    if (h > 40) {
      div.css('height', collapsedSize);
      div.after('<a id="more" class="item" href="#">Read more</a><br/>');
      var link = div.next();
      link.click(function(e) {
        e.stopPropagation();

        if (link.text() != 'Collapse') {
          link.text('Collapse');
          div.animate({
            'height': h
          });

        } else {
          div.animate({
            'height': collapsedSize
          });
          link.text('Read more');
        }

      });
    }

  });   
};
Dano007
  • 1,872
  • 6
  • 29
  • 63

3 Answers3

1

Easiest way is to prevent the default action:

link.click(function(e) {
  e.preventDefault();
});

Another way is to return to the scrolled position:

var scrollTop = document.body.scrollTop;

link.click(function(e) {
  document.body.scrollTop = scrollTop;
});
Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
1

Replace your code for adding 'Read More' link with the following line :

div.after('<a id="more" class="item" href="#!">Read more</a><br/>');

This answer is explained wonderfully here :

https://stackoverflow.com/a/11246131/802651

Community
  • 1
  • 1
Adarsh Konchady
  • 2,577
  • 5
  • 30
  • 50
0

Put

e.preventDefault()

at the beginning of the click handler.

Barmar
  • 741,623
  • 53
  • 500
  • 612