Search code examples
jqueryjquery-uijquery-tabs

customize the jquery tabs


I want to customize the jQuery default tabs. I have added the Add Tabs button in nav bar.

I want to add the newer tabs before that button: How I can do this?

HTML:

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("#tabs").tabs();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="tabs">
    <ul>
        <li><a href="#fragment-1"><span>One</span></a></li>
        <li><a href="#fragment-2"><span>Two</span></a></li>
        <li><input type='button' id='addTab' value='Add Tab'></li>
    </ul>

    <div id="fragment-1">
        <p>First tab is active by default:</p>
        <pre><code>$('#example').tabs();</code></pre>
    </div>
    <div id="fragment-2">
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
    </div>
</div>

    <input type='button' id='removeTab' value='RemoveTab'>
</body>
</html>

JS:

$('#addTab').live('click', function() {
    $("#tabs").tabs("add", "http://google.com", "A newTab", [2])
});
$('#removeTab').live('click', function() {
    $("#tabs").tabs("remove", "http://google.com", "A newTab", [2])
});​

​jsFiddle: http://jsfiddle.net/6VrwD/14/


Solution

  • I had the same problem. I found a bit tricky way to avoid it. I'm not sure it works on every browser environment, but please try the way below if you like it:

    At first, give a class name to the last <li> tag where you place the "Add Tab" button.

    <ul id="mytabs">
        <li><a href="#fragment-1"><span>One</span></a></li>
        <li><a href="#fragment-2"><span>Two</span></a></li>
        <li class='list_btn'><input type='button' id='addTab' value='Add Tab'></li>
    </ul>
    

    And next, in the click function, just add a tab to the last position. And after you add a new tab to the last position, you can switch the order of the last tab and the "Add Tab" button.

    $('#addTab').live('click', function() {
        // add a tab to the last position.
        $("#tabs").tabs("add", "http://google.com", "A newTab");
    
        // switch the order of the last tab and the "Add Tab" button.
        $(".list_btn").clone().appendTo("#mytabs");
        $(".list_btn:first").remove();
    });
    

    You will be able to rewrite the code more sophisticated way, especially at the last part where switching the order of the tabs. Thank you.