Archived topic
Disabled smooth scroll, now clicking # anchor links causing page to refresh
2 replies · Started by Randy on June 19, 2021
Hi,
To try to eliminate unnecessary javascript bloat (working on CWVs), I disables the Smooth Scroll class in Customizer > General.
I then added this line to my child theme css file (per the tip in the smooth scroll deprecation notice here https://github.com/cferdinandi/smooth-scroll#readme):
html {
scroll-behavior: smooth;
}
Now the issue is that when I click on a button that points to the id attribute of another element (e.g. #anotherelementid), the behavior is inconsistent. Sometimes, this triggers the page to refresh, sometimes to open in a new tab...it's just not consistently scrolling to the target id.
I found a possible work-around, which is to add a preventDefault() to all of the click listeners like this:
document.querySelector('.somebuttonclass').addEventListener('click', function (e) {
e.preventDefault();
//do other stuff
}, false);
But this seems messy and cumbersome to have to do everywhere. Is there some better way to get theses #anchor tags to behave correctly (e.g. scroll to the target element and not refresh page nor open page in new tab)
Example bad behavior in private info box.
Thank you
Oops...ignore the bad example in the private info box...I accidentally had "open link in new window" set on that button in GB.
The rest of my question remains though regarding a better way to prevent page refreshes when clicking on some #anchor links other than using preventDefault() if possible?
Hi there,
the preventDefault shouldn't be required when using the scroll-behaviour CSS property for those kinds of links. And page reload shouldn't occur when following an on page link. I also tested the button several times and could not get the reload to occur.
If reload is occurring then i can only assume there are other eventListeners that are interfering with its behaviour.