Add Active Class to Menu - javascript

I have a side menu and I want to display the active class when it loads the page.
The obvious answer would be to do this with jquery in every page but it repeats tons of code and it's boring.
So I used this in a app.js globally:
//Active side-menu
$('.nav-item').click(function () {
$(this).addClass('active');
});
But this doesn't work because it puts active and when it loads the page this class is removed after loading the html
What can I do?
<ul class="nav">
<li class="nav-item">
<a class="nav-link" href="general-setup" onclick="gitLabFetch()" id="createEnviromentTab">
<img src="../resources/img/icons/create-icon.png" alt="" class="menuIcon">
<span class="menu-title">Create Environment</span>
</a>
</li>
//A lot of li elements
<ul>

I think that on page load, you should get the url, try to find it on the menu with javascript and then add the active class to the nav-item, something like this:
$(document).ready(function() {
var url = window.location.pathname + window.location.search;
$('ul.nav a.nav-link[href="' + url + '"]').parent().addClass('active');
});
A little example, you might need to tweak the url part:
$(document).ready(function() {
var url = 'general-setup';//window.location.pathname + window.location.search;
$('ul.nav a.nav-link[href="' + url + '"]').parent().addClass('active');
});
.active {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav">
<li class="nav-item">
<a class="nav-link" href="general-setup" onclick="gitLabFetch()" id="createEnviromentTab">
<img src="../resources/img/icons/create-icon.png" alt="" class="menuIcon">
<span class="menu-title">Create Environment</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="general-setup2" onclick="gitLabFetch()" id="createEnviromentTab">
<img src="../resources/img/icons/create-icon.png" alt="" class="menuIcon">
<span class="menu-title">Create Environment</span>
</a>
</li>
//A lot of li elements
<ul>

Ok, so after further thought i have come up with a solution.
An approach i would take is to add a data attribute to anchor onto, this gives you the freedom to define routes that your list items link to and style them accordingly based on route...
(() => {
$('li')
.filter((i, li) => $(li).data('route') === window.location.pathname)
.addClass('active')
})()
<li data-route="/">HOME</li>
<li data-route="/friends">Friends</li>
<li data-route="/profile">Profile</li>
<li data-route="/blog">Blog</li>
As you can see, i run over all the list-items and filter out all the items that do not have data-route attributes that match the window.location.pathname, after i am left with the filtered list, i apply an active class to the matched items.

Related

Select an element if the href value is a specific word

Hi and thanks in advance for your help!
I have previously used JS to add an active class to an element if the corresponding URL shows.
I am trying to take what I have done in the past and edit it.
I am trying to add an active class to an element if the href attribute equals '#tab1' for example. Rather than if the URL matches.
Please see the existing JS below that I am trying to work from, I have tried a few things including a getelementbyID rather than selecting the href but I'm lost.
$(document).ready(function () {
const $links = $('.hs-mega-menu ul li a');
$.each($links, function (index, link) {
if (link.href == (document.URL)) {
$(this).addClass('active');
}
});
});
An example of one of the nav-links I am trying to select and apply the active class too are below:
<li class="nav-item"> <a class="nav-link g-py-10--md g-px-15--md" href="#tab1" role="tab" data-toggle="tab">Printed Stationery<i class="g-ml-10 fa-solid fa-caret-down d-sm-none"></i></a> </li>
There are a few ways to do this, you can use a function like you have or you can filter or just use a selector for the attribute. Here are examples of the latter two.
$(function() {
let testurl = "#tab1";
const $links = $('.hs-mega-menu ul li a');
$links.filter(function(index, link) {
return $(this).attr('href') == testurl;
}).addClass("active");
$links.filter("[href='" + testurl + "']").addClass("active-test")
});
.active {
color: green;
}
.active-test {
background-color: #ffddff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hs-mega-menu">
<ul>
<li class="nav-item"> <a class="nav-link g-py-10--md g-px-15--md" href="#tab1" role="tab" data-toggle="tab">Printed Stationery<i class="g-ml-10 fa-solid fa-caret-down d-sm-none"></i></a> </li>
<li class="nav-item"> <a class="nav-link g-py-10--md g-px-15--md" href="#tab1" role="tab" data-toggle="tab">Printed Stationery<i class="g-ml-10 fa-solid fa-caret-down d-sm-none"></i></a> </li>
<li class="nav-item"> <a class="nav-link g-py-10--md g-px-15--md" href="#tab2" role="tab" data-toggle="tab">Printed Stationery<i class="g-ml-10 fa-solid fa-caret-down d-sm-none"></i></a> </li>
</ul>
</div>

jQuery adding active class to navbar doesnt work

So instead of adding an active class to the navbar using HTML I instead wanted to add it through jQuery but my code doesn't seem to work.
$('.navbar-nav li a[href="' + location.pathname + '"]').addClass('active');
<nav>
<ul class="navbar-nav">
<li class="nav-item" >
<a class="nav-link active" href="">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Wat is het?</a>
</li>
</ul>
</nav>
Can anybody help me out?
I think what do you need is window.location.href.
Something like this:
var pathname = window.location.href;
$('.navbar-nav li a').attr('href',pathname).addClass('active');
Check this example: https://jsfiddle.net/tbx56gtL/7/
Maybe you can do it like this:
$(function() {
var currentLoc = window.location.href;
if(/PageYouWant/.test(currentLoc) {
$('.navbar-nav li a').addClass('active');
}
});
If you want to set active in anchor tag you can do one of the following options.
Asign ids to every a tag
Asign a data attrib and add a class toggleClassX
Use $(this).addClass("active")
The following are the examples of each recomendation :
1 html:
<nav>
<ul class="navbar-nav">
<li class="nav-item" >
<a class="nav-link active" id="myId1" href="">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" id="myId2" href="">Wat is het?</a>
</li>
</ul>
</nav>
2 html:
<nav>
<ul class="navbar-nav">
<li class="nav-item" >
<a class="nav-link toggleClass1 active" data-tclass="1" href="">Home</a>
</li>
<li class="nav-item">
<a class="nav-link toggleClass2" data-tclass="2" href="">Wat is het?</a>
</li>
</ul>
</nav>
3 html: your structure is ok for the last example
1 js:
$("element").click(function(){
$("#myId1").addClass("active")
});
2 js:
$(".nav-link").click(function(){
var tclass = $(this).data("tclass)
$(".toggleClass"+tclass).addClass("active")
});
3 js:
$(".nav-link").click(function(){
$(this).addClass("active")
});
Hope the above answer your question.

Javascript code for Bootstrap Sidebar menu not working

I have a Sidebar / Menu that I am working with. It has been created with Bootstrap, DJango, and Javascript.
Basically, I am trying to write Javascript so that when on clicks on a menu-item, the background changes color (dark blue), the icon change color (light green / turquoise) and it gets a type of "wedge"
Below is an example of a menu-item that has been chosen (Dashboard) along with menu-items that have not been chosen (Security and Messages). The "wedge" has a red arrow pointing to it.
Here is the HTML code that is being used:
[... snip ...]
<div class="page-container">
<div class="page-sidebar-wrapper">
<div class="page-sidebar navbar-collapse collapse">
<ul class="page-sidebar-menu page-header-fixed page-sidebar-menu-hover-submenu "
data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200">
<li class="nav-item start active open">
<a href="{% url 'mainadmin:dashboard' %}" class="nav-link nav-toggle">
<i class="fa fa-tachometer"></i>
<span class="title">Dashboard</span>
<span class="selected"></span>
<span class="arrow open"></span>
</a>
</li>
<li class="nav-item ">
<a href="{% url 'mainadmin:security' %}" class="nav-link nav-toggle">
<i class="fa fa-users"></i>
<span class="title">Security</span>
<span class="arrow"></span>
</a>
</li>
<li class="nav-item ">
<a href="{% url 'mainadmin:in_progress' %}" class="nav-link nav-toggle">
<i class="fa fa-comment"></i>
<span class="title">Messages</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="{% url 'mainadmin:in_progress' %}" class="nav-link ">
<span class="title">List All Messages</span>
</a>
</li>
<li class="nav-item ">
<a href="{% url 'mainadmin:in_progress' %}" class="nav-link ">
<span class="title">List My Messages</span>
<span class="badge badge-danger"></span>
</a>
</li>
</ul>
</li>
[... snip ...]
Here is the Javascript code:
<script>
$(document).ready(function () {
$('.nav-item a').click(function(e) {
$('.nav-item a').removeClass('selected');
$('.nav-item a').removeClass('arrow');
$('.nav-item a').removeClass('open');
$('.nav-item a').removeClass('active');
alert("I have gotten in");
var $parent = $(this).parent();
$parent.addClass('selected');
$parent.addClass('arrow');
$parent.addClass('open');
$parent.addClass('active');
e.preventDefault();
});
});
</script>
I do get the alert message - but - what happens is :
-> the background of the chosen menu-item does change color - which is correct
--> The icon of the chosen menu-item changes color (to light blue / turquoise) - which is correct
-> the tick of the arrow does not take place for the chosen menu-item :(
-> the old chosen menu item does not "de-select"
What am I doing wrong?
TIA
Hi #Joe Lissner
Thanks so much for the response!
I had to add the following to get the "wedge" portion to work. It required span tags
// REFERENCE: https://stackoverflow.com/questions/2013710/add-span-tag-within-anchor-in-jquery
$(this).append('<span class="selected"></span>');
$(this).append('<span class="arrow open"></span>');
While this works when clicking on the main-menu item, I'm not so lucky when it comes to clicking on sub-menu items. As of now, I am pretty much new to Javascript.
How would one get the sub-menu items to work?
Also, when clicking on an item, it does not go to the page specified in "href="
How would can one make changes to the code so that when the menu-item is clicked, it would go to the page specified in "href="
Again, thanks for the response :-)
You are removing the classes from the a tags, not the .nav-item elements.
Try this:
$(document).ready(function () {
$('.nav-item a').click(function(e) {
e.preventDefault(); // best practice to have this first, if you remove this line then the link will function as expected.
var $parent = $(this).parent();
var $arrow = $parent.find('.arrow');
$('.nav-item').removeClass('selected arrow open active'); // simplified
$('.nav-item .arrow').removeClass('open');
$('.nav-item .selected').detach(); // remove the span that was there before
alert("I have gotten in");
$parent.addClass('open active'); // simplified
$arrow.addClass('open').before('<span class="selected" />')
});
});
Edit - Fixed the issue with the arrow

Why does this work? window.location.href

Example link: http://localhost/test/page.php?success
I'm curious about this. And I'm also new to JavaScript so it's not really a surprise but I understand the code below, I just do not know why it works away with what I seem to understand. See this question for more reference.
I have this JavaScript:
<script type="text/javascript">
jQuery(function($) {
var path = window.location.href.split( '?' )[0];
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('sub-menu active');
$(this).parent().closest("li").addClass('active');
$(this).parent().parent().closest("li").addClass('active');
}
});
});
</script>
The Sidebar:
<li class="sub-menu"> // Sidebar with no submenu
<a class="" href="page1.php">
<i class="icon-calendar"></i>
<span>This is page 1</span>
</a>
</li>
<li class="sub-menu"> // Sidebar with a submenu
<a href="javascript:;" class="">
<i class="icon-group"></i>
<span>This has sub pages</span>
<span class="arrow"></span>
</a>
<ul class="sub">
<li><a class="" href="page2.php">This is page 2</a></li>
<li><a class="" href="page3.php">This is page 3</a></li>
</ul>
</li>
The code puts an active class to the menu on the sidebar which href is equals to the current url. But window.location.href returns the whole url but what is inside the href's are just the page.php. So why does this.href === path work? When window.location.href.split( '?' )[0] returns http://localhost/test/page.php and the href is just page.php.
The href property of an anchor is normalized to an absolute value.
See this example:
HTML:
Test
JS:
var a = document.querySelector('a');
console.log(a.href);
In this instance the relative URL is being resolved to the location of the document containing the a element. You can use the base element to control the resolution of relative URLs.

if else statement - based on iFrame content?

I have a label in navigational breadcrumb:
<li>Eligibility</li>
Please keep in mind, i am very new learning .NET.
On this page there is iFrame content, where you click a link to view the respective content:
<ul id="ss-categories" >
<li class="eligibility">
<a href="#" onclick="ChangeFrame('mem_eligibility.aspx');")>Eligibility</a href>
</li>
<li class="deductible">
<a href="#" onclick="ChangeFrame('mem_deductible.aspx');")>Deductible</a href>
</li>
<li class="claims"><a href="#" onclick="ChangeFrame('mem_claims.aspx');")>Claims & EOBs</a href>
</li>
<li class="benefits">
<a href="#" onclick="ChangeFrame('mem_benefits.aspx');")>Benefits</a href>
</li>
<li class="hospital">
<a href="#" onclick="ChangeFrame('mem_priorAuth.aspx');")>Hospital Admissions</a href>
</li>
<li class="priorauth">
<a href="#" onclick="ChangeFrame('mem_Inpatient.aspx');")>Prior Authorizations</a href>
</li>
And the iFrame displays the content based on the link you click:
<iframe id="ctl00_middleContent_frame1" style="float:left" scrolling="auto" frameborder="0" height="400" width="100%" src="mem_eligibility.aspx">
In that navigational breakcrumb at the top, how would i code it so that it will change, based on the section of content displayed in the iFrame.
i.e. (in lehmans terms)
if iFrame src="mem_elibigility.aspx" {
document.write = 'Eligibility'
}
if iFrame src="mem_deductible.asps" {
document.write = 'Deductible'
}
Hope that makes sense, and yes i know my code is complete garbage... and is not structured right, but thats not my job at the moment...
Updated Version:
The following stores the urls that control your iFrame as title attributes and it uses jQuery to set the title of your "header" area. I tried to clean up a bit of the code as well, but this should work for exactly what you need:
jQuery (Example):
$(document).ready(function(){
$('#ss-categories li').click(function()
{
var test = $(this).text();
$("#title").text(test);
//Code to change iframe based on property of the item clicked goes here
var title = $(this).attr("title");
$('#ctl00_middleContent_frame1').attr('src', title);
});
});
HTML (Example):
<ul id="ss-categories" >
<li class="eligibility" title="mem_eligibility.aspx">
Eligibility
</li>
<li class="deductible" title="mem_deductible.aspx">
Deductible
</li>
<li class="claims" title="mem_claims.aspx">
Claims & EOBs
</li>
<li class="benefits" title="mem_benefits.aspx">
Benefits
</li>
<li class="hospital" title="mem_priorAuth.aspx">
Hospital Admissions
</li>
<li class="priorauth" title="mem_Inpatient.aspx">
Prior Authorizations
</li>
<li id="title" style="font-size: x-large; font-weight: bold">Eligibility</li>
<iframe id="ctl00_middleContent_frame1" style="float:left" scrolling="auto" frameborder="0" height="400" width="100%" src="http://www.google.com">
Try this demo to see if that is the functionality you want : Updated Demo
Older answer:
Is something like this demo what you are looking for?
Code:
$(document).ready(function(){
$('#ss-categories li').click(function()
{
var test = $(this).text();
$("#title").text(test);
//Insert logic here to change iFrame based on clicked item
});
});
It creates a function that will grab the "name" of one of your links in the list and it will display that in your "title" area. If I understood you correctly - I think this will do what you need.

Categories

Resources