jrobinsonc
12/18/2013 - 11:20 AM

make_tabs

make_tabs

/*
 * Copyright (C) JoseRobinson.com
 * https://gist.github.com/jrobinsonc/8020730
 */
function makeTabs(container) {
    var $ = jQuery,
        $container = $(container),
        $$anchors = $container.find("> ul > li > a"),
        $$tabs = $container.find("> div > div");

    $$anchors.on('click', function(evt) {
        evt.preventDefault();

        var $self = $(this),
            $parent = $self.parent("li");

        if ($parent.is(".current")) {
            return;
        }

        $$tabs.hide();
        $$anchors.closest("li.current").removeClass("current");
        $parent.addClass("current");
        $$tabs.filter($self.attr("href")).fadeIn();
    });

    $$anchors.eq(0).trigger("click");
}
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tabs</title>
</head>
<body>

    <div id="my-tabs">
        <ul>
            <li><a href="#tab1">Tab 1</a></li>
            <li><a href="#tab2">Tab 2</a></li>
        </ul>
        
        <div>
            <div id="tab1">Tab 1 content</div>
            
            <div id="tab2">Tab 2 content</div>
        </div>
    </div>
    
    <script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="make-tabs.js"></script>
    <script>
        jQuery(document).ready(function($) {
            make_tabs("#my-tabs");
        });
    </script>
    
</body>
</html>