I am trying to add/remove active class in the navbar using a snipped from similar questions, however nothing happens in my case. It´s very possible I am missing out something that could not figured out so far.
Here is my HTML
<div class="collapse navbar-collapse" id="navbarColor01">
<ul class="navbar-nav mr-auto">
<li class="nav-item active" id="dashboard">
<a class="nav-link" href="{% url 'dashboard' %}">Dashboard</a>
</li>
<li class="nav-item" id="painel_regras">
<a class="nav-link" href="{% url 'painel_regras' %}">Todos as Regras</a>
</li>
</ul>
</div>
Here is the Javascript part
<script type="text/javascript">
var navContainer = document.getElementById("navbarColor01");
var navitem = navContainer.getElementsByClassName("nav-item");
for (var i = 0; i < navitem.length; i++) {
navitem[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
</script>
There might be conflicts with other elements that have the active class, so when you access current[0], the item at index 0 is not the one in the navbar. I have replaced document.getElementsByClassName with document.querySelector to make the element more specific.
var navContainer = document.getElementById("navbarColor01");
var navitem = navContainer.getElementsByClassName("nav-item");
for (var i = 0; i < navitem.length; i++) {
navitem[i].addEventListener("click", function() {
var current = document.querySelector("#navbarColor01 .nav-item.active");
current.className = current.className.replace(" active", "");
this.className += " active";
});
}
.active {
font-weight: bold;
}
<div class="collapse navbar-collapse" id="navbarColor01">
<ul class="navbar-nav mr-auto">
<li class="nav-item active" id="dashboard">
<a class="nav-link" href="#">Dashboard</a>
</li>
<li class="nav-item" id="painel_regras">
<a class="nav-link" href="#">Todos as Regras</a>
</li>
</ul>
</div>
Related
There are such buttons in the navbar, how to do this - when a tab is selected for the specified content for this category
// ---------Responsive-navbar-active-animation-----------
function test(){
var tabsNewAnim = $('#navbarSupportedContent');
var selectorNewAnim = $('#navbarSupportedContent').find('li').length;
var activeItemNewAnim = tabsNewAnim.find('.active');
var activeWidthNewAnimHeight = activeItemNewAnim.innerHeight();
var activeWidthNewAnimWidth = activeItemNewAnim.innerWidth();
var itemPosNewAnimTop = activeItemNewAnim.position();
var itemPosNewAnimLeft = activeItemNewAnim.position();
$(".hori-selector").css({
"top":itemPosNewAnimTop.top + "px",
"left":itemPosNewAnimLeft.left + "px",
"height": activeWidthNewAnimHeight + "px",
"width": activeWidthNewAnimWidth + "px"
});
$("#navbarSupportedContent").on("click","li",function(e){
$('#navbarSupportedContent ul li').removeClass("active");
$(this).addClass('active');
var activeWidthNewAnimHeight = $(this).innerHeight();
var activeWidthNewAnimWidth = $(this).innerWidth();
var itemPosNewAnimTop = $(this).position();
var itemPosNewAnimLeft = $(this).position();
$(".hori-selector").css({
"top":itemPosNewAnimTop.top + "px",
"left":itemPosNewAnimLeft.left + "px",
"height": activeWidthNewAnimHeight + "px",
"width": activeWidthNewAnimWidth + "px"
});
});
}
$(document).ready(function(){
setTimeout(function(){ test(); });
});
$(window).on('resize', function(){
setTimeout(function(){ test(); }, 500);
});
$(".navbar-toggler").click(function(){
$(".navbar-collapse").slideToggle(300);
setTimeout(function(){ test(); });
});
// --------------add active class-on another-page move----------
jQuery(document).ready(function($){
// Get current path and find target link
var path = window.location.pathname.split("/").pop();
// Account for home page with empty path
if ( path == '' ) {
path = 'index.html';
}
var target = $('#navbarSupportedContent ul li a[href="'+path+'"]');
// Add active class to target link
target.parent().addClass('active');
});
// Add active class on another page linked
// ==========================================
// $(window).on('load',function () {
// var current = location.pathname;
// console.log(current);
// $('#navbarSupportedContent ul 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.parent().addClass('active');
// $this.parents('.menu-submenu').addClass('show-dropdown');
// $this.parents('.menu-submenu').parent().addClass('active');
// }else{
// $this.parent().removeClass('active');
// }
// })
// });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="navbar navbar-expand-custom navbar-mainbg">
<a class="navbar-brand navbar-logo" href="#">Navbar</a>
<button class="navbar-toggler" type="button" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<i class="fas fa-bars text-white"></i>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<div class="hori-selector">
<div class="left"></div>
<div class="right"></div>
</div>
<li class="nav-item">
<a class="nav-link" href="javascript:void(adress-book.html);"><i class="fas fa-tachometer-alt"></i>Dashboard</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="javascript:void(0);"><i class="far fa-address-book"></i>Address Book</a>
</li>
<li class="nav-item">
<a class="nav-link" href="javascript:void(0);"><i class="far fa-clone"></i>Components</a>
</li>
<li class="nav-item">
<a class="nav-link" href="javascript:void(0);"><i class="far fa-calendar-alt"></i>Calendar</a>
</li>
<li class="nav-item">
<a class="nav-link" href="javascript:void(0);"><i class="far fa-chart-bar"></i>Charts</a>
</li>
<li class="nav-item">
<a class="nav-link" href="javascript:void(0);"><i class="far fa-copy"></i>Documents</a>
</li>
</ul>
</div>
</nav>
please..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................
As far, as I know, in javascript, there is no way to implement html document in your page, by changing the url. It may be done on the server side, but not on front-end.
If you want to display some content based on selected tab, just set "display: block" for selected content when you pressed some tab, and set "display: none" for others.
This is how my code looks like:
<div class="header-nav navbar-collapse collapse ">
<ul id="navigation" class=" nav navbar-nav">
<li>
Home
</li>
<li>
About Us
</li>
</ul>
</div>
I've been trying to add the active class to each of them when the user is on that specific page but no succes so far
Tis is how my script looks like:
var i = 0;
[].forEach.call(document.querySelectorAll('li > a'), function(nav) {
console.log(nav.pathname,window.location.pathname);
if (nav.pathname === window.location.pathname){
i = 1;
console.log(i);
nav.classList.add('active')
}
else{
console.log(i)
nav.classList.removeClass('active')
}
})
The active class is set on the "a" not on "li" and i don't know how to fix this. Maybe someone can help me?
In looking at the classes, it looks like you may be using Bootstrap. I added in those libs to the snippet, and updated some of the classes. I also added in another nav item with the href equal to js since that is the pathname for the snippet window. Otherwise it won't add the active class as there would not be a pathname that would be equal.
I also changed the nav items to pills, so you can see the active link easier.
var i = 0;
document.querySelectorAll('ul.nav > li > a').forEach((nav) => {
console.log({
navPathname: nav.pathname,
windowLocationPathname: window.location.pathname,
areEqual: nav.pathname === window.location.pathname,
});
if (nav.pathname === window.location.pathname) {
nav.classList.add('active')
} else {
nav.classList.remove('active')
}
})
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div class="navbar navbar-light bg-light">
<ul id="navigation" class="nav nav-pills">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="js">JS</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about-us.html">About Us</a>
</li>
</ul>
</div>
To target the parent element, you have a few options - my favorite is element.closest(selector) which takes a starting element and finds the closest containing parent that matches selector
let els = document.querySelectorAll('li > a');
els.forEach(el => {
el.addEventListener('click', e => {
els.forEach(a => a.closest('li').classList.remove('active'));
e.target.closest('li').classList.add('active');
})
})
li.active {
background-color: green;
}
<ul>
<li><a href='#'>link 1</a></li>
<li><a href='#'>link 1</a></li>
<li><a href='#'>link 1</a></li>
</ul>
Thanks for this, i merged the two responses and made it into one that works for me, this is the script that worked without even touching the classes into the nav-bar:
document.querySelectorAll('ul.nav > li > a').forEach((nav) => {
console.log({
navPathname: nav.pathname,
windowLocationPathname: window.location.pathname,
areEqual: nav.pathname === window.location.pathname,
});
if (nav.pathname === window.location.pathname) {
nav.closest('li').classList.add('active')
} else {
nav.closest('li').classList.remove('active')
}
})
I have this one problem regarding the highlighted navbar menu which will only highlight when we clicked on it. For that to work, I'm using javascript. However, each pages has its own sub pages, for example, page Home has a link of local/home, but its content will lead to local/home/content. The sub link will not make the navbar to function The navbar was coded in different file, which I just extends in the home and other pages. I'm not very good at explaining but if I can elaborate more on any part I would do so. Below I attached my JS and my navbar:
Navbar :
<ul class="navbar-nav mr-auto" id="nav">
<li class="nav-item">
<a class="nav-link active" href="{{ url('/') }}">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('courses') }}">opportunities</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('events') }}">events</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('uqalc') }}">courses</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('contact') }}">contact</a>
</li>
</ul>
Javascript :
const currloc = location.href;
const menuItem = document.querySelectorAll('a');
const menuLen = menuItem.length;
for (let i = 0; i < menuLen; i++) {
menuItem[i].classList.remove('active');
if (menuItem[i].href === currloc) {
menuItem[i].className = "nav-link active";
}
}
Here, I add active class to the anchor tag which is inside .navbar-nav If the window location is https://www.google.com/index.html
then this code find an anchor tag which one inside the .navbar-nav if anchor tag href should be index.html then this code add class active to the anchor tag
function removeQueryString(url) {
return url.split('?')[0]
}
[].forEach.call(document.querySelectorAll('.navbar-nav a'), function(elem) {
if (removeQueryString(elem.href) === removeQueryString(window.location.href))
elem.classList.add('active')
else
elem.classList.remove('active')
})
I need to enable and disable tab based select results.Below the code I am working.If device B status is On-Line I need to disable Device-V tab.How to implement this using JavaScript/jQuery.
jQuery:
if(result.includes("On-line") ){
$(selected_device_id).html("");
//Need to implement disable function here
$(selected_device_id).append(result+" ✅");
HTML File:
<div class="panel">
<br>
<ul class="nav nav-pills nav-tabs">
<li class="active">
<a
data-toggle="tab"
href="#Device-B"
onclick="document.getElementById('Object').value = '';
document.getElementById('first_i').value = '';
document.getElementById('second_i').value = '';
document.getElementById('third_i').value = '';">
<i>
<b>Device B</b>
</i>
</a>
</li>
<li>
<a
data-toggle="tab"
href="#Device-V"
onclick="document.getElementById('tr181_object').value = '';
document.getElementById('first_i').value = '';
document.getElementById('second_i').value = '';
document.getElementById('third_i').value = '';">
<i>
<b>Video</b>
</i>
</a>
</li>
</div>
$(document).ready(function()
{
var switch_ch = 0 ;
$(".linktoggle").on("click",function(){
i = $(this).index(".linktoggle") ;
if( $(".linktoggle").attr("href") === "#Device-B")
{
if( switch_ch === 0 )
{
$(".linktoggle:eq(0)").show();
$("li:eq(0)").show();
$(".linktoggle:eq(1)").hide();
$("li:eq(1)").hide();
switch_ch = 1 ;
}
else
{
$(".linktoggle:eq(1)").show();
$("li:eq(1)").show();
switch_ch = 0 ;
}
}
if( $(".linktoggle").attr("href") === "#Device-V")
{
$(".linktoggle:eq("+i +")").hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel">
<br>
<ul class="nav nav-pills nav-tabs">
<li class="active">
<a
class="linktoggle"
href="#Device-B" >
<i>
<b>Device B</b>
</i>
</a>
</li>
<li>
<a
class="linktoggle"
data-toggle="tab"
href="#Device-V"
>
<i>
<b>Video</b>
</i>
</a>
</li>
</div>
I have a menu with a submenu
The html
<ul class="nav navbar-nav float-xs-right top-nav">
<li class="nav-item"><a class="nav-link" href="/our-work/">Our Work</a></li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="/what-we-do/">What We Do</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="/what-we-do/we-develop/">We Develop</a>
<a class="dropdown-item" href="/what-we-do/we-promote/">We Promote</a>
<a class="dropdown-item" href="/what-we-do/we-support/">We Support</a>
</div>
</li>
<li class="nav-item"><a class="nav-link" href="/contact/">Contact</a></li>
</ul>
I am adding bg color using jQuery
function activeMenu() {
var curr_url = window.location.pathname ;
var curr_menu = $("a[href$='" + curr_url + "']");
$(curr_menu).css("background", "#fff");
}
activeMenu();
It is changing bg color of a tag and if it is submenu than the submenu's bg color is changing. But I want to change the bg color of the parent menu not the submenu.
Is there a possible solution to select the parent menu using jQuery?
See this jQuery method: https://api.jquery.com/parent/
In your case, I think this is what you're looking for;
function activeMenu() {
var curr_url = window.location.pathname ;
var curr_menu = $("a[href$='" + curr_url + "']");
$(curr_menu).parent(".dropdown-toggle").css("background", "#fff");
}
activeMenu();
You can do this with vanilla javascript. Let's say your <ul> has an id of "menu":
const menu = document.getElementById("menu").children;
const list = [...menu]
const currentPage = list.filter(li => li.children[0].pathname == window.location.pathname)
currentPage[0].className = "active"