addclass - Optimize jquery add and remove class -


there must solution somewhere, not understand. problem simple, not know how optimize it.

i've got simple code of tab navigation (to view content)

$(function(){     $('#tab_o_nas article').hide();     $('#tab-1').show();     $('#opcja-1').addclass('active_tab');      $('#opcja-1').click(function(){         $(this).addclass('active_tab');         $('#opcja-2').removeclass('active_tab');         $('#opcja-3').removeclass('active_tab');         $('#opcja-4').removeclass('active_tab');         $('#tab_o_nas article').hide();         $('#tab-1').show();         return false;     });      $('#opcja-2').click(function(){         $(this).addclass('active_tab');         $('#opcja-1').removeclass('active_tab');         $('#opcja-3').removeclass('active_tab');         $('#opcja-4').removeclass('active_tab');         $('#tab_o_nas article').hide();         $('#tab-2').show();         return false;     });      $('#opcja-3').click(function(){         $(this).addclass('active_tab');         $('#opcja-1').removeclass('active_tab');         $('#opcja-2').removeclass('active_tab');         $('#opcja-4').removeclass('active_tab');         $('#tab_o_nas article').hide();         $('#tab-3').show();         return false;     });      $('#opcja-4').click(function(){         $(this).addclass('active_tab');         $('#opcja-1').removeclass('active_tab');         $('#opcja-2').removeclass('active_tab');         $('#opcja-3').removeclass('active_tab');         $('#tab_o_nas article').hide();         $('#tab-4').show();         return false;     });    }); 

fiddle

is there other way optimize addclass , removeclass? shorter code?

firstly, should fix markup of navigation ordered-list (the anchors should inside <li>s, not other way around):

<ol id="nav_o_nas">         <li id="opcja-1"><a href="#">tab 1</a></li>         <li id="opcja-2"><a href="#">tab 2</a></li>         <li id="opcja-3"><a href="#">tab 3</a></li>         <li id="opcja-4"><a href="#">tab 4</a></li> </ol> 

then, can add simple binder list, delegates anchors, finds index of item clicked, , toggles classes , articles appropriately:

$('#nav_o_nas').on('click', 'a', function(e) {     e.preventdefault(); // should used instead of return false;      // index of clicked link (0-3)         var index = $('#nav_o_nas a').index(this);      // select list items, remove class, target correct link, add class         $('#nav_o_nas li').removeclass('active_tab').eq(index).addclass('active_tab');     // hide articles, show correct article     $('article').hide().eq(index).show(); }); 

see working here http://jsfiddle.net/4ayms/2/


Comments