简体   繁体   中英

How to stop html page from jumping when anchor is clicked, but still go to the url in the href?

I know that this issue seems similar to many that preceded it, but the main difference is that I still want to go to the url that's in the anchor's href and direct them to another page.

Here's my code: <a class="tile" href="https://www.weather.com">weather<a/>

When the anchor is clicked, it jumps to the top of the page right before the user is redirected to the url in the href

I've tried adding this to the JS to resolve it, but to no avail.

this.el.addEventListener('click', (e) => {
    e.preventDefault();
    window.location = this.el.getAttribute('href');
}, false);

Any help would be appreciated.

You shouldn't need that javascript but simply try adding the http protocol to the front of your url. For example: <a class="tile" href="https://www.weather.com" />

This post explains why. Without specifying a protocol, the link will be relative to the current request URI

It should not Jump. However in your case if it jumps then use dud href and then click event on that:

<a class="tile" href="javascript:void(0)"  onclick='redirect(event)'>weather<a/>

in Script: i think in your example you are missing: window.location. href

 function redirect(e){
    e.preventDefault();
    window.location.href = "https://www.weather.com"; // notice href
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM