How to set active link on page reload? - javascript

I want to add active link on page reload, but I don't know how to do this. The fact is that when I put active based on bootstrap 4, the active link doesn't work. I try many things but I really don't know how to interact with this jquery's plugin. Please help me.
I don't know how to make this on existing code.
HTML
<ul id="myNav" class="nav mt-7 mb-5">
<li class="nav-item">
<a class="nav-link active chiffres" href="tgn.php">01</a>
</li>
<li class="nav-item">
<a class="nav-link chiffres" href="oprah.php">02</a>
</li>
<li class="nav-item">
<a class="nav-link chiffres" href="innocent.php">03</a>
</li>
<li class="nav-item">
<a class="nav-link chiffres" href="reveal.php">04</a>
</li>
<li class="nav-item">
<a class="nav-link chiffres" href="maison21g.php">05</a>
</li>
</ul>
JAVASCRIPT
(function($){
$.fn.linkUnderlineAnim = function(options) {
var defaults = $.extend({
"speed" : 300,
"color" : "#DB3340",
"thickness" : 2,
"distance" : 0,
"bottom" : 0
}, options);
return this.each(function() {
var items = $("li a");
var o = defaults;
items.css("position", "relative")
.css("text-decoration", "none")
.css("padding-bottom", o.distance);
var id = this.id;
if (id !="") {
// it has id, so we will use it to customize the style sheet
}
else {
// it does not have id, so we generate a unique one to
customize the style sheet
this.id = '_' + new Date().getTime(); // it is important to
prefix the id with any character, because only numbers not working in
CSS selection
id = this.id;
}
//it is not possible to access :before in JavaScript/jQuery, so
we add a stylesheet instead. But we used/generated the id to avoid
styling non selected (ul) elements
var css = '#' + id + ' li a {position: relative; text-decoration:
none;}' +
'#' + id +' li a:before {content: "";position: absolute;
width: 100%; height: ' + o.thickness + 'px; bottom: ' + o.bottom +
'px; left: 0;'+
'background-color: ' + o.color + ';' +
'visibility: hidden; -webkit-transform: scaleX(0); transform:
scaleX(0);' +
'-webkit-transition: all ' + o.speed/1000 +'s ease-in-out 0s;
transition: all ' + o.speed/1000 + 's ease-in-out 0s;}' +
'#' + id +' li a:hover:before {visibility: visible; -webkit-
transform: scaleX(1); transform: scaleX(1);}' + '#' + id +'li
a:active{background:red;}' ,
head = document.head || document.getElementsByTagName('head')
[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
});
}
})(jQuery);

Try this solution it will take the path from your url and set active class into it.
$(function($) {
let url = window.location.href;
$('li a').each(function() {
if (this.href === url) {
$(this).closest('li').addClass('active');
}
});
});
.active {text-decoration: underline}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul id="myNav" class="nav mt-7 mb-5">
<li class="nav-item">
<a class="nav-link chiffres" href="tgn.php">01</a>
</li>
<li class="nav-item">
<a class="nav-link chiffres" href="oprah.php">02</a>
</li>
<li class="nav-item">
<a class="nav-link chiffres" href="innocent.php">03</a>
</li>
<li class="nav-item">
<a class="nav-link chiffres" href="reveal.php">04</a>
</li>
<li class="nav-item">
<a class="nav-link chiffres" href="maison21g.php">05</a>
</li>
</ul>

Related

Display content by category

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.

Adding an active class to the navbar

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')
}
})

Active link name is not changing color in bootstrap navbar

This is a single-page website currently I am working on. But When I click another link in the navbar it's not changing color though hovering is working perfectly. Here is my html code :
<html>
<body>
<div class="collapse navbar-collapse justify-content-between" id="navbarSupportedContent">
<ul class="navbar-nav ms-auto mb-2 ">
<li class="nav-item ">
<a class="nav-link scroll active " aria-current="page" href="#intro">Home</a>
</li>
<li class="nav-item">
<a class="nav-link scroll" href="#about">About Us </a>
</li>
<li class="nav-item">
<a class="nav-link scroll" href="#services">Services</a>
</li>
<li class="nav-item">
<a class="nav-link scroll" href="#">Products</a>
</li>
</ul>
</div>
</html>
</body>
enter image description here
Here is my css:
<style>
.navbar .nav-item a {
color: #5cbf8f !important;
}
.navbar .nav-item a:hover {
color: #028b77 !important;
}
.navbar .nav-item a.active {
color: #028b77 !important;
}
</style>
enter image description here
Here is my Js :
<script>
$(document).ready(function () {
var scrollLink = $(".scroll");
// Smooth scrolling
scrollLink.click(function (e) {
e.preventDefault();
$("body,html").animate(
{
scrollTop: $(this.hash).offset().top,
},
1000
);
});
// Active link switching
$(window).scroll(function () {
var scrollbarLocation = $(this).scrollTop();
scrollLink.each(function () {
var sectionOffset = $(this.hash).offset().top - 20;
if (sectionOffset <= scrollbarLocation) {
$(this).parent().addClass("active");
$(this).parent().siblings().removeClass("active");
}
});
});
});
</script>
enter image description here
N.B: Don't really know about js, just found it on the internet.
Navbar:
enter image description here
I think your js is wrong.
$('.active').removeClass('active');
$(this).addClass('active');
More efficient options are available if the DOM hierarchy is known.
For example, if they're all siblings, you can use this:
$(this).addClass('active').siblings('.active').removeClass('active');

Improve code for increasing font size in Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am working on a functionality to increase/decrease font size of the page. The font size of the navbar cannot increase beyond 19px and that of the rest of the content cannot go beyond 50px ; and in case of decrement- the font size of navbar cannot decrease below the current size and that of the rest cannot go below 20px.
I have only written the code for the page content(which is working). I need help with completing it for the navbar and improving the code.
Below is the HTML,CSS & JS code -
function inc() {
var el = document.getElementById('test');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
console.log("SIZE", fontSize)
if (fontSize <= 50) {
el.style.fontSize = (fontSize + 2) + 'px';
console.log("incSize", el.style.fontSize)
}
}
function dec() {
var el = document.getElementById('test');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
console.log("SIZE", fontSize)
if (fontSize >= 20) {
el.style.fontSize = (fontSize - 2) + 'px';
console.log("decSize", el.style.fontSize)
}
}
/* Basic styling */
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
nav {
background: #001a33;
}
.navbar-nav .nav-link {
color: white;
font-size: 12.8px;
}
.navbar-nav .nav-link:hover {
color: #91d5f3;
text-decoration: none;
}
.submenu {
color: white;
padding-top: 0.5rem;
font-size: 0.9rem;
}
.submenu-select {
font-size: 16px;
}
<nav class="navbar navbar-expand-lg py-0 " id="header-bar">
<div class="container">
<button class="navbar-dark 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 mr-auto">
<li class="nav-item">
<a class="nav-link" href="#" id="first">ITEM1<span
class="sr-only">(current)</span></a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link " href="#">ITEM0</a>
</li>
<li class="nav-item">
<a class="nav-link px-3" href="#">ITEM2</a>
</li>
<li class="nav-item">
<a class="nav-link " href="#">ITEM3</a>
</li>
<li class="nav-item">
<a class="nav-link px-3 " href="#">ITEM4</a>
</li>
<label for="submenu" class="submenu px-2">Submenu:</label>
<select name="submenu" id="submenu" class="submenu-select">
<option value="Option1">option1</option>
<option value="Option2">option2</option>
</select>
</ul>
</div>
</div>
</nav>
<button onclick="inc()">INCREASE</button>
<button onclick="dec()">DECREASE</button>
<h1 id="test">FONT CHANGE</h1>
Try this
Create an array of items on the page with their corresponding min and max sizes
Have one function decide if it is increase or decrease (DRY)
loop over the array
NOTE: I moved the font-size of the nav to the nav container
NOTE: I have NOT tested this in IE8. It is not feasible to support anything lower than IE11
var items = [{
"el": "nav",
"maxSize": 30,
"minSize": 12.8
}, {
"el": "#test",
"maxSize": 50,
"minSize": 20
}]
var incdec = function(dir) {
items.forEach(function(item) {
size(dir, item)
});
};
var size = function(dir, item) {
var el = document.querySelector(item.el);
var max = item.maxSize;
var min = item.minSize;
console.log(dir, min,max)
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
if (dir === 1 && fontSize <= max) {
el.style.fontSize = (fontSize + 2) + 'px';
console.log("incSize", el.tagName, el.style.fontSize)
} else if (dir === -1 && fontSize >= min) {
el.style.fontSize = (fontSize - 2) + 'px';
console.log("decSize", el.tagName, el.style.fontSize)
}
}
/* Basic styling */
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
nav {
background: #001a33;
font-size: 12.8px;
}
.navbar-nav .nav-link {
color: white;
}
.navbar-nav .nav-link:hover {
color: #91d5f3;
text-decoration: none;
}
.submenu {
color: white;
padding-top: 0.5rem;
font-size: 0.9rem;
}
.submenu-select {
font-size: 16px;
}
<nav class="navbar navbar-expand-lg py-0 " id="header-bar">
<div class="container">
<button class="navbar-dark 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 mr-auto">
<li class="nav-item">
<a class="nav-link" href="#" id="first">ITEM1<span
class="sr-only">(current)</span></a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link " href="#">ITEM0</a>
</li>
<li class="nav-item">
<a class="nav-link px-3" href="#">ITEM2</a>
</li>
<li class="nav-item">
<a class="nav-link " href="#">ITEM3</a>
</li>
<li class="nav-item">
<a class="nav-link px-3 " href="#">ITEM4</a>
</li>
<label for="submenu" class="submenu px-2">Submenu:</label>
<select name="submenu" id="submenu" class="submenu-select">
<option value="Option1">option1</option>
<option value="Option2">option2</option>
</select>
</ul>
</div>
</div>
</nav>
<button onclick="incdec(1)">INCREASE</button>
<button onclick="incdec(-1)">DECREASE</button>
<h1 id="test">FONT CHANGE</h1>

Change menu background color for current page

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"

Categories