0

I wanna have the feature on my website that if I click one of the topbar navigation elements in the header I wanna be in this section on the website. For example if I click here "How":enter image description here

I wanna land here:enter image description here

How can I do that?

AIIMOOR
  • 57
  • 1
  • 8
  • 1
    I pretty sure this is a duplicate to [Link to a section of a webpage](https://stackoverflow.com/questions/8424785/link-to-a-section-of-a-webpage/8424807) or [Linking to a specific part of a web page](https://stackoverflow.com/questions/15481911/linking-to-a-specific-part-of-a-web-page) (and likely many more), if not then please explain why. – t.niese Oct 05 '21 at 10:39

2 Answers2

0

If it's on the same page, look into making headings link targets. The premise being the a tags in your nav point to an id on a heading tag e.g.

<a href="#about-us">...</a>

<!-- will take you to: -->

<h2 id="about-us">About us</h2>

seedBoot
  • 373
  • 2
  • 12
  • Before answering a question you should check if it has already been answered here on SO. And if your answer does not include any new information compared to those you should leave a comment pointing to that answer(s) instead of writing a new one with basically the same content. (or vote to close it as soon as you have enough reputation) – t.niese Oct 05 '21 at 10:45
0

To get a smooth scrolling experience instead of jumping to an anchor, you can achieve this by by using an eventListener on the header. Then using the getBoundingClientRect() of the how element to get its position on the page.
You can then scroll the window object to the position of the how Element.

let header = document.getElementById('hacker-header');
let how = document.getElementById('how');
header.addEventListener('click', () => {
  window.scrollTo({
    top: how.getBoundingClientRect().y,
    left: how.getBoundingClientRect().x,
    behavior: 'smooth'
  });
});
body {
background: black;
}
h1 {
 color:lime;
}
#high {
   height: 5000px;
   width:200px;
   background: linear-gradient(180deg, rgba(112,135,95,1) 0%, rgba(21,55,31,1) 35%, rgba(7,121,5,1) 100%);
}
<header id="hacker-header">
<h1>Hacker</h1>
</header>
<div id="high">
</div>
<footer id="how">
<h1>How</h1>
</footer>
Tschallacka
  • 27,901
  • 14
  • 88
  • 133
  • 1
    Why JavaScript if one could just use `scroll-behavior: smooth;` for a smooth scrolling experience? – t.niese Oct 05 '21 at 10:57