Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery expander on collapse

Tags:

jquery

I'm using jQuery expander for a read more-read less type situation and it's working fine. I'd like to scroll the user to the headline of the article after they click read less. I'm trying to figure out the code but I'm not too familiar with jQuery.

$('.expand_please').expander({
  slicePoint: 1000,
  widow: 2,
  expandEffect: 'show',
  userCollapseText: 'Read less',
  expandText: 'Read more',
  onCollapse: $(this).closest('h2').scroll()
});

EDIT: Relevant HTML:

<div class="row keyline" id="show_article1">
  <h2 style="margin-bottom: 1em;">TITLE</h2>
  <div class="link_article" style="display: none;"><a href="/share/thomas/more/18" data-remote="true">READ MORE</a></div>
  <div class="fivecol">
    <img alt="thumbnail" class="thumbnail" src="/system/thumb.jpg">
  </div>
  <div class="sevencol last expand_please marginer"><div class="summary" style="display: none;">
  ARTICLE BODY TEXT
  <span class="read-less"><a href="#">Read less</a></span>
  </div>
</div>
like image 446
t56k Avatar asked Dec 21 '25 17:12

t56k


1 Answers

To scroll to the element in question, you simply need to get its offset().top value, and pass that value to the animate() method.

It'd look something like this:

$('.expand_please').expander({
      slicePoint: 1000,
      widow: 2,
      expandEffect: 'show',
      userCollapseText: 'Read less',
      expandText: 'Read more',
      onCollapse: function(){
        var amount = $(this).siblings('h2:first').offset().top;
        $('body, html').animate({scrollTop : amount},800);

      }
});

The above method will obviously animate the scroll, which is a nice touch, but should you just want something more basic, you can use element.scrollIntoView(true);1

In your case, that would be:

...
onCollapse: function(){
    // pass true to align with top of scroll area
    // pass false to align with bottom of scroll area
    $(this).siblings('h2:first').scrollIntoView(true)
}
...

1 https://developer.mozilla.org/en-US/docs/DOM/element.scrollIntoView

like image 146
couzzi Avatar answered Dec 24 '25 09:12

couzzi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!