\$\begingroup\$
\$\endgroup\$
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();
});
2 Answers 2
\$\begingroup\$
\$\endgroup\$
4
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
-
-
\$\begingroup\$ Is your html as you want it to be? This bit of code assumes that
#vtaband#vtab2are 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– darshanags2013年03月08日 02:29:17 +00:00Commented Mar 8, 2013 at 2:29 -
\$\begingroup\$ are nested tabs. lacking specify this in the question. \$\endgroup\$AURIGADL– AURIGADL2013年03月08日 02:51:05 +00:00Commented Mar 8, 2013 at 2:51
-
\$\begingroup\$ @AURIGADL answer updated \$\endgroup\$darshanags– darshanags2013年03月08日 06:36:08 +00:00Commented Mar 8, 2013 at 6:36
\$\begingroup\$
\$\endgroup\$
1
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.
You must log in to answer this question.
default