I am new to JQuery and am trying to add an 'active' tag to a bootstrap class. Can anyone let me know if there is something wrong with my syntax in my .js file.
Here is my base.js file:
$(document).ready(function(){
$("#navlinks li a").on(click, function(){
$(this).addClass('active').siblings().removeClass('active');
})
});
Here is the html page I am using (using django):
<div class="collapse navbar-collapse">
<ul class="navbar-nav mr-auto" id="navlinks">
<li class="nav-item">
<a class="nav-link" href="{% url 'home' %}"><i class="fas fa-home"></i> Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'contact'%}"><i class="far fa-envelope"></i> Contact</a>
</li>
</ul>
Just incase I am not ordering my .js files correctly, here is the bottom of my html page:
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<!-- Custom JS would follow Bootstrap -->
<script type="text/javascript" src="{% static 'js/base.js' %}"></script>
UPDATE:
Making some progress here:
$(function(){
$('#navlinks li a').each(function(){
var $this = $(this);
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
});
So this does the trick when I click the home link, ie, the Contact link appears 'active' and the Home link remains 'disabled.' However, when I click the Home link, both links appear in an 'active' state.
I tried to remedy the situation with this:
$(function(){
var current = location.pathname;
$('#navlinks li a').each(function(){
var $this = $(this);
if($this.hasClass("active")){
$this.removeClass('active');
}
})
$('#navlinks li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
});
Any idea why this wouldn't help me with my new situation? We're getting there, thanks everyone!