I have created a reusable code for jQuery tab functionality for my client site.
Every thing works fine but the only thing I am worried is that the lines code I have written for this small feature is very high. Can any one help me to shrink lines of code or any suggestions.
Here is my script
/**
* @param link Class name of the tab header
* @param content Class name of the element
* @param current should be class name of the element which you want to show in the begin
* @example _initTab('.tab-link','.tab-content','.first-tab-content-id')
*/
function _initTab(link, content, current) {
var tabLink = link || '.tab-link';
var tabContent = content || '.tab-content';
var elementId = current || null; //Clicked element
//In the begin hide all the tabs
$(tabContent).addClass('hide');
function animateIcon() {
var iconElement = $(tabLink).find('.icon');
var addClassName = iconElement.hasClass('sz-icon-arrow-right') ? 'sz-icon-arrow-down' : 'sz-icon-arrow-right';
var removeClassName = iconElement.hasClass('sz-icon-arrow-right') ? 'sz-icon-arrow-right' : 'sz-icon-arrow-down';
iconElement.removeClass(removeClassName).addClass(addClassName);
}
function showElement(elId) {
animateIcon();
$(tabContent).addClass('hide');
$(elId).removeClass('hide');
}
//If any tab-content needs to be opened in the begin
if (elementId) {
showElement(elementId);
}
//Bind click events for the tab
$(document).on('click', tabLink, function () {
elementId = $(this).data('element');
showElement(elementId);
});
}
My Html will look something like this
<div class="tab-wrapper">
<h3 class="tab-link" data-element=".credit-card-sec">
Credit Card
<span class="icon sz-icon-arrow-right"></span>
</h3>
<div class="tab-content credit-card-sec">
<div class="credit-card-form">
Credit card form elements
</div>
</div>
<h3 class="tab-link" data-element=".debit-card-sec">
Credit Card
<span class="icon sz-icon-arrow-right"></span>
</h3>
<div class="tab-content debit-card-sec">
<div class="debit-card-form">
Debit card form elements
</div>
</div>
</div>