I recently needed to open and close a jQuery Mobile collapsible widget from my own JavaScript code, in response to other events on the page. Unfortunately, looking at the documentation for the collapsible widget’s public methods, where you’d expect to find expand and collapse methods, you won’t find much help:

Manually firing a click on the collapsible div element is one option, as if the user had tapped it. I’ve never been a fan of that approach though, and especially not in frontend JavaScript. Co-mingling your internal flow control with events that are intended to be triggered by user input is a good way to find yourself with inconsistent issues that are difficult to reproduce and track down.

More importantly, I needed to control whether the widget was expanded or collapsed in this case. So, I really wanted to find a clean way to deterministically open and close the collapsible instead of toggling it. Luckily, there turned out to be an easy, straightforward way to do that.

Looking under the hood

A nice thing about interpreted languages like JavaScript is that it’s easy to take a look at the source for a library you’re using and find undocumented behaviors when these situations arise. For example, here’s the relevant source for jQuery Mobile’s collapsible widget (as of version 1.1):

The CSS toggling in that event handler is less important than how that handler is triggered. Seeing that the widget bound a couple custom events named “expand” and “collapse”, it seemed logical that using jQuery’s trigger method on the collapsible div might have the same effect.

To test that the solution is really that simple, you can open a page with a collapsible and experiment from that browser’s JavaScript console. That approach is great for testing JavaScript ideas in any browser, but I used Chrome since it’s based on the same rendering engine that my jQuery Mobile site was targeting.

Sure enough, selecting a collapsible div and chaining .trigger('expand') or .trigger('collapse') opened and closed the widget just as if a user had clicked on the collapsible’s heading.

Pulling the “trigger”

To give you a more concrete example of how that works, here’s an excerpt of a simple jQuery Mobile page with two collapsibles on it:

Given those two widgets, you could use this JavaScript to select the first one and ensure that it’s expanded:

Similarly, you could use this code to force the second one to be collapsed:

Nice and easy. Now we have complete control over the collapsible instead of being limited to a toggle operation.

Of course, since this is an undocumented behavior, there’s no guarantee this will continue working in future versions of jQuery Mobile. However, it seems straightforward enough that it’s unlikely to change in the near future.