1
\$\begingroup\$

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();

});
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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

\$\endgroup\$
4
  • \$\begingroup\$ I put your code but did not work in jsbin \$\endgroup\$
    – AURIGADL
    Commented Mar 8, 2013 at 2:23
  • \$\begingroup\$ 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? \$\endgroup\$
    – darshanags
    Commented Mar 8, 2013 at 2:29
  • \$\begingroup\$ are nested tabs. lacking specify this in the question. \$\endgroup\$
    – AURIGADL
    Commented Mar 8, 2013 at 2:51
  • \$\begingroup\$ @AURIGADL answer updated \$\endgroup\$
    – darshanags
    Commented Mar 8, 2013 at 6:36
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ I put your code but did not work in jsbin \$\endgroup\$
    – AURIGADL
    Commented Mar 8, 2013 at 2:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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