jquery tabs with extra padding on dynamically create / delete new tabs

advertisements

I have an issue with Jquery Tabs and to be more precise with padding between each tabs that, on my page, I create and delete several times.

Every time that I create and delete a tab, and extra space is left on tabs area:

Why the distance between [ Main Tab ] and [ Tab 1 ] is not the same between [ Tab 1 ] and [ Tab 9 ] considering that in the middle 8 new tabs has been created and removed?

HTML:

<div id='demo'>
<ul>
    <li><a href="#main">Main Tab</a></li>
    <li><a href="#ref">Tab 1</a></li>
</ul>
<div id='main'>Main</div>
<div id='ref'>Reference tab</div>
</div>

JavaScript:

$( '#demo' ).tabs();
var tabs = $( "#demo" ).tabs();
var ul = tabs.find("ul");
//-- Create 10 tabs
for (i = 1; i < 10; i++) {
    $( "<li><a href='#tab" + i + "'>Tab " + i + " </a></li>" ).appendTo(ul);
    $( "<div id='tab" + i + "' style=''>This is the tab " + i + "</div>" ).appendTo(tabs);
}
tabs.tabs('refresh');

//-- Delete 9 tabs
for (i = 1; i < 9; i++) {
    $( "#demo ul a[href^=#tab" + i + "]" ).remove();
    $( "#demo div[id^=tab" + i + "]" ).remove();
}
tabs.tabs('refresh');

This is the JsFiddle to reproduce it

http://jsfiddle.net/wh3ct1cn/


The problem is that you're removing just the anchors, and not the entire list items. Here's a fix:

$( "#demo ul a[href^=#tab5]" ).parent('li').remove();

Demo


Rather than deleting them from the DOM, why not use the remove() function?

//-- Delete tabs 5, 6, and 7
for (i = 7; i > 4; i--) {
    $("#demo").tabs('remove', i);
}

Demo

I'm working in reverse order because the indexes change after each operation.