Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

why does it not work

<button onclick="myFunction();" id="myd">save</button>

<script> function myFunction(){ var email = prompt("whats your email"); document.getElementById("myd").href = "mailto:" + email + "?subject=Cabbages"; } </script>

2 Answers

Hi Mully,

Changing the href attribute of a button doesn't make sense since buttons don't have href attributes. If you want to open the mail client after filling the email prompt you could use:

<button onclick="myFunction();" id="myd">save</button>

<script> 
  function myFunction(){ 
    var email = prompt("whats your email"); 
    window.location.href = "mailto:" + email + "?subject=Cabbages"; 
  } 
</script>

I am not sure what your function is trying to do that it is not working, I ran your code with an additional function as a callback to check its functionality:

function myFunction(checkHref) { 
  var email = prompt("whats your email"); 
  document.getElementById("myd").href = "mailto:" + email + "?subject=Cabbages"; 
  checkHref();
} 

checkHref = () => {
  console.log(document.getElementById("myd").href);
}

On clicking the button, the href attribute is maybe updating too late for what you need. If you are using this data or transferring the value synchronously, the href value is not updating before you use it. In my code above, the checkHref() function is running before the href is updated which will cause the console to log whatever the last value for href was of "myd".

To fix this, a delay needs to exist between when it's set and when it's used.