t56k
t56k

Reputation: 6981

jQuery expander on collapse

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>

Upvotes: 3

Views: 1090

Answers (2)

couzzi
couzzi

Reputation: 6366

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

Upvotes: 3

njwags
njwags

Reputation: 1147

I Believe that onCollapse wants a function to call when the expander collapses. You are also looking for jQuery's .scrollTop method not .scroll. .scroll attaches a handler to the scroll event. Try the following

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

UPDATE: .closest() will not work because it looks through ancestors of the matched set of elements. In the HTML provided you are actually trying to select a sibling, e.g.

$(this).siblings('h2').first().offset().top

Upvotes: 2

Related Questions