1

I'd like to know why my code doesn't work.I'm just trying to change the height attribute from '1000' to '2' Here's the code:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<canvas id="canv" width="1000" height="1000" onclick="click()" onmousemove=""></canvas>
<script type="text/javascript">
function click(){
    var l = document.getElementById("canv");
    l.height = "2";

}
</script>
</body>
</html>

1 Answers1

1

You've called your handler click. onxyz-style attribute handlers are executed in an environment that has the element itself mixed into scope, so click in your handler refers to the click on the canvas itself, not the global function. So your global function isn't being called.

If you use a different name, you don't have the conflict, and the global function is called:

function clickCanvas(){
    console.log("Got here");
    var l = document.getElementById("canv");
    l.height = "2";
}
<canvas id="canv" width="1000" height="1000" onclick="clickCanvas()" onmousemove=""></canvas>

I strongly recommend not using onxyz-attribute-style handlers, though, not least because they rely on global functions, and globals are a Bad Thing™. Instead, hook up your handler with modern event handling, which in addition to playing nicely with others wouldn't have had the name conflict problem you had. It also lets you use this in the handler to refer to the element on which you hooked the event:

document.getElementById("canv").addEventListener("click", function() {
    console.log("Got here");
    this.height = "2";
}, false);
<canvas id="canv" width="1000" height="1000"></canvas>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Ive been doing js for many many years, and never once have I picked up that you cant name the function the same as the event when using `onxyz` markup. I had to double check this with jsfiddle to quite believe it! – Jamiec Sep 20 '16 at 11:09
  • 1
    @Jamiec: Trust your uncle T.J... ;-) *(Trust...but verify.)* – T.J. Crowder Sep 20 '16 at 12:27