Reputation: 3809
adding active class to parent list when link is clicked/active , am trying to inject that using JavaScript
as follow:
$(document).ready(
function()
{
//injecting active status to the navigation bar lists
var element = document.getElementById("navbar-ul");
var links = element.getElementsByTagName("a");
for(var i = 0; i < links.length ; i++) {
links[i].onclick(function () {
links[i].parent().addClass('active');
});
}
}
);
but am getting the following error:
TypeError: links[i].onclick is not a function
how I supposed to achieve that?
Upvotes: 0
Views: 114
Reputation: 101
You would be better of with adding a class to the tags who needs an eventListener. (with jquery)
$(document).ready(function() {
$("#navbar-ul a").on("click", function() {
var active = document.querySelector('#navbar-ul .active');
if(active){
$("#navbar-ul a").removeClass('active');
}
$(this).addClass("active");
});
);
Upvotes: 0
Reputation: 12923
This is very simply with jQuery:
$("#navbar-ul a").click(function(){
$(this).parent().addClass("active");
});
I'm guessing you're trying to add an active state to the link thats being clicked on and remove the others? If so you can use .siblings()
to find the other links and remove their class:
$("#navbar-ul a").click(function(){
$(this).closest("li").addClass("active").siblings("li").removeClass("active");
});
Upvotes: 0
Reputation: 16989
A more verbose JQuery way to approach this
$('#navbar-ul a').each(function() {
$(this).on('click', function() {
$(this).parent().addClass('active');
});
});
Upvotes: 3