views:

57

answers:

5

Once #theButton is clicked, an alert should be triggered. Why aren't any of the events being triggered using the following methods? Thanks in advance.

  <html>
     <head>
      <script type="text/javascript" language="javascript">

       var theButton = document.getElementById("theButton");

       theButton.onclick = function(){alert("Clicked!");}
       theButton.onclick = clickAlert;
       theButton.onclick(alert("Clicked!"));

       function clickAlert(){
        alert("Clicked!");
       }
      </script>
     </head>
     <body>
      <input type="button" id="theButton">
     </body>
    </html>
+1  A: 

Because theButton doesn't exist yet when you run your script?

Wrap it into the body's onload event or jQuery's ready().

Pekka
jQuery's `ready()` is a wrapper for `DOMContentLoaded` event, not `laod` event.
Crozin
@Crozin I know, but IIRC, getting `DOMContentLoaded` without jQuery across browsers was awfully difficult. Still, you are right.
Pekka
@Pekka - What do you mean by does not exist yet?
Babiker
@Babiker at the point the Javascript is executed, the DOM isn't rendered by the browser yet, so you can't access any elements in the DOM.
Pekka
+1  A: 

Try wrapping it in the document.Ready() function.

Brandon
That doesn't necessarily exist - the OP is not using jQuery.
Pekka
+2  A: 

You have three problems

  1. You misspell function on line 7. (This generates a runtime error, by the way)
  2. You try to access the node #theButton before it's available in the DOM. Take Pekka's advice for this one
  3. You overwrite the onclick property on line 8 - not sure if you're doing that on purpose or what
Peter Bailey
+1  A: 

I like the jQuery.ready() answer, but I believe you could also move the <script> block to some point afeter you delcalre the button like at the end of the page.

Seattle Leonard
... or use the `onload` event.
Pekka
+1  A: 

It works if you put the onclick within the input tag (and spell things right):

<html>
     <head>
      <script type="text/javascript" language="javascript">



       function clickAlert(){
        alert("Clicked!");       

       }

      </script>
     </head>
     <body>
      <input type="button" id="theButton" NAME="theButton" onclick="clickAlert()">
     </body>
    </html>
Tommy