Search code examples
javascripthtml

How do I register an event for a button in JavaScript?


I am making an HTML document for a javascript file. I want to use a button that will show the drawn rectangle, but I am still don't know fully on how would I code it. This is what my code looks like in HTML document. Also, when I open the html doc in FireFox, it does not show anything beside the title:

<!--Create a document that displays a drawn rectangle -->
<!DOCTYPE html>
<html lang="en">
<head>
    <title> myRectangle.html </title>
    <meta charset="utf-8"/>
    <script type="text/javascript" src="myRects.js"
    </script>
</head>
<body>
<h3>Drawing Rectangle</h3>
<form id="myCanvas" action="">
    <p>
        <button> type ="button">Draw Me</button>
    </p>
</form>
</body>
</html> 

This is what the JavaScript file looks like:

// myRects.js
// This script shows the use of the rectangle methods of the canvas
// element to draw two rectanges

function draw() {
    var dom = document.getElementById("myCanvas");
    if (dom.getContext) {
        var context = dom.getContext('2d');

        // Draw the outer filled rectangle
        context.fillRect(100, 100, 200, 200);

        // Clear a rectangle inside the first rectangle
        context.clearRect(150, 150, 100, 100);

        // Draw a stroke rectange
        context.strokeRect(180, 180, 40, 40);

        // Draw a small filled rectangle
        context.fillRect(195, 195, 10, 10);
    }
}

Solution

  • The reason only the title is shown is because you are missing a > after the opening tag of the script in the head: it should be like this:

    <script type = "text/javascript" src = "myRects.js">
    </script>
    

    to run draw() when the button is clicked, do something like this:

    <button id="click-to-draw"> Draw me </button>
    

    And inside your script (you will need to move the location of the script tag to underneath the button)

    document.getElementById("click-to-draw").addEventListener("click", function() {
    draw();
    });
    

    Update: I just realized that you can simplify this to just document.getElementById("click-to-draw").addEventListener("click", draw);