Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

jQuery UI Tabs: Changing selected tab

DZone's Guide to

jQuery UI Tabs: Changing selected tab

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

We're using the tabs part of the jQuery UI library on the project I'm currently working on and one thing we wanted to do was change the default tab that was being selected.

The documentation suggested that one way to do this was to give the index of the tab we wanted selected when calling the tabs function:

$( ".selector" ).tabs({ selected: 3 });
Since we wanted to select the tab by name based on a value from the query string we thought it would probably be simpler if we could just set the selected tab using a css class.

Our initial thought was that we could put the 'ui-tabs-hide' class on the divs that we wanted to hide and then not put that class on the one that we wanted to show.

Unfortunately that didn't work and the first tab was still being selected…

We downloaded version 1.8.2 of the library via Google's CDN (which seems really cool!) and were able to see that our class was actually intentionally being removed!

if (o.selected >= 0 && this.anchors.length) { // check for length avoids error when initializing empty list
				this.panels.eq(o.selected).removeClass('ui-tabs-hide');

Luckily a little further down the file there is a comment which explains some other ways to manipulate the selected tab:

// Selected tab
// use "selected" option or try to retrieve:
// 1. from fragment identifier in url
// 2. from cookie
// 3. from selected class attribute on <li>

We need to put the class 'ui-tabs-selected' on the appropriate <li> and then that will be the one that gets selected.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}