0

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 class="carousel-item item-1">
    <a id="link" class="arrow arrow-prev" href="#item-3"></a>
    <a id="link" class="arrow arrow-next" 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.

Ali Roman
  • 11
  • 2
  • Does this answer your question? [How to prevent default event handling in an onclick method?](https://stackoverflow.com/questions/7056669/how-to-prevent-default-event-handling-in-an-onclick-method) in your JS click handler for the image carousel, call `event.preventDefault()`. More info at https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault – WOUNDEDStevenJones Jan 12 '22 at 20:34
  • Are there any elements with corresponding ids you are linking to? If not, you could consider to add them somewhere on your page with `position:fixed` e.g. ``. Please note: Element IDs should be unique within the entire document. – schmauch Jan 12 '22 at 21:28

2 Answers2

0

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 class="carousel-item item-1">
  <div id="link" class="arrow arrow-prev"></div>
  <div id="link" class="arrow arrow-next"></div>
</div>
neoguri
  • 139
  • 1
  • 9
0

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.