RiotAct
RiotAct

Reputation: 773

JQuery accordion scroll open element into view

I have a simple accordion script and would like for the items to scroll into view when they are "opened". The issue I am running into on mobile devices, is if one has a long content, when the next is opened, it moves out of view when the other is closed.

Here is an example code: HTML

<div id="mobile-bios">
  <div class="leader-image">Section 1</div>
  <div class="leader-content">
    Leader 1
  </div>
  <div class="leader-image">Section 2</div>
  <div class="leader-content">
    Leader 2
  </div>
  <div class="leader-image">Section 3</div>
  <div class="leader-content">
    Leader 3
  </div>

</div>

CSS

.leader-content {
  display: none;
  height: 500px;
}

JQUERY

// Leader Accordion
$('#mobile-bios').find('.leader-image').click(function() {

  //Expand or collapse this panel
  $(this).addClass('active').next().slideToggle('fast');

  $('html,body').animate({
    scrollTop: $(this).offset().top
  }, 500);

  //Hide the other panels
  $("#mobile-bios .leader-content").not($(this).next()).slideUp('fast');
  $('#mobile-bios .leader-image').not($(this)).removeClass('active');

});

I tried using the scrollTop function, and while it kind of works, it doesn't do what I would like.

I also have a fiddle here.

Upvotes: 2

Views: 480

Answers (1)

RiotAct
RiotAct

Reputation: 773

Ok I figured out a way to fix this by adding a bind to the click function to complete the scrolling function at the right time. Here is the final JQuery script:

// Leader Accordion
$('#mobile-bios').find('.leader-image').click(function() {
  //Expand or collapse this panel
  $(this).addClass('active').next().slideToggle('fast');

  //Hide the other panels
  $("#mobile-bios .leader-content").not($(this).next()).slideUp('fast');
  $('#mobile-bios .leader-image').not($(this)).removeClass('active');
});

$('#mobile-bios .leader-image').bind('click', function() {
  var self = this;
  setTimeout(function() {
    theOffset = $(self).offset();
    $('body,html').animate({
      scrollTop: theOffset.top - 100
    });
  }, 310);
}); 

Upvotes: 2

Related Questions