Forum Moderators: open

Message Too Old, No Replies

mailto using document.location not working

works in ie + chrome but not firefox

         

martynrlee

1:11 pm on Feb 10, 2009 (gmt 0)

10+ Year Member



Hi Guys,

I am having problems using the following method to open the default mail client using a javascript function.

It works fine in IE + chrome but not in firefox (nothing happens when clicked):

function openemail() {

document.location = "mailto:martyn@example.com;"

}

<li><a href="javascript:openemail();"><img src="images/linkimage.gif" /></a></li>

Can anyone explain why this might be occurring? and hopefully point me in the right direction. All help most appreciated!

[edited by: eelixduppy at 4:36 pm (utc) on Feb. 10, 2009]
[edit reason] disabled smileys [/edit]

Fotiman

6:02 pm on Feb 10, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Welcome to WebmasterWorld! With regards to your question, it seems to work just fine in Firefox. Below is the code sample I used. However, it's worth noting that:
1. There's no need for JavaScript here. All you've done is made it so that users with JavaScript disabled will not be able to send mail. Do you perhaps have JavaScript disabled in Firefox?
2. There is no "javascript:" protocol, so href="javascript:..." is invalid. You should instead use the onclick event (but in this particular case, you shouldn't be using JavaScript at all in my opinion).

Here's the code I used that worked:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled</title>
</head>
<body>
<div>
<ul>
<li><a href="javascript:openemail();">There is not "javascript:" protocol</a></li>
<li><a href="mailto:martyn@example.com">This is the right way to do it</a></li>
<li><a href="mailto:martyn@example.com" id="emailLink">This is another way to do it</a></li>
</ul>
</div>
<script type="text/javascript">
function openemail() {
document.location = "mailto:martyn@example.com;"
}
window.onload = function () {
// Attach event handler
var el = document.getElementById('emailLink');
el.onclick = function () {
document.location = el.href;
return false; // this prevents the href from being followed
}
};
</script>
</body>
</html>

The 2nd and 3rd links will work for those with or without JavaScript enabled.

[edited by: Fotiman at 6:04 pm (utc) on Feb. 10, 2009]

martynrlee

5:05 pm on Feb 11, 2009 (gmt 0)

10+ Year Member



Thanks very much Fotiman, very useful.