I am trying to create a mailto button, where it creates the title and body of an email.
My code does its job correctly but I realised if the letter '&' is in the text, then the rest of the code is skipped. so the string is visible until '&', and anything after that will not be in the email body.
Have a look a the example: jsFiddle
var title = "my track title";
var artist= "ArtistA & Artist B";
var trackURL= " http://localhost/music";
var subjectText = title + " by " + artist;
var bodyText = "Check out the track " + title + " by " + artist + " on " + trackURL;
var url = 'mailto:' + '' + '?subject=' + subjectText + '&body=' + bodyText;
$(".email").on("click tap", function(event) {
event.preventDefault();
window.location = url;
});
console.log(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="email">Send Email</button>
In the console it is shown correctly but if you pres the button and open the it in an email application you see that the text is like: Check out the track my track title by ArtistA
and the rest is missing.
If I change '&' to 'and' it works correctly and shows: Check out the track my track title by ArtistA and Artist B on http:/localhost/music
Any idea how to fix it? i tried .toString()
but did not work.
That is because &
is the separator character of the url parameters.
You need to encode you values (encodeURIComponent
for the texts and encodeURI
for the url) before adding them to the url string.
var title ="my track title";
var artist= "ArtistA & Artist B";
var trackURL= " http://localhost/music";
var subjectText = encodeURIComponent(title + " by " + artist);
var bodyText = encodeURIComponent("Check out the track " + title + " by " + artist + " on ") + encodeURI(trackURL);
var url = 'mailto:' + '' + '?subject=' + subjectText + '&body=' + bodyText;
$(".email").on("click tap", function(event) {
event.preventDefault();
window.location = url;
});
console.log(url);