Add active class after page loading - javascript

I am trying to add an active class after page load. Here is my script. This script is working when I click. But when the page is loaded, the active class disappear.
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<li class="nav-item">
<a class="nav-link" href="{{url('/account')}}" target="_blank">
<i class="fas fa-fw fa-tachometer-alt"> account</i>
</li>
</ul>
$(document).ready(function(){
$(".nav-item a").on("click", function(){ $(".nav-item").find(".active").removeClass("active"); $(this).parent().addClass("active");});
});
I am trying to work with localStorage function not succeed .please suggest me what I have to do.

You can clean up your code in many ways:
use toggleClass instead of add/remove class
use .nav-link rather than .nav-item a for one, a will be any anchor element, not just the first child (you'd do better to do .nav-item > a), but that has a distinctive class (.nav-link) so use that
to assign a class on load, just do it and don't put it in the click event
$(document).ready(function() {
$('.nav-item').addClass('active'); // <-- how to add the class on page load
$(".nav-link").on("click", function() {
$(this).parent().toggleClass('active');
});
});
.active .nav-link::after {
content: " <==";
color: red;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<div class="container">
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<li class="nav-item">
<a class="nav-link" href="{{url('/account')}}" target="_blank">
<i class="fas fa-fw fa-tachometer-alt"> account</i>
</a>
</li>
</ul>
</div>

You can check if the url has the href or not then you can trigger the click event for the <a> which has matched href ..
Try the next code
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<li class="nav-item">
<a class="nav-link" href="{{url('/account')}}" target="_blank">
<i class="fas fa-fw fa-tachometer-alt"> account</i>
</a>
</li>
</ul>
$(document).ready(function(){
$(".nav-item a").on("click", function(){
$(".nav-item.active").removeClass("active");
$(this).parent().addClass("active");
}).filter(function(){
return window.location.href.indexOf($(this).attr('href').trim()) > -1;
}).click();
});
Note about the code above ^^^^^:
The code above won't work as expected IF you have url http://website.com/account/thing and you have two <a> with hrefs /account and /account/thing both of <a> will get selected
To avoid this you can use data attribute
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<li class="nav-item">
<a class="nav-link" href="{{url('/account')}}" data-href="http://website.com/account" target="_blank">
<i class="fas fa-fw fa-tachometer-alt"> account</i>
</a>
</li>
</ul>
$(document).ready(function(){
$(".nav-item a").on("click", function(){
$(".nav-item.active").removeClass("active");
$(this).parent().addClass("active");
}).filter(function(){
return window.location.href == $(this).attr('data-href').trim();
}).click();
});
Note about the code above ^^^^^:
In <a> add data-href="http://website.com/account" replace http://website.com/account with the full url

Related

How to manage more effectively html button click events?

It looks ridiculous to do so many tasks on a button click while every button should have its own events:
function allStories() {
$('#zero-md').hide();
$('.container-aboutme').hide();
$('.container-allstories').show();
$('.container-allstories').load("pages/allstories.html");
$("#home").removeClass("nav-link active").addClass("nav-link");
$("#aboutme").removeClass("nav-link active").addClass("nav-link");
$("#allposts").removeClass("nav-link").addClass("nav-link active");
}
function aboutMe() {
$('#zero-md').hide();
$('.container-allstories').hide();
$('.container-aboutme').show();
$('.container-aboutme').load("pages/about.html");
$("#home").removeClass("nav-link active").addClass("nav-link");
$("#allposts").removeClass("nav-link active").addClass("nav-link");
$("#aboutme").removeClass("nav-link").addClass("nav-link active");
}
<li class="nav-item">
<a class="nav-link" id="allposts" onclick="allStories()" href="#">All posts</a>
</li>
<li class="nav-item">
<a class="nav-link" id="aboutme" onclick="aboutMe()" href="#">About me</a>
</li>
Is there is a better, more effective way to organize such events with less code?
You mean this
$("#nav").on("click",".nav-link",function(e) {
e.preventDefault(); // stop the link
const id = this.id;
const $thisContainer = $('.container'+id);
$('#zero-md').hide();
$('.container').hide(); // hide all containers
$thisContainer.load("pages/"+id+".html",function() { // perhaps not load if already loaded
$thisContainer.fadeIn("slow");
}) ;
$(".nav-link").removeClass("active")
$(this).addClass("active")
})
<ul id="nav">
<li class="nav-item">
<a class="nav-link" id="allposts" href="#">All posts</a>
</li>
<li class="nav-item">
<a class="nav-link" id="about" href="#">About me</a>
</li>
</ul>
Yes. Try to keep your code DRY (don't repeat yourself.)
Add an event listener in your JS.
Use e.target to determine what was clicked.
Chain your commands together when they're operating on the same elements.
Don't remove a class and then add the same class back. Just remove the one you want to get rid of.
I've added some stand in elements since not everything was present in your HTML.
$('.nav-link').click( (e)=>{
let theLink = $(e.target).attr('id');
const container = '.container-'+$(theLink).attr('id');
$('#zero-md').hide();
$('.container').hide();
$(container).show().load("pages/"+theLink+".html");
alert('loading: pages/'+theLink+'.html');
$("#home").removeClass("nav-link active").addClass("nav-link");
$(".nav-link").removeClass("active");
$("#"+theLink).addClass("active");
});
.active {
font-size: 1.5rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="nav-item">
<a class="nav-link" id="allstories" href="#">All posts</a>
</li>
<li class="nav-item">
<a class="nav-link" id="aboutme" href="#">About me</a>
</li>
<div class="container container-allstories">All Stories</div>
<div class="container container-aboutme">About Me</div>
<div id="zero-md">Zero MD</div>

Add a class if url is equal to href of a link

I'm trying to make a jQuery script in WordPress, that will add the "active" class to the element of my sidebar that has the same URL as the matching link in the navbar.
(function ($) {
var url = window.location.href;
$('.navbar-nav li').each(function ($) {
if ($('.navbar-nav li a').attr('href') == url) {
$('.navbar-nav li').addClass('active');
}
});
console.log(url);
})(jQuery);
.active {
background-color: black;}
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-white">
<div class="collapse navbar-collapse" id="navbarTogglerDemo01">
<ul class="nav navbar-nav">
<li class="nav-item menu_accueil only-mobile">
<a class="nav-link" href="<?php echo get_site_url() ?>/">
Accueil
</a>
</li>
<li class="nav-item menu_marque">
<a class="nav-link" href="<?php echo get_site_url() ?>/la-marque-honey">
La marque
</a>
</li>
<li class="nav-item menu_formule">
<a class="nav-link" href="<?php echo get_site_url().'/la-formule-honey' ?>">
La formule
</a>
</li>
<li class="nav-item menu_bebe">
<a class="nav-link" href="<?php echo get_site_url() ?>/conseil">
Le monde de bébé
</a>
</li>
</ul>
</div>
</nav>
It shows an error ( $ is not a function ), while there's another piece of code on the website that works well with the same selectors.
What's the issue here ?
Thanks
It shows an error ( $ is not a function )
This error was because you were redefining $ inside the each as the element being iterated:
$('.navbar-nav li').each(function ($) {
// Dont do this -------------------^
There were a few things wrong with your code, but in general what you were doing was using selectors within the whole page instead of selectors with the current element being enumerated using each
$(function() {
var url = window.location.href;
$('.navbar-nav li').each(function() {
if ($('a',this).attr('href') == url) {
$(this).addClass('active');
}
});
console.log(url);
});
.active {
background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar fixed-top ">
<div class="" id="navbarTogglerDemo01">
<ul class="nav navbar-nav">
<li class="nav-item menu_accueil only-mobile">
<a class="nav-link" href="xxx">
Accueil
</a>
</li>
<li class="nav-item menu_marque">
<a class="nav-link" href="xxx">
La marque
</a>
</li>
<li class="nav-item menu_formule">
<a class="nav-link" href="https://stacksnippets.net/js">
La formule
</a>
</li>
<li class="nav-item menu_bebe">
<a class="nav-link" href="xxx">
Le monde de bébé
</a>
</li>
</ul>
</div>
</nav>
You need to make sure your jquery script is loaded before your function is called. Just make sure the jquery script tag is before the script tag containing your code.
Aside from your initial error - what you have here will add .active to every li that's a child of .navbar-nav.
$('.navbar-nav li').each(function ($) {//So is $ in the function parenthisis
if ($('.navbar-nav li a').attr('href') == url) {
$('.navbar-nav li').addClass('active');//this is wrong
}
});
You should make use of the this keyword. Something like
$('.navbar-nav li').each(function () {
let anchor = $(this).children('a');
if ($(anchor).attr('href') == url) {
$(this).addClass('active');
}
});
Try this:
jQuery( document ).ready(function() {
var url = window.location.href;
$('.navbar-nav li').each(function ($) {
if ($('.navbar-nav li a').attr('href') == url) {
$('.navbar-nav li').addClass('active');
}
});
console.log(url);
});

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

Adding a class to body when a Hyperlink tag is clicked which is in the child ul of li tag using jquery

I want to add a class to body when a link is clicked. This is easily done when the link is in the parent ul, but my problem is that i want to do that for the the link present in the child ul of parent li. Whenever I try to do this It has no effect.
What I am trying to do is as given below:
Script:
<script>
$(document).ready(function () {
$("ul.treeview-menu").find("a.links").click(function () {
$("body").addClass("sidebar-collapse");
});
});
</script>
<ul class="sidebar-menu nav nav-list" id="dashboard-menu">
<li class="treeview">
<a rel="tooltip" data-placement="right" target="_self" href="">
<span class="caption">Parent Link</span>
</a>
<ul class="treeview-menu">
<li>
child link
</li>
</ul>
</li>
<ul>
Thank you in advance.
Try with on('click',...), may be your Navigation will generate dynamically after load page so you have to use delegated event binding
$(document).ready(function () {
$(document).on('click','ul.treeview-menu a.links',function () {
$("body").addClass("sidebar-collapse");
});
});
<ul class="sidebar-menu nav nav-list" id="dashboard-menu">
<li class="treeview">
<a rel="tooltip" data-placement="right" target="_self" href="">
<span class="caption">Parent Link</span>
</a>
<ul class="treeview-menu">
<li>
child link
</li>
</ul>
</li>
<ul>
you have two issues:
1- this line //}); it was commented and was preventing your code from working.
2-when the hyperlink is clicked it refreshes the page and thus any class you've added to your previous html has been erased that's why you want be able to see any change.
try this:
<script>
$(document).ready(function () {
$("ul.treeview-menu").find("a.links").click(function (e) {
e.preventDefault()
$("body").addClass("sidebar-collapse");
});
});
</script>
<ul class="sidebar-menu nav nav-list" id="dashboard-menu">
<li class="treeview">
<a rel="tooltip" data-placement="right" target="_self" href="">
<span class="caption">Parent Link</span>
</a>
<ul class="treeview-menu">
<li>
child link
</li>
</ul>
</li>
<ul>
$(document).ready(function () {
$("ul.treeview-menu").find("a.links").click(function (e) {
e.preventDefault()
$("body").addClass("Enter your class name");
});
});

Categories

Resources