Reputation: 6800
I'm creating a custom button on my webpage which actually is a <div>
, I want to trigger a mailto when the button is clicked. What is the best way out?
I've tried calling a javascript function using-onClick that looks like this -
function foo(){
window.open("mailto:[email protected]");
}
But that opens a new tab in Chrome first, and then asks for the relevant app to send out the email. This experience is different from what we generally get when we simply do a <a href=mailto:.....>
in HTML.
I can also create a new document element in the JS function, and simulate a click like this -
function sendEmail() {
var mail = 'mailto:[email protected]';
var a = document.createElement('a');
a.href = mail;
a.click();
};
But i'm not too sure if that's the right way! Anyone has a better solution?
Upvotes: 43
Views: 125878
Reputation: 17657
Try this, and tell me if works. (If not, I will delete answer.)
<script>
function sendEmail()
{
window.location = "mailto:[email protected]";
}
</script>
<div onclick="sendEmail();">Send e-mail</div>
It is possible to pass the parameters subject and body, but I think that it is not possible to format the text:
<a href='mailto:[email protected]?subject=Me&body=Hello!'>EMAIL</a>
Upvotes: 68
Reputation: 2289
In order to obfuscate your email from SPAM bots that scan website for emails, you can do the following,
<div class="button" onclick="location.href='mail'+'to:xyz'+'@'+abc'+'.'+'com';">Send E-Mail</div>
and instead of the 'Send E-Mail' text you can place an image of your actual email address (screenshot) to make it more obvious.
Upvotes: 7
Reputation: 1215
This worked for me:
<script>
function sendEmail()
{
window.location.assign("mailto:[email protected]");
}
</script>
<div onclick="sendEmail();">Send e-mail</div>
@Tony has used the same approach just assign
has been added.
Upvotes: 9
Reputation: 11
Try this :
<div class="button" href="javascript: void(0)" onclick="location.href='mailto:[email protected]';">Click to Send email</div>
Upvotes: 0
Reputation: 9661
Extremely late to the party I know, but what about combining these answers into something simpler and more practical:
<div class="button" onclick="location.href='mailto:[email protected]';">Send E-Mail</div>
Upvotes: 32
Reputation: 83
Try this function and html. It will open a new email client with.
<div onclick="doMail();">
function doMail() {
var email ="[email protected]";
location.href = "mailto:"+email;
}
Upvotes: 6
Reputation: 9947
<div onclick="mailtoperformingFunction('inner');" id="divbutton">
<script type="text/javascript">
function mailtoperformingFunction()
{
}
</script>
Upvotes: 0
Reputation: 36794
Use an anchor tag but change the display property to block:
HTML
<a class="mailto" href="mailto:[email protected]">Mail</a>
CSS
.mailto{
display:block;
width:100px;
height:20px;
}
Upvotes: 28