sir_thursday
sir_thursday

Reputation: 5409

Optimizing "tab" code

I've implemented a "tab" control that switches between two different tabs, pretty self explanatory. Here's the relevant code:

HTML:

<div class="tabs margin-r">
  <div id="tab-1" class="tab">Tab 1</div>
  <div id="tab-2" class="tab">Tab 2</div>
</div>

JS:

var tabs = {

  init: function() {
    // Initialize cookie
    if(readCookie("tab_cookie")==null) {
      $("#tab-1").addClass("current-tab");
    } else {
      $("#" + readCookie("tab_cookie")).addClass("current-tab");
    }
    // Handle click event
    $(".tab").click(tabs.switchTabs);
  },

  switchTabs: function() {
    $(this).siblings(".tab").removeClass("current-tab");
    $(this).addClass("current-tab");
    createCookie("tab_cookie", $(this).attr("id"));
  }
};

$(document).ready(tabs.init);

I'm looking to optimize this code, and provide support for multiple tabs to be on the same page. Obviously, the use of ids here makes multiple tabs difficult, so I'm looking to change that implementation. Any ideas, best practices, etc?

Upvotes: 0

Views: 85

Answers (2)

Ramy Nasr
Ramy Nasr

Reputation: 2527

instead of using id you can use data for example:

<div data-tab="1" class="tab"></div>

and that way you can access this using jQuery data():

$(this).data('tab'); // returns string: 1

// Get tab id and defaults to 1 if null
var tab_id = readCookie("tab_cookie") || 1;

// Set current tab
$('[data-tab=' + tab_id + ']', '.tabs').addClass('current');

instead of attaching a listener to each tab. You can delegate events by attaching the listener to the parent:

$('.tabs').on('click', '.tab', tabs.switchTabs);

This will also give you the benefit if you even want to add more tabs using ajax after the DOM was already created.


No need to use siblings() if there is only one tab set in page

You can write this:

$(this).siblings(".tab").removeClass("current-tab");
$(this).addClass("current-tab");

like that:

$('.current-tab').removeClass('current-tab');
$(this).addClass("current-tab");

if you still need to use siblings() you can still use $(this).siblings('current-tab') to select only the tabs that needs to be changed, rather than all of them.

Upvotes: 1

Orenrocco
Orenrocco

Reputation: 21

Well you are going to have loading issues, because if you are talking narrowing the html files into one html file you are going to have to consider minifying the html or other. However, about two years ago I tried to do what you are doing now, and it became a big mess. I came to the conclusion that it is best to run each individual page within the tabs as php sessions so if you switch tabs the other session would close from the tab you switched from. But for what you are specifying, you could list the tabs as variables, and go from there

Upvotes: 0

Related Questions