Navigation Javascript removing the class - javascript

I use navigation from bootstrap and a little PHP to make it modular. I used jQuery to add an "active" CSS class on the client-side.
I want to add active class to "The Plan" "Nominees" "News" "FAQs" and "Contact" when they are active and don't do anything on "Vote Now" and "The Homepage".
jQuery(document).ready(function($){
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,''));
$('#menu_list li a').each(function(){
if(urlRegExp.test(this.href)){
$(this).addClass('active');
}
// I added this for removing the active class from all the nav items on home page (which is the logo)
else if (url == ''){
$('#menu_list li a').removeClass('active');
}
});
})
And here is my header.php
<header>
<nav class="navbar navbar-toggleable-md fixed-top navbar-light bg-faded">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav" id="menu_list">
<li><a class="nav-item nav-link" href="the_plan.php">The Plan</a></li>
<li><a class="nav-item nav-link" href="nominees.php">Nominees</a></li>
<li><a class="nav-item nav-link" href="news.php">News</a></li>
<li class="logo_container">
<a class="navbar-brand" href="/"><img src="assets/images/point_north_logo.png"><span class="sr-only">(current)</span></a>
</li>
<li><a class="nav-item nav-link" href="faqs.php">FAQs</a></li>
<li><a class="nav-item nav-link" href="contact.php">Contact</a></li>
<li><button class="btn_vote">Vote Now!</button></li>
</div>
</div>
</nav>
</header>
The issue is when I'm on the Home page, this code adds active to all the links. What I'm trying to achieve is when I'm Home Page, I don't want to add any classes to other links. The code I found is looking for href to highlight I believe, and if it can't find it. It highlights all of them with adding active class to all.
I don't have JSfiddle for this because since script looking for hyperlinks with a clear destination. fiddle didn't work for some reason. If somebody can help me with this that would be great, however, if you need a staging I can try to set something up.

Related

How to add and remove the active class on the various sections of my HTML nav bar using JavaScript?

I have a nav bar that has four different section names of the webpage. When I click on one of the section names, I want it to be active (highlighted) and I want the previous active section name to no longer be active. I have been trying many different JavaScript functions and code, but have not been able to succeed. If anyone can look at my code and let me know what I am missing or doing wrong, that would be amazing. Please let me know if you have any questions with my code or problem, I will be happy to answer. Thank you.
HTML Code (navbar.html):
<nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top" id="sideNav">
<a class="navbar-brand js-scroll-trigger" href="#about">
<span class="d-block d-lg-none">Joseph Smith</span>
<span class="d-none d-lg-block"><img class="img-fluid img-profile rounded-circle mx-auto mb-2" src="{% static 'img/joseph_headshot.jpg' %}"alt="..." /></span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav">
<li class="nav-item"><a class="nav-link js-scroll-trigger active" href="#about">About</a></li>
<li class="nav-item"><a class="nav-link js-scroll-trigger" href="#education">Education</a></li>
<li class="nav-item"><a class="nav-link js-scroll-trigger" href="#experience">Experience</a></li>
<li class="nav-item"><a class="nav-link js-scroll-trigger" href="#skills">Skills</a></li>
</ul>
</div>
</nav>
JavaScript Code (script.js):
responsiveNavItems.map(function (responsiveNavItem) {
responsiveNavItem.addEventListener('click', () => {
const curr_active = document.getElementsByClassName("navbar-nav").getElementsByTagName('li').getElementsByClassName(".active");
curr_active[0].className = curr_active[0].className.replace(" active", "");
responsiveNavItem.className += " active";
}
});
});
I think the main problem may be the period before "active" when looking for elements with that class name.
Try this...
responsiveNavItems.map(function (responsiveNavItem) {
responsiveNavItem.addEventListener('click', nav_link_click);
});
function nav_link_click() {
const curr_active = document.getElementsByClassName('navbar-nav').getElementsByTagName('li').getElementsByClassName('active');
curr_active[0].classList.remove('active');
this.classList.add('active');
}
You can use querySelector(). It allows you to find the first element that matches one or more CSS selectors. You can call the querySelector() method on the document or any HTML element.
function myFunction(e) {
var elements = document.querySelector(".active");
if(elements !==null){
elements.classList.remove("active");
}
e.target.className = "active";
}

Updating Active Class on Navbar using MDBootstrap and nav.php

I am trying to update the active class on my navbar using MDBootstrap by checking the current href so that it signifies which page the user is currently on. I can successfully set the class to active in an individual list item in the code below, but it will not update when I choose another navbar option on the browser. I have tried all snippets of js code found on Stackoverflow to no avail. For context, all of my navbar code is in one file, nav.php, and is being loaded into all other files.
How I'm loading the navbar into each php file which works perfectly:
<div id="nav-placeholder">
</div>
<script>
$(function(){
$("#nav-placeholder").load("nav.php");
});
</script>
UPDATE: I am no longer loading nav.php using the code above, I am simply using <?php include_once "nav.php";?> at the top of each PHP file.
nav.php:
<!-- header.php includes all the relevant CDN links for MDBootStrap 4.19.1 -->
<?php include_once "header.php";?>
<!DOCTYPE html>
<html lang="en">
<nav class="mb-1 navbar navbar-expand-lg navbar-dark default-color" id="nav-placeholder">
<a class="navbar-brand" href="#"></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent-333"
aria-controls="navbarSupportedContent-333" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent-333">
<ul class="navbar-nav mr-auto" id="nav">
<li class="nav-item">
<a class="nav-link" href="/index.php">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/about.php">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/apply.php">Apply Now</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/contact.php">Contact Us</a>
</li>
</ul>
</div>
</nav>
<!-- Make sure that upon execution of the js, 'active' isn't being nullified -->
<script>
$(function(){
var current = location.pathname;
$('#nav li').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');
}
})
})
</script>
</html>
I would appreciate any help you may have to offer, I am sure I am overlooking something or am unaware of some critical knowledge. Thank you!

Jquery function to set active nav tab using url is selecting more than it should

I have a Jquery function which I use to set the 'active' class on my nav anchors, it uses the URL to do so. The function works for the most part but the problem is that when tab 1 is active it's also setting tabs 10, 11 and 12 as active too.
The code below is what I'm using and it's correctly outputting the page in the console.log, it also works as it should for all other links except Item 1 as seen in the screenshot.
$(function(){
var url = window.location.href;
var page = url.substr(url.lastIndexOf('/')+1 );
$('.nav-item a[href*="'+page+'"]').addClass('active');
console.log(page);
});
The nav is fairly large so I'll share a condensed version, just keep in mind that middle ul actually contains a total of 12 Items and each item shares the url
article.php?contentID=
After the = comes the item number from 1 to 12.
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<ul class="navbar-nav" >
<li><a class="navbar-brand" href="articles.php">Twist</a></li>
</ul>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link " href="article.php?contentID=1">Item 1</a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="commentary.php">Commentary</a>
</li>
<li>
<a id="logLink" class="nav-link" href="logout.php">Log out</a>
</li>
</ul>
</div>
</nav>
Any help would be appreciated and I'm pretty sure it's something obvious but I'm just not seeing it.
Thanks in advance.
Twist
You are using the 'attribute contains' selector which selects any that have the given sub-string "article.php?contentID=1".
So this matches all of the following
"article.php?contentID=1",
"article.php?contentID=10",
"article.php?contentID=11",
"article.php?contentID=12", and
"some_article.php?contentID=1whatever"
Just remove the *
'.nav-item a[href="'+page+'"]'
Interesting question... The key was to have href$="='+page+'" so that the statement which adds the active class becomes:
$('.nav-item a[href$="=' + page + '"]').addClass('active');
Working snippet below - change the hardcoded value of page to test yourself:
$(function() {
var url = window.location.href;
var page = 1 //url.substr(url.lastIndexOf('/')+1 );
$('.nav-item a[href$="=' + page + '"]').addClass('active');
console.log('looking for page#:', page);
});
a.nav-link.active {
background: lightgreen;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="container">
<h2>Nav</h2>
<p>Basic horizontal menu:</p>
<ul class="nav">
<li class="nav-item">
<a class="nav-link" href="#article.php?contentID=1">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#article.php?contentID=2">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#article.php?contentID=10">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#article.php?contentID=11">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#article.php?contentID=21">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
</div>

Bootstrap Navbar Active State Switching Bootstrap (Javascript Related)

I use the class="active" on my navbar navigation items with the most current version of bootstrap (4) and it does not switch when I click on the links. I found similar questions to this and tried to make the javascript fit my own code, but it didn't work. Note: These links on my navbar are all on the same page. The goal is to make the clicked on nav-item link active so that the user knows what they're currently viewing on the page.
Here is what my javascript code looks like:
$(".nav .nav-link").on("click", function(){
$(".nav").find(".active").removeClass("active");
$(this).addClass("active");
});
Here is what my html navbar code looks like:
<header>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<img class="logo" src="images/logo.png" width="55px" align="left">
<a class="navbar-brand" href="index.html">ROWAN AEΠ</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<!--Div for Alignment Purposes Below -->
<div class="navig-align">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link active" href="#HOME">HOME</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#ABOUT">ABOUT</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">BOARD</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">RECRUITMENT</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">FAQ</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">CONTACT</a>
</li>
<li class="nav-item">
<a id="donatebutton" class="nav-link" href="http://www.example.org" target="_blank">DONATE
<img class="donateimg" src="images/externallink.png" alt=""></a>
</li>
</ul>
</div>
</div>
</nav>
</header>
If someone can look at my html and figure out a solution to for the script, I will be very grateful.
You dont appear to have an ancestor to the nav list with the class of "nav" - also the nav-link li's are what should get the 'active' class - not the 'a' within it.
Also - you can target the active item directly to remove the active class - whether its the li or the a.
if you want to keep the active class on the a - then just change the click handler
$(".nav-link").on("click", function(){
$(".nav-link.active").removeClass("active");
$(this).addClass("active");
});
If you want the active class on the li - then
if you want to keep the active class on the a - then just change the click handler
$(".nav-item").on("click", function(){
$(".nav-item.active).removeClass("active");
$(this).addClass("active");
});
You do not have a class .nav which you are referencing in your jQuery selector.
Update your jQuery too:
$(".nav-link").on("click", function(){
$(".nav-link.active").removeClass("active");
$(this).addClass("active");
});
Link to example: https://jsfiddle.net/Lb3u9c5d/

Navbar fade and show at the same time

Currently I am building a navigation bar using Bootstrap v4 and I found out that the animation during collapsing in responsive view is not right.
Hence, I inspect the specific navigation bar and I found out that the classes (.in and .show) are in the same elements when I toggle the collapsible content.
Is there any solution on it through JavaScript or by overriding CSS?
For your information, here are the inspection of my navigation bar.
https://i.imgur.com/f4R48gv.jpg
TQ.
EDIT :
<nav class="navbar navbar-expand-sm navbar-dark bg-dark top-nav">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#mainmenu" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse" id="mainmenu">
<ul class="navbar-nav mr-auto">
<li class="nav-item px-3"><a class="nav-link" href="#">ITEM 1</a></li>
<li class="nav-item px-3"><a class="nav-link" href="#">ITEM 2</a></li>
<li class="nav-item px-3"><a class="nav-link" href="#">ITEM 3</a></li>
</ul>
<div class="navbar-nav">
<a class="nav-item nav-link px-3" href="#">SIGN IN</a>
<div class="divider"></div>
<a class="nav-item nav-link px-3" href="#">SIGN UP</a>
</div>
</div>
</nav>
Here are the jsfiddle link to the file.
https://jsfiddle.net/Jeffrey_Teoh/4y6n6xt4/11/
you are including bootstrap version 3 on top of your file and bootstrap version 4 at the end of your file... same with jQuery. Scripts should be added only once.

Categories