Reputation: 271
How do I add a class to an <li>
element when it is clicked?
I have the following code:
<ul id="moodtabs" class="side bar tabs">
<li id="tabs1" onclick="showStuff(this)" class="mbutton">Cheerful</li>
<li id="tabs2" onclick="showStuff(this)" class="mbutton">Romantic</li>
</ul>
<div id="tabs-1" class="tabContent" style="display: block;">
<h4>Content 1</h4>
</div>
<div id="tabs-2" class="tabContent" style="display: block;">
<h4>Content 2</h4>
</div>
When the user clicks on the first <li>
then content 1 is shown and the same will happen for the 2nd <li>
with the 2nd content.
Here is my JS:
function showStuff(element) {
var tabContents = document.getElementsByClassName('tabContent');
for (var i = 0; i < tabContents.length; i++) {
tabContents[i].style.display = 'none';
}
var tabContentIdToShow = element.id.replace(/(\d)/g, '-$1');
document.getElementById(tabContentIdToShow).style.display = 'block';
}
$('ul#moodtabs li').click(function() {
$('ul li.current').removeClass('current');
$(this).closest('li').addClass('current');
});
I'm trying to add a class active
to the <li>
tags so I can style them when they are active.
Upvotes: 2
Views: 3705
Reputation: 206669
Your code already works (could be though better written)
But most probably you're missign to wrap your jQuery code in DOM ready:
jQuery(function( $ ){ // DOM ready
$('.tabs').each(function() {
var $tab = $(this).find(".tab");
$tab.on("click", function() {
var tabId = this.id.replace(/\D/g,'');
$tab.not(this).removeClass('current');
$(this).addClass('current');
$(".tabContent").removeClass("current");
$("#tabs-"+tabId).addClass("current");
});
});
});
.mbutton {background:none;}
.mbutton.current{background:red;}
.tabContent {display:none;}
.tabContent.current{display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<ul id="moodtabs" class="side bar tabs">
<li id="tabs1" class="tab mbutton">Cheerful</li>
<li id="tabs2" class="tab mbutton">Romantic</li>
</ul>
<div id="tabs-1" class="tabContent">
<h4>Content 1</h4>
</div>
<div id="tabs-2" class="tabContent">
<h4>Content 222222</h4>
</div>
Upvotes: 3
Reputation: 2007
I think the simplest binding would be
$('ul#moodtabs li').click(function() {
$(this).addClass('current').siblings('li').removeClass('current');
});
You can also drop your javascript function entirely and have this be your full function
$('ul#moodtabs li').click(function() {
var myTab = $(this).index();
$(this).addClass('current').siblings('li').removeClass('current');
$('.tabContent').eq(myTab).css('display','block').siblings('.tabContent').css('display','none');
});
Upvotes: 0