Reputation: 5986
I am working on a new project and the html does not allow me to have the tab headers and content within the same container. Therefore I have used Jquery and its nth child selector to enable and disable each tab. I have put together an example on jsfiddle http://jsfiddle.net/QdbdT/1/
This is the javascript
$(".control-bar-nav-wrapper ul li:nth-child(1)").on("click", function() {
$(this).addClass("active").siblings().removeClass("active");
$(".slider-wrapper-container > div:nth-child(1)").addClass("active").siblings().removeClass("active");
});
$(".control-bar-nav-wrapper ul li:nth-child(2)").on("click", function() {
$(this).addClass("active").siblings().removeClass("active");
$(".slider-wrapper-container > div:nth-child(2)").addClass("active").siblings().removeClass("active");
});
$(".control-bar-nav-wrapper ul li:nth-child(3)").on("click", function() {
$(this).addClass("active").siblings().removeClass("active");
$(".slider-wrapper-container > div:nth-child(3)").addClass("active").siblings().removeClass("active");
});
$(".control-bar-nav-wrapper ul li:nth-child(4)").on("click", function() {
$(this).addClass("active").siblings().removeClass("active");
$(".slider-wrapper-container > div:nth-child(4)").addClass("active").siblings().removeClass("active");
});
This does work, but i cant help that feel that there maybe a more efficient way of coding it. I thought that maybe some type of indexing would help but I could not get my head around it. If anyone has any ideas I would appreciate it, cheers.
Upvotes: 0
Views: 98
Reputation: 76557
You may want to consider using a data attribute
to allow you to map between the clicked element and the container element. Although, it doesn't seem the most elegant, it does help in the readability department.
CSS
<li class="applications active" data-display='Applications'>
<a href="#">Applications</a>
</li>
<li class="communities" data-display='Communities'>
<a href="#">Communities</a>
</li>
<li class="friends" data-display='Friends'>
<a href="#">Friends</a>
</li>
<li class="administration" data-display='Administration'>
<a href="#">Administration</a>
</li>
jQuery
$('[data-display]').on('click',function()
{
$('.slider-wrapper').removeClass('active');
$('#' + $(this).attr('data-display')).addClass('active');
});
Upvotes: 0
Reputation: 33661
You can use .index() and .eq() in your example to achieve the same effect and to combine all the functions
$(".control-bar-nav-wrapper ul li").on("click", function() {
$(this).addClass("active").siblings().removeClass("active");
$(".slider-wrapper-container > div").eq($(this).index()).addClass("active").siblings().removeClass("active");
});
Upvotes: 4