JavaScript add class depending on current URL
If you want to use "pure" ("vanilla") JavaScript, use the following code(assuming that <ul id="nav">
exists):
window.onload = function() {
var all_links = document.getElementById("nav").getElementsByTagName("a"),
i=0, len=all_links.length,
full_path = location.href.split('#')[0]; //Ignore hashes?
// Loop through each link.
for(; i<len; i++) {
if(all_links[i].href.split("#")[0] == full_path) {
all_links[i].className += " active";
}
}
}
Using jQuery:
$(document).ready(function(){
var full_path = location.href.split("#")[0];
$("#nav a").each(function(){
var $this = $(this);
if($this.prop("href").split("#")[0] == full_path) {
$this.addClass("active");
}
});
});
Adding active class based on current URL
You have a few issues with your code. Your mainly confusing jQuery methods with regular native browser methods/conventions:
You need to use
.forEach()
and not.each()
. The.forEach()
method is a method on the NodeList thatquerySelectorAll()
returns..attr()
is not a valid method. To get an element's attribute you can use.getAttribute()
. We can use.href
here instead to get the href. Note thatgetAttribute("href")
will retrieve the URL as it is in your mark-up, whereas.href
will retrieve the full, eg, if you hadhref="/foo/bar"
,.href
will givehttps://example.com/foo/bar
, whereas.getAttribute()
will return just/foo/bar
.Use the element parameter of the function instead of
this
. When you use.forEach()
you're iterating over the elements in your NodeList (ie: the elements you selected), so you can access each using the first parameter of theforEach
callback. Thethis
value in the browser (if not in strict mode) will default towindow
, so it won't be the element like you're expecting it to be:
const current = window.location.href;
document.querySelectorAll("#nav-tab a").forEach(function(elem){
if(elem.href.includes(current)){
elem.classList.add("active");
}
});
I've also changed .indexOf(...) !== -1
to .includes()
, which is a more modern way to check if a string contains another value.
I will point out that you can make your query selector more advanced, which will limit the number of elements you iterate:
const current = window.location.href;
document.querySelectorAll(`#nav-tab a[href*="${current}"]`).forEach(elem => {
elem.classList.add("active");
});
This uses the attribute selector a[href*=...]
to select the a
elements that have a href
that contains the text in stored in current
.
Add css class to menu item based on current url
You should use an else if
and put https://mywebsite.com/dashboard/
at the end because it would match your other 2:
jQuery(document).ready(function() {
if (window.location.href.indexOf("https://mywebsite.com/dashboard/?candidate-page=my-orders") > -1) {
$('a[href="https://mywebsite.com/dashboard/?candidate-page=my-orders"]').addClass("current-active-menu");
} else if (window.location.href.indexOf("https://mywebsite.com/dashboard/?candidate-page=resumes-list") > -1) {
$('a[href="https://mywebsite.com/dashboard/?candidate-page=resumes-list"]').addClass("current-active-menu");
} else if (window.location.href.indexOf("https://mywebsite.com/dashboard/") > -1) {
$('a[href="https://mywebsite.com/dashboard/"]').addClass("current-active-menu");
}
});
Also it looks like you whole url should match so you should think about using ===
in your if instead of indexOf
:
window.location.href === "https://mywebsite.com/dashboard/?candidate-page=my-orders"
With your original problem, using indexOf
put the active class onto the wrong link because you were testing if that string exists anywhere in the url (which https://mywebsite.com/dashboard/
exists in all three of your urls you test)
Add Active Navigation Class Based on URL
The reason this isn't working is because the javascript is executing, then the page is reloading which nullifies the 'active' class. What you probably want to do is something like:
$(function(){
var current = location.pathname;
$('#nav 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.addClass('active');
}
})
})
There are some cases in which this won't work (multiple similarly pointed links), but I think this could work for you.
Add a class to a page element contained in a particular url
to check if a url contains any string, do the following:
if(window.location.href.indexOf(".com/poste") > -1) {
// do something
}
(checking if the index of a string is bigger than -1 is like asking if he is in there)
to conditonally add class:
element.classList.add("my-class");
combined it would be:
if(window.location.href.indexOf(".com/poste") > -1) {
titleClass = document.querySelector(".your-title-class");
titleClass.classList.add("conditionalClass");
}
*there are other solutions using jquery (like the one in @Wimanicesir comment), but it personaly prefer not using it :)
Related Topics
How to Disable a Specific Li Element Inside a Ul
CSS Reveal from Corner Animation
How to Style Canvas Elements with CSS
Getting Values of Global Stylesheet in Jquery
How to Change the Label Size of a Material UI Textfield
Cross-Browser Way to Flip HTML/Image via JavaScript/Css
Something Similar to Treegrid in Jqgrid
Bootstrap 3 Compatible with Current Angularjs Bootstrap Directives
Detect High Contrast Extension Use in Chrome Browser
How to Position a Bootstrap Popover
How to Detect MAC Os Inverted Color Mode in JavaScript/Css
How to Get All Valid Keywords for CSS Property
Make Bootstrap Modal Draggable and Keep Background Usable
How to Check What Fonts Are Installed on MAChines via the Web
Make a Div Scroll When I Reach a Certain Point