ทำ Scroll smooth และ focus anchor link

Published on
Web Development
Discord

ให้ browser ไป focus ตำแหน่ง Anchor link เวลากดเข้ามา หรือ refresh url ยังไง?

ตัวอย่างเช่น link /path/to/url#step3 ให้ไป focus ที่ #step3 เลย

ใช้ window.onload และ window.scroll (ถ้าจะให้มัน scroll หรือใช้ auto )

window.onload = () => {
  const hash = window.location.hash;
  const id = hash.substr(1);
  const element = document.getElementById(id);

  if (element) {
    window.scroll({
      behavior: 'smooth',
      left: 0,
      top: element.offsetTop
    });
  }
};

ส่วน CSS ปรับแค่

html {
  scroll-behavior: smooth;
}

Gatsby ใส่ไว้ในไฟล์ gatsby-browser.js

export const onClientEntry = () => {
  window.onload = fn;
};
Buy Me A Coffee
Authors
Discord