I have various section on my docusaurus homepage, and from the top navigation bar I am able to scrollTo
intended sections using below code by checking window.location.pathname==='/'
.
let navLink = document.querySelectorAll('nav .navbar__link');
if(navLink) {
navLink.forEach(function(link) {
link.addEventListener('click', function(e){
e.preventDefault();
let selectedSection = e.currentTarget.textContent.toLowerCase();
if(window.location.pathname === '/') {
window.scrollTo(0,document.querySelector(`#anchor-${selectedSection}-section`).offsetTop - 100);
}
})
})
}
Which is working fine when I am on home page.
After coming back (routing) to home page from docs page by clicking on Home
nav link, the scrollTo
method doesn't work and I am straightaway routed to docs path instead of scrolling to one of the home sections. Although I am checking for window.location.pathname === '/'
the code doesn't execute.
Can someone help me figure out what is happening behind the scenes of routing while clicking from docs pages.
Note: I have written the above script on index.js
file.
Step 1 : Created a new page called home.js
Step 2 : updated the docusaurus.config.js link object from /
to /home
{ to: '/home', label: "Home", position: 'left'}
Step 3: inside home.js
added the redirect functionality to redirect to "/" which solved my actual issue.