Locomotive Scroll: Is it possible to use querySelector with an URL and an anchor tag?

891 Views Asked by At

The links in my navigation use URLs with an anchor-tag (f.e. mysite.com/about#cv). The reason being that i want to jump/scroll to a specific section even if i am not on the f.e. about-page. Normally this works fine. But i am using the locomotive scroll library.

I am currently using:

<script>$('.nav-link').on('click', function() {const slider = document.querySelector('#cv');locoScroll.scrollTo(slider)</script>

This works fine, when i am on the page where the anchor is located. But i want to be able to access the specific section from anywhere on my site.

1

There are 1 best solutions below

0
Tadas On

You need to check on which website page you are and then inject according script for that page:

// get currentURL
let link = $(location).attr('href');

switch (link) { 
    case 'https://yourwebsite.com/about': 
       $('.nav-link').on('click', function() {const slider = document.querySelector('#cv');locoScroll.scrollTo(slider)
    break;
    case 'https://yourwebsite.com/homepage': 
       $('.nav-link').on('click', function() {const slider = document.querySelector('#homepage');locoScroll.scrollTo(slider)
    break;
    default:
       alert('Some script if no one case from the above happens');
}