$('.active').click(function() {
$(this).toggleClass('active');
$(this).toggleClass('active');
});
I know this is totally wrong but I'm new and trying to learn; What I'm trying to do is toggle the active class for the <li>
onclick()
really appreciate any help. Thankyou.
<ul class="nav nav-tabs">
<li role="presentation" onclick="toggleClass();">Hi</li>
</ul>
I think instead of $('.active').click(function())
, you should target li
click as
$( "li" ).click(function() {
$(this).toggleClass("active");
});
fiddle: http://jsfiddle.net/wVVbT/142/
Here is a link for description about how to use .toggleClass .
toggleClass: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
$('li').click(function() { $(this).toggleClass('active'); })
ul li{ float: left; margin-right: 20px; } .active { background: #69a; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li> Link A</li> <li>Link B</li> </ul>
You need to create a function toggleClass
JS
Create a new function toggleClass which will accept the current clicked element
function toggleClass(elem) {
$(elem).toggleClass('active');
};
HTML
add toggleClass
function to onclick
handler & pass the current element as an argument
<li role="presentation" onclick="toggleClass(this);">Hi</li>
CSS
Create a class .active
.active {
background: yellow;
}
What you need to do is set all other elements's classes to inactive,
$('.active').className = 'inactive';
$(this).className = 'active';
That top expression will affect all elements with the class and the bottom one will change the current clicked element.
try this:
$("nav li").click(function() {
$(this).toggleClass("active");
});
if only for <li>
elements with active
class
$("nav li.active").click(function() {
$(this).toggleClass("active");
});
This is not how Bootstrap is supposed to work. If you are using bootstrap, use their tab js component. more on it here
Basically you add a listener on those LI tags like this: (from the docs)
$('.nav.nav-tabs li').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
The way you did, you were toggling the state twice so in the end it would stay the same.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.