jQuery UI Tabs - How can I remove tab list item if corresponding content panel is empty?

areid picture areid · Mar 21, 2011 · Viewed 8.3k times · Source

I am using the basic jQuery UI Tabs setup with a cms system and I was wondering if I can hide a navigation tab if the content panel with the corresponding id is empty.

HTML

<div id="tabs">
    <ul>
        <li><a href="#tabs-1">Nunc tincidunt</a></li>
        <li><a href="#tabs-2">Proin dolor</a></li>
        <li><a href="#tabs-3">Aenean lacinia</a></li>
    </ul>
    <div id="tabs-1">
        <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
    </div>
    <div id="tabs-2">
        <p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
    </div>
    <div id="tabs-3">

    </div>

JavaScript

$(function() {
    $( "#tabs" ).tabs();
});

Help appreciated :)

Answer

Richard Marskell - Drackir picture Richard Marskell - Drackir · Mar 21, 2011

If you want to remove all empty tabs, you can use this code:

$(function() {
    var $tabs = $( "#tabs" );
    $tabs.tabs();
    var offst = 0;
    $('#tabs > div').each(function(index, elem) {
        if ($(elem).html().trim() === '') {
            $tabs.tabs( "remove" , index - offst);
            offst++;
        }
    });
});

Here's an example on jsfiddle

Notes:

  • The reason for the offst variable is because, if you remove a tab, the indexes will change.
  • This caches the tabs element in $tabs so it doesn't have to call the selector multiple times.
  • This uses the proper remove function of jQuery UI tabs.