Home > Blockchain >  How to prevent a webpage scrolling to the top when a link is clicked?
How to prevent a webpage scrolling to the top when a link is clicked?

Time:01-13

Every time I click on the navigation arrow in my image carousel, image slide is changed but the webpage is scrolling to the top.

  <div >
    <a id="link"  href="#item-3"></a>
    <a id="link"  href="#item-2"></a>
  </div>

I know it's because of the "#" in the href, however, I am not sure how to prevent this behavior.

CodePudding user response:

If your navigation arrows require no page transition, may I suggest you use a different html element such as the div or span element?

<div >
  <div id="link" ></div>
  <div id="link" ></div>
</div>

CodePudding user response:

You can change the

<a href="#">My Link</a>

to

<a href="javascript:;">My Link</a>

This way when the link is clicked the page won't scroll to top. This is cleaner than using href="#" and then preventing the default event from running.

  •  Tags:  
  • Related