Kristen
Kristen

Reputation: 31

I can't figure out why my simple attempt at adding an event handler isn't working

I'm trying to add a click event to a button on my web page. Its a simple button created with a tag and I set the id attribute to "button1". In the javascript code, I used getElementById to store the button in the variable btn and used the onClick method to add the click event. The function is basic and only displays an alert box.Simple, right?

But for some reason, clicking the button doesn't do anything. I don't see where I went wrong. I double checked my spelling everywhere, so it isn't a typo. Did I miss a step somewhere?

  <html>
    <head>
      <title>Add Event Handler</title>
    <head>
    <body>
      <h1>Add Event Handler</h1>

      <button id="button1">Click Me</button>

      <script>
        function test(){
          alert("The event handler was set.");
        }

        var btn = document.getElementById("button1");
        btn.onClick = test;
     </script>
 </body>

Upvotes: 3

Views: 41

Answers (2)

Phil
Phil

Reputation: 164744

Ideally, you should be using EventTarget.addEventListener()

btn.addEventListener('click', test, false)

Upvotes: 0

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93173

    btn.onclick = test;

not

    btn.onClick = test;

  <html>
    <head>
      <title>Add Event Handler</title>
    <head>
    <body>
      <h1>Add Event Handler</h1>

      <button id="button1">Click Me</button>

      <script>
        function test(){
          alert("The event handler was set.");
        }

        var btn = document.getElementById("button1");
        btn.onclick = test;
     </script>
 </body>

Upvotes: 4

Related Questions