Capturing the expand and collapse event on a jQuery Mobile collapsible set

Filed under: jQuery, jQuery Mobile

comments (2) Views: 10,581

This morning over at Goba.mobi I needed to capture the expanding/collapsing of a jQuery Mobile collapsible set. I wanted to add a class to an element, but only when a a specific set was opened. I Googled for a few minutes before finding a post over on the jQuery Mobile forums. Turns out it's pretty simple. Here's what I did.

In our case we're using form tags as the container, so that's what I bound my event to. I only cared about the expand event since I wanted to target the opening of a specific container, namely the Phone section. Next I used simple JavaScript property access (this.id) to check the id if the current target. Finally I added and removed a class as needed.

Pro-tip: Rather than applying a large number of attributes to an element with jQuery's css() method, consider creating a class for those styles. Then using the addClass()/removeClass() partner methods to add and remove the styling. Much simpler and it keeps your CSS out of your JavaScript code.

Amazon logo

If this article was interesting, or helpful, or even wrong, please consider leaving a comment, or buying something from my wishlist. It's appreciated!

comments powered by Disqus