Wednesday, January 27, 2010

Use Javascript to create email

I have a mailto link (using <a />). Upon clicking on that link, I wish to carry out other functions as well (e.g. hide a div, popup a message, etc). The onclick attribute in <a /> does not work properly with the mailto in href.

A solution is to define a Javascript function that handles the mailto inside it.
function Link_OnClickEvent() {
$("#Comment").hide();
window.open("mailto:coded@mail.com", "_blank");
}

Note: You can also use this method if you want to dynamically define the email subject, content or mailto address.

1 comment:

  1. The last line can be considered a bad practice nowadays. The reason is that it opens unnecessary window, and completely bypasses user preference. You might want to consider using location.href (I have not personally tried it, given my resistance towards having a publicly visible email address).

    Would you enlighten us as to why onclick attribute does not work properly with mailto? This test works (albeit I've only tried it in Chrome):

    <script>
    function onClick() {
    alert('test');
    }
    </script>
    <a href="mailto:test@test.com" onclick="onClick();">Test</a>

    ReplyDelete