OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Add Offset Y "-100px" when I click on an anchor and it scrolls me down to an element

  • Thread starter Thread starter Mada
  • Start date Start date
M

Mada

Guest
I need to add an offset of -100px when I click on a link that scrolls me down to a section. I have managed to make my scroll smooth , but i cannot make it to scroll with offsetY.

Here is my js code :

Code:
const links = document.querySelectorAll("a");

for (const link of links) {
  link.addEventListener("click", clickHandler);
}

function clickHandler(e) {
  e.preventDefault();
  const href = this.getAttribute("href");
  const offsetTop = document.querySelector(href).offsetTop;

  scroll({
    top: offsetTop,
    behavior: "smooth",
  });
}

... and here is my html :

Code:
<a href ="#mysection">Go to section </a>
<p>this is some lorem</p>
<p>this is some lorem</p>
<p>this is some lorem</p>

<div id ="mysection"> The section that appears when i click on the anchor. I want an offset on this div so that when i click on anchor, it wil scroll me at the beggining of this section </div>

<p>I need to add an offset of -100px when I click on a link that scrolls me down to a section. I have managed to make my scroll smooth , but i cannot make it to scroll with offsetY.</p>
<p>Here is my js code :</p>
<pre><code>const links = document.querySelectorAll("a");

for (const link of links) {
link.addEventListener("click", clickHandler);
}

function clickHandler(e) {
e.preventDefault();
const href = this.getAttribute("href");
const offsetTop = document.querySelector(href).offsetTop;

scroll({
top: offsetTop,
behavior: "smooth",
});
}
</code></pre>
<p>... and here is my html :</p>
<pre><code><a href ="#mysection">Go to section </a>
<p>this is some lorem</p>
<p>this is some lorem</p>
<p>this is some lorem</p>

<div id ="mysection"> The section that appears when i click on the anchor. I want an offset on this div so that when i click on anchor, it wil scroll me at the beggining of this section </div>
</code></pre>
 

Latest posts

H
Replies
0
Views
1
Hür Doğan ÜNLÜ
H
Top