I recently created a navbar using Bootstrap 4 and I'm looking for a more efficient way to toggle the active icon on the current page. Here's my current setup:
<li class="nav-item"><a href="/" id="A"
{% if request.path == "/" %}
class="nav-link active"
{% else %}
class="nav-link"
{% endif %}>Home</a></li>
<li class="nav-item"><a href="/blog" id="B"
{% if request.path == "/blog/" %}
class="nav-link active" {% else %}
class="nav-link"
{% endif %}>Blog</a></li>
Instead of this lengthy code, I would like a simpler solution that can activate a script based on URL names. Here's what I have in mind:
{% if request.path == '/' %}
<script>
document.getElementById("#A").classList.add('active');
if ( document.getElementById("#A").classList.contains('active') )
document.getElementById("#A").classList.toggle('active');
</script>
{% elif request.path == '/blog/' %}
<script>
document.getElementById("#B").classList.add('active');
if ( document.getElementById("#B").classList.contains('active') )
document.getElementById("#B").classList.toggle('active');
</script>
{% endif %}
Is there a better and easier approach to achieve this? I welcome any suggestions on how to highlight the active page icon on the navbar with toggling styles. Thank you.