Reputation: 778
I thought I did everything right but my code doesn't work. I intend to change the background for the selected tab. Here's my trial.
<script>
$('#navigation li').click(function() {
$('#navigation li').removeClass('active');
$(this).addClass('active');
});
</script>
The html is here
<ul class="navbar-nav ml-auto" id="navigation">
<li class="nav-item active">
<a class="nav-link " href="{% url 'home' %}" id="nav">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'view' %}" id="nav">Work</a>
</li>
</ul>
the active class
<style>
.active{background-color:black}
</style>
I've tried making comparisons to available examples here on stackoverflow but not working for me.
Upvotes: 0
Views: 26
Reputation: 71
I managed to accomplish your goal with the following code:
<!DOCTYPE html>
<head>
<style>
.active{background-color:black}
</style>
</head>
<body>
<ul class="navbar-nav ml-auto" id="navigation">
<li onclick="changeBackground(this.id)" class="nav-item" id="home">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li onclick="changeBackground(this.id)" id="work" class="nav-item">
<a class="nav-link" href="#" id="work">Work</a>
</li>
</ul>
<script>
function changeBackground(id) {
// First remove all "active classes"
let otherElements = document.getElementsByClassName("nav-item")
for (index=0; index < otherElements.length; index++) {
otherElements[index].classList.remove("active")
}
// Then add the class to the just clicked element
let clickedNavItem = document.getElementById(id)
clickedNavItem.classList.add("active")
}
</script>
</body>
</html>
Upvotes: 1