Mayoco
Mayoco

Reputation: 87

onclick event handler not work

This is a example code in JavaScript: The Definitive Guide,6th Edition.

<button id="my button">click me</button>
<script>
var b = document.getElementById("my button");
b.onclick = fuction(){alert("Thanks for clicking me!");}; /*work well if I delete this parse*/
b.addEventListener ("click", function(){ alert("Thanks again!");}, false);
</script>

When I click the button, nothing happen.

Upvotes: 2

Views: 97

Answers (3)

Kelly Taylor
Kelly Taylor

Reputation: 56

Your button id can't have a space between the words. Use an underscore instead like <button id="my_button">click me</button>

Also, in your function call for your onclick you spelled function wrong.

See JSFiddle for working example: https://jsfiddle.net/us2dq8sz/

Upvotes: 1

are you sure you write well?

1 - Remove space on id value: change id="my button" to id="mybutton".

2 - is not fuction, is function.

<button id="mybutton">click me</button>
<script>
var b = document.getElementById("mybutton");
b.onclick = function(){alert("Thanks for clicking me!");}; /*work well if I delete this parse*/
b.addEventListener ("click", function(){ alert("Thanks again!");}, false);
</script>

Upvotes: 1

Anonymous Duck
Anonymous Duck

Reputation: 2978

Wrong spelling in this line

b.onclick = fuction(){alert("Thanks for clicking me!");}; /*work well if I delete this parse*/

fuction instead of function

Working version : https://jsfiddle.net/x46ugomj/

Upvotes: 0

Related Questions