0

I have a location.href code added to identify the section of the page the user is viewing in the URL (www.example.com/#section1, www.example.com/#section2 etc.)

  document.getElementById('link_no' + (i + 1)).classList.add('active-link');
        let currentLocation = location.href;
        currLocationArray = currentLocation.split("#");
        currentLocation = currLocationArray[0];
        currentLocation += `#section${i+1}`;
        
        location.href = currentLocation;
// scroll section
let sectionOfI = document.getElementById(`section${i+1}`);
        let scrollArea = getOffset(sectionOfI);
          scrollEventNew(scrollArea.top,e);

but it's messing up the smooth scroll of my JS built scroll function



function scrollEventNew(y , event) {
      window.scrollTo({
        left: 0,
        top: y,
        behavior: 'smooth'
    })  
    }

is there a way to keep both codes without commenting out my location.href?
I can't opt for a CSS smooth scroll either.

srohome
  • 15
  • 2
  • You shouldn't be setting `window.location.href` in the first place - instead use `history.pushState`. – Dai Jun 30 '22 at 22:59
  • Your code does the same thing as `Element.scrollTo` - when programming you generally should not reinvent-the-wheel. Just do `sectionOfI.scrollTo( { behavior: 'smooth' } )`, see here: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo (`Element.scrollTo` is not the same thing as `window.scrollTo`). – Dai Jun 30 '22 at 23:01
  • 1
    Setting `location.href` redirects to the page you set it to which is why it jumps to that section, and your scroll code is running after it but it's already where it needs to be after the redirect so effectively it does nothing. [Here](https://stackoverflow.com/a/12446376/10601203) is an example of changing the URL without redirecting, or you could try to set the location.href after your scroll method finishes. – Jesse Jun 30 '22 at 23:03

0 Answers0