Hi,
I’m trying to add a class (.active) to a div (.target) on page load when the URL has a specific slug (#active). Is that possible with java script?
Here is my site Read-Only: Webflow - Test Site
Hi,
I’m trying to add a class (.active) to a div (.target) on page load when the URL has a specific slug (#active). Is that possible with java script?
Here is my site Read-Only: Webflow - Test Site
With JS, certainly. Check the URL, find your div, add your class.
Thanks, this seems to work:
<script>
document.addEventListener('DOMContentLoaded', function () {
if (window.location.hash === '#active') {
var targetDiv = document.querySelector('.target');
if (targetDiv) {
targetDiv.classList.add('active');
}
}
});
</script>
Hi, I have the same question so don’t want to hijack the topic, but in my case the slug doesn’t contain a hash but is a value of a parameter (filter). I’ve looked for the corresponding method and found the searchParams property and URLSearchParams: get() method. The latter helped me to extract the value of the URL, but I can’t get the if-statement to work to add the class to the tag:
let params = new URLSearchParams(document.location.search);
let name = params.get(“portfolio-tag_equal”);
console.log(name)
if (name === “"%5B\"Writing\"%5D"”) {
const activeClass = document.querySelector(‘.tag-with-active-state’);
activeClass.classList.add(‘is-active-inputactive’);
}
In the above example I’m trying to add the class to each tag, just to get it to work first, but no results. The console.log(name) returns [“Writing”]. Using this in the if-statement didn’t work, so I tried to use the way it’s written in the URL, with the ‘\’ added in front of the ‘ “ ‘. But again no result. I’ve also tried @matthiash way with the double if-statement.
In the end I’d like to give the tag the active state that’s corresponding with the value in the URL. Was thinking of writing a different if-statement for each value to get it to work first, and later on to find the corresponding URL value with the text in the tag, probably needing regex since for instance the URL value of Graphic Design is Graphic+design.
Any help of getting this to work would be great!