Share it!

Accordions, also known as collapsible sets , allow to show a large amount of step- or category-arranged content using a minimal amount of space. This is especially useful when screen sizes are small, such in a mobile device, or when you have a lot of content to display in a single page.

Working with collapsible sets

If you work with jQuery Mobile, or any accordions for that matter, you may have noticed that content expands right below its header. If you tap/click on a header that’s near the bottom of the screen, content will expand outside the bounds of the screen. This will force you to scroll to see it and tap on the screen twice to start looking at the actual content.

To the top

I faced this problem quite a few times when working with jQM’s collapsible widget so I created a small piece of JS code that scrolls the content to the top, making it always visible.

At the core, a handler is attached to every collapsible (filtered by their jQM’s role) so that, every time a collapsible’s header is tapped, it will be moved to the top of the page (both header and content). To accomplish this, the script first closes all the other collapsibles in the set (if any) and then scrolls to the top of the page using a smooth animation.


/**
* Attach a handler to collapsible sets.
*
* Attach a handler to every collapsible (filtered by their jQM’s role) so that,
* every time a collapsible’s header is tapped, it will scroll to the top of the page (both header and content)..
*
* @link https://imelgrat.me/javascript/collapsible-scroll-jquery-mobile/
*/
$(document).on('pagebeforeshow', function()
{
$("[data-role='collapsible']").collapsible(
{
collapse: function(event, ui)
{
$(this).children().next().slideUp(350);
},
expand: function(event, ui)
{
$(this).children().next().slideDown(500);
jQuery('html, body').animate(
{
scrollTop: jQuery(this).offset().top 10
}, 500);
}
});
});

Here’s a short demo to test the script. You can also see it in action and play with it by visiting CodePen or get the code from this GitHub gist.

See the Pen Move content to the top in jQuery Mobile collapsible sets by Iván Melgrati (@imelgrat) on CodePen.


Share it!