user1560363
user1560363

Reputation: 13

accordion display position

I am a newbie for jQuery. I am trying jQuery UI accordion function and have a problem to display it in the proper position. I see below question has asked without answer which may be similar but more complicated than mine because it involves scrollTo which I don't use. jQuery scrollTo accordion end position

My question is simple. When I just use the accordion example code from jQuery website and put long content in the first panel. the 2nd panel will be pushed to a much lower position that you need to scroll down to find the panel. When you click 2nd panel, browser will not direct you to the top of the accordion or at least the top of the 2nd panel. Users need to scroll up before seeing the content in 2nd panel.

Here is the Fiddle code.

Please kindly help. Thanks!

Upvotes: 1

Views: 1937

Answers (1)

Alexander Schimpf
Alexander Schimpf

Reputation: 2392

You could set up code to scroll to the top of the new panel when the open panel changes, like this:

$("#accordion").accordion({
  change : function (event, ui) {
      $('html, body').animate({
         scrollTop: $(ui.newHeader).offset().top
      }, 500);          
  }
});

You might also want to set autoHeight: false on the accordion, to keep each panel sized to it's content.

$("#accordion").accordion({
  autoHeight: false,
  change : function (event, ui) {
      $('html, body').animate({
         scrollTop: $(ui.newHeader).offset().top
      }, 500);          
  }
});

EDIT: To fix the problem that was described in a comment, use the following code in the accordion's change event handler:

if(ui.newHeader.length > 0) {
    $('html, body').animate({
        scrollTop: $(ui.newHeader).offset().top
    }, 500);
}

This will prevent an error from occurring when all of the panels are closed.

A jsFiddle is here.

Upvotes: 2

Related Questions