A. Z.
A. Z.

Reputation: 736

How to create jQuery code pattern?

I use code from this tutorial: jacklmoore.com/notes/jquery-tabs.

<ul class='tabs'>
    <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 id='tab1'>
    <p>Hi, this is the first tab.</p>
</div>
<div id='tab2'>
    <p>This is the 2nd tab.</p>
</div>
<div id='tab3'>
    <p>And this is the 3rd tab.</p>
</div>

script:

$('ul.tabs').each(function(){
    // For each set of tabs, we want to keep track of
    // which tab is active and it's associated content
    var $active, $content, $links = $(this).find('a');

    // If the location.hash matches one of the links, use that as the active tab.
    // If no match is found, use the first link as the initial active tab.
    $active = $($links.filter('[href="'+location.hash+'"]')[0] || $links[0]);
    $active.addClass('active');
    $content = $($active.attr('href'));

    // Hide the remaining content
    $links.not($active).each(function () {
        $($(this).attr('href')).hide();
    });

    // Bind the click event handler
    $(this).on('click', 'a', function(e){
        // Make the old tab inactive.
        $active.removeClass('active');
        $content.hide();

        // Update the variables with the new link and content
        $active = $(this);
        $content = $($(this).attr('href'));

        // Make the tab active.
        $active.addClass('active');
        $content.show();

        // Prevent the anchor's default click action
        e.preventDefault();
    });
});

If I want to have more than one system of tabs on a page, I have to repeat script code:

$('ul.tabs2').each(function(){...});
$('ul.tabs3').each(function(){...});

I do not want to have many copies of simmilar code. Is it possible to create a kind of code pattern for similar code lines from the example?

var = xxx
$('ul.tabs').each(function(){
  xxx
});
$('ul.tabs2').each(function(){
  xxx
});
$('ul.tabs3').each(function(){
  xxx
});

Upvotes: 1

Views: 154

Answers (2)

bozdoz
bozdoz

Reputation: 12860

You can have a comma separated list of selectors (like in CSS):

var = xxx
$('ul.tabs, ul.tabs2, ul.tabs3').each(function(){
  xxx
});

Within the function, $(this) then becomes a variable for each of the comma-separated selectors. The function would run over all three.

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

What you probably want is to turn it into a jQuery plugin that you can call on a collection of elements:

$.fn.myTabs = function() {

  return this.each(function() {

    // All code here

  });

};

$('.tabs2, .tabs3').myTabs();

Upvotes: 3

Related Questions