mailto in JavaScript

Kushank Singh Oct 12, 2023
mailto in JavaScript

There is a dire need to have a mailto functionality in many web applications that can mail some information to the given address.

This tutorial will add such mailto functionality to any element using JavaScript.

The Document.createElement() function creates a new HTML elemet by specifying the tagName. It returns the new element.

Use the code below and add mailto functionality to any element using JavaScript.

var email = document.createElement('a');
email.href = 'mailto:abc@mail.com';
email.click();

In the code example, an anchor tag with name email was created, and we added the mailto functionality to it using the href attribute.

We can consider an alternative method to add such mailto functionality using jQuery.

When clicked upon, we have an anchor tag that activates the functionality and lets us mail to the given mail address.

In jQuery, an efficient JavaScript library, the attr() method is used to set values to attributes or return them.

Check the code below.

HTML Code:

<a id="email" href="#">
  Click to mail.
</a>

jQuery Codes:

$(document).ready(function() {
  $('#email').attr('href', 'mailto:abc@mail.com');
});