Same page link-age

Have you ever wondered how to create a link to an element that is not on a different page, but on the same page as your link?

While creating my portfolio page I had this very confounding issue. I knew how to create links <a href=""> so I started there. I gave each of my elements that I wanted to link to a unique id and passed that id href="#projects".

This worked wonderfully until I looked up at my URL…oh no! My href tacked /#projects onto the end of my URL! This was an unintended side effect that I definitely did not want! But how do I get it to go away while still being able to link to a different section on my page??

Now I have to begin my search for how to do this seemingly simple thing; which although appears simple may not actually be. To <insert preferred search engine> we go!!

After searching for what seemed like an eternity, and not coming up with results that met my needs, I just so happened to stumble across something that seemed so elegantly simple that I figured I would try it; what could it hurt? It could only not work again, right?

Enter document.querySelector().scrollIntoView().

Being a new developer scrollIntoView() is not something that I had come across yet, but it seemed to describe perfectly what I was trying to do. Shout out to the person who named this function so descriptively and succinctly!

With this set of methods, I can plug my unique IDs into the querySelector and use them in an onClick event!

const scrollToContact = () => {
document.querySelector('#contact').scrollIntoView()
}
<Nav.Link onClick={scrollToContact}> Contact Me </Nav.Link>

Badda bing badda boom! It works! It scrolls to the exact spot on my page I want it to and it doesn’t add anything onto my URL! Huzzah and sound the trumpets!

Hopefully, this trick will save you mountains of time and work for the project that you’re building! TTFN and happy coding!