codacopia
codacopia

Reputation: 2501

Need to add Prev/Next toggles to tab script

Here is the JS Fiddle of my existing tab build:

http://jsfiddle.net/getpresto/89ZAG/1/

<ul class="tabs">
<li><a href="#">Tab 1</a></li>
<li><a href="#">Tab 2</a></li>
<li><a href="#">Tab 3</a></li>
</ul>

What I need is the ability to add a far left button that will cycle the user to the next tab to the left and a far right button that will cycle the user to the right tab. If the user reaches either end and continues to click the same prev or next option then they will simply continue through to the other end of tabs. So if they are on tab 1 and click the left navigation button then they will go to tab 3 as an example.

How can I adjust this script to include this feature? Thank you for your time.

Upvotes: 1

Views: 970

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

Basic steps for any version will be:

  • You need to get the current selected tab index,
  • alter it with +1 or -1 (depending on the button pressed),
  • then wrap the value based on the number of tabs,
  • then update the current tab.

If you can upgrade to JS 1.9.1 or higher something like this will work:

JSFiddle: http://jsfiddle.net/89ZAG/8/

$(document).ready(function () {
    var selectTab = function (delta) {
        //var index = $("#tabs .current").parent().index();
        var index = $("#tabs").tabs('option', 'active');
        var count = $("#tabs ul > li").length;
        index += delta;
        if (index < 0) {
            index = count - 1;
        }
        if (index >= count) {
            index = 0;
        }
        $('#tabs').tabs('option', 'active', index);
    };

    $("#tabs").tabs();
    $('#prev').click(function () {
        selectTab(-1);
    });
    $('#next').click(function () {
        selectTab(1);
    });
}); //end document ready

But the HTML also needs to be restructured to suit that later tabs requirements (the panel selectors are in the link href properties:

HTML:

<div id="tabs">
    <ul class="tabs header">
        <li><a href="#tab1">Tab 1</a>

        </li>
        <li><a href="#tab2">Tab 2</a>

        </li>
        <li><a href="#tab3">Tab 3</a>

        </li>
    </ul>
    <div class="panes" id="tab1">
        <!--Start Tab 1-->Tab 1 content.</div>
    <div class="panes" id="tab2">
        <!--End Tab 1 & Start Tab 2-->Tab 2 content.</div>
    <div class="panes" id="tab3">
        <!--End Tab 2 & Start Tab 3-->Tab 3 content.</div>
    <!--End Tab 3-->
    <!--End Panes-->
</div>
<input class="header" type="button" value="Prev" id="prev" />
<input class="header" type="button" value="Next" id="next" />

You will need to style the two buttons so they appear beside/over your tabs.

Upvotes: 1

Related Questions