0

Hihi, I need that when I visit my webpage and # is present in the url go to that section. So What I did is to add an JS script

document.addEventListener('DOMContentLoaded', () => {
    // setupScrolling();
    setupTitle();
    if (window.location.hash) {
        const element = document.getElementById(window.location.hash);
        if (element) {
            const offset = element.offsetTop;
            const a = offset - (document.querySelector('header')?.offsetHeight);
            window.scroll({
                top: offset,
                behavior: 'smooth'
            });
            return false;
        }
    }
});

This is the script I added into my public/index.html

But, the behavior isn't correct.. Once the page scroll down to the section it will automatically go back to the top of the site and I don't know why.

Can anyone help me and tell me what I should do?

juli1234
  • 67
  • 6
  • Hi @juli1234! First of all, can you provide an example from your HTML code? I understood that you're trying to pass the ID of an element which should anchor the scroll within the hash value, right? – Rafael Cavalcante Nov 05 '21 at 14:25
  • try using [Element.scrollIntoView()](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) instead of `window.scroll` – WhiteHat Nov 05 '21 at 14:37

1 Answers1

0

You don't really need javascript to do this. You can only use HTML.
Simply add an id to the elements you want to allow users to jump to.
Then, when the id of an element is present in your webpage URL as a hash, the page will be directly scrolled to it when the page is loaded.

For example, let say I've got an element with the id 'down-section'

<span id="down-section">Down Section in the page</span>

Access to the link https://your-domaine.com#down-section will directly jump to "Down Section in the page".

Add a smooth behavior.

You may want to add smooth behavior in this particular case. Just add a code like this to your javascript script:

if (!!document.location.hash){
    document.getElementsByTagName('html')[0].style.scrollBehavior = 'smooth';
}
Nel
  • 454
  • 5
  • 14
  • It isn't working anyway.. I don't know if it is react or what.. – juli1234 Nov 05 '21 at 18:00
  • You didn't mention you're using react.. It's a very important information here.. – Nel Nov 05 '21 at 21:42
  • Take a look at these answers, they may help you https://stackoverflow.com/questions/43441856/how-to-scroll-to-an-element – Nel Nov 05 '21 at 21:42