Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Any idea how to write this code better."the html is nested tabs" Two selectors and two similar events, in a function would be better or a pattern to reduce lines. eg .jsbin

$(function() {
  var $items  = $('#vtab>ul>li'),
      $items2 = $('#vtab2>ul>li');

  $items.mouseover(function() {
    var index = $items.index($(this));
    $items.removeClass('selected');
    $(this).addClass('selected');
    $('#vtab>div').hide().eq(index).show();
  }).eq(1).mouseover();

  $items2.mouseover(function() {
    var index = $items2.index($(this));
    $items2.removeClass('selected');
    $(this).addClass('selected');
    $('#vtab2>div').hide().eq(index).show();
  }).eq(1).mouseover();

});
share|improve this question

migrated from stackoverflow.com Mar 8 '13 at 1:22

This question came from our site for professional and enthusiast programmers.

2 Answers 2

up vote 1 down vote accepted

HTML (add tab-panel class to tab containers):

<div id="vtab" class="tab-panel">

<div id="vtab2" class="tab-panel">

jQuery:

$(function () {

    $(".tab-panel").each(function () {

        var $currentPanel = $(this),
        $items = $currentPanel.find(">ul>li");

        $items.mouseover(function () {
            var $this = $(this),
            index = $items.index($this);

            $items.removeClass('selected');
            $this.addClass('selected');
            $currentPanel.find(">div").hide().eq(index).show();
        }).eq(1).mouseover();

    });

});

jsbin here

share|improve this answer
    
I put your code but did not work in jsbin –  AURIGADL Mar 8 '13 at 2:23
    
Is your html as you want it to be? This bit of code assumes that #vtab and #vtab2 are on the same level but it looks like they are nested, is this correct? Can you validate your html as well and update the jsbin please? –  darshanags Mar 8 '13 at 2:29
    
are nested tabs. lacking specify this in the question. –  AURIGADL Mar 8 '13 at 2:51
    
@AURIGADL answer updated –  darshanags Mar 8 '13 at 6:36

Give those #vtabs a class and it should be simple:

$(function() {
    $('.vtab > ul > li').mouseover(function() {
        var $this = $(this);

        $this.addClass('selected').siblings().removeClass('selected');
        $this.closest('.vtab').find('div').eq($this.index()).hide().siblings().show();
    }).each(function() {
        $(this).find('> ul > li').eq(1).mouseover();
    });
});

Although I'd try turning it into a plugin at this point.

share|improve this answer
    
I put your code but did not work in jsbin –  AURIGADL Mar 8 '13 at 2:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.