Reputation: 1038
I need to highlight menu button when selecting menu item. if i select menu item then need to apply current class to (li
).
This is what i have tried.
Here is HTML,
<ul>
<li class="current"><a href="#">HOME</a></li>
<li><a href="#">SERVICE</a></li>
<li><a href="#">ABOUTUS</a></li>
<li><a href="#">PROFILE</a></li>
<li><a href="#">CONTACTUS</a></li>
</ul>
Here is Jquery,
var opener = {
init:function() {
this.menuselection();
},
menuselection:function(){
$('ul li a').on('click', function (){
$('ul li').addClass('current');
});
}
}
opener.init();
Here is CSS,
.current a {
color: #03c9a9;
}
a,
a:active,
a:focus {
color: #fff;
}
a,
a:hover,
a:active,
a:focus {
outline: 0;
border: 0;
text-decoration: none;
color: #fff;
}
Upvotes: 5
Views: 197
Reputation: 3830
Make few changes in your script, remove class current from all other li
tags
and on click of a
element add the current class to the closest li
.
var opener = {
init:function() {
this.menuselection();
},
menuselection:function(){
$('ul li a').on('mouseup', function (){
$("li.current").removeClass("current");
$(this).closest("li").addClass('current');
});
}
}
opener.init();
And from your CSS, remove the color from your a tags.
CSS:
.current a {
color: #03c9a9;
}
a,
a:hover,
a:active,
a:focus {
outline: 0;
border: 0;
text-decoration: none;
}
.li-logo {
text-align: left;
}
Upvotes: 1
Reputation: 13474
You can use this
.
$('ul li a').on('click', function (){
$(this).addClass('current');
});
Update
To remove all other current class if applied from other li tags
$('ul li a').on('click', function (){
$('ul li').removeClass('current');
$(this).addClass('current');
}
Upvotes: 1
Reputation: 30557
Use $(this)
to get the current element and closest('li')
to get the li
var opener = {
init:function() {
this.menuselection();
},
menuselection:function(){
$('ul li a').on('click', function (){
$(this).closest('li').addClass('current');
});
}
}
Otherwise, $('ul li')
will add the class to all li
elements
Update
if i select $('ul li') , then apply current class then i need to remove all other current class if applied from other li tags.
Before adding the class to $(this).closest('li')
, do
$('ul li').removeClass('current');
Upvotes: 2
Reputation: 41
Use this, small correction in prev comment
$('ul li a').on('click', function (){
$('ul li a').removeClass('current');
$(this).addClass('current');
});
Upvotes: 4
Reputation: 2309
Fiddle: http://jsfiddle.net/9bzc9j2q/3/
You need to remove 'current' class from all li's and add the class only to the parent of the clicked item.
$('ul li a').on('click', function (){
$('ul li').removeClass('current');
$(this).parent().addClass('current');
});
Upvotes: 1