1

I have a set of buttons that reveal content using a jquery accordion (for a mobile site). I am wondering what the best way would be so that when a user selects the other button, it scrolls to the top of that button that was selected.

Here's what I currently have for my accordion script:

$( "#accordion" ).accordion({
        collapsible: true,
        active: false, 
        autoHeight: false,
        clearStyle: true
    });
});

I also made this fiddle, but it doesn't really function like it does when viewing it on a mobile device (unless you resize the window/viewport area. Then it functions like it would on a mobile device.)

ultraloveninja
  • 1,969
  • 5
  • 27
  • 56

1 Answers1

1

I found this related question.

According to the comment, you could use element.scrollIntoView() for the active element, since this 'is supported in all major browsers'.

There is also a mention to a jquery plugin (in the third answer), which does the same thing.

If you bind to the change event of the accordion, the following should work:

$('#myaccordion').accordion({
  // .. other options
  change: function(event, ui) {
            ui.newHeader.scrollIntoView(); // or scrollintoview(), 
                                           // if you're using the plugin
          }
});

I haven't tried either solution, perhaps you could post a comment if one of them works?

EDIT

After rereading your question it seemed, that you won't need the scrollIntoView function/plugin, since the button you press will usually already be in view (how would you have pressed it...).

So, you might just use window.scroll (or whatever scrollable top-level container you use).

Based on your jsfiddle example, the following seems to work:

    $( "#accordion" ).accordion({
        collapsible: true,
        active: false, 
        autoHeight: false,
        clearStyle: true,
        change: function(event, ui) {
            if (ui.newHeader) {
            var scrollTop = ui.newHeader.position().top;
            window.scroll(0,scrollTop);
            }
        }
    });
Community
  • 1
  • 1
MartinStettner
  • 28,719
  • 15
  • 79
  • 106
  • Hmmm. Well, I tried adding in the scrollIntoView plugin and that doesn't seem to work. Unless I have it setup wrong. Here my updated fiddle: http://jsfiddle.net/ultraloveninja/6skgc/6/ – ultraloveninja Jul 17 '12 at 16:13