Search code examples
javascriptbrowserscrollmailto

By clicking "mailto" link jumps to top of the page


I used this javaScript code to add "mailto" to an element on my page:

document.getElementById("mailTo").href = "mailto:?subject=look at this website&body=Hi,I found this website and thought you might like it "+ document.location.href

Now, when I click the link, it opens the email just fine, but it also jumps to the top of the page suddenly, can anyone tell me why that is happening? or how I can stop that behavior?


Solution

  • I'd remove the original onClick event from the link, and create a new function to handle the click. That should prevent the unwanted behavior from a regular a-tag, which I guess that your button is?

    Something along the lines of;

    document.getElementById('mailTo').removeAttribute("onclick");
    
    document.getElementById('mailTo').onclick = function(){
        location.href = "mailto:?subject=look at this website&body=Hi,I found this website and thought you might like it "+ document.location.href;
    };
    

    The documentation on "preventDefault();" here could also prove valuable: https://www.w3schools.com/jsref/event_preventdefault.asp