0
<script>
var el = document.getElementById('btn');
e1.onclick=function()
{
//
    alert('hello');
};
  </script>
  <button type="button" id="btn" >Log-in</button>

I am simply testing how unobstrusive javaScript works with a simple button onclick() event but when i click on the Log-in button nothing happens alert box doesn appears

rick
  • 913
  • 6
  • 13
  • 28
  • possible duplicate of [Why does jQuery or a DOM method such as \`getElementById\` not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Bergi May 01 '14 at 06:56

3 Answers3

3

Your script appears before the button.

It runs before the button is added to the DOM.

document.getElementById('btn') doesn't find the button because the button doesn't exist then.


Move the script after the button or put it in a function and call that function after the button exists (e.g. from the window's load event).


Also, don't rename your variables in the middle of your code. A lower case L and the numeral 1 aren't interchangeable.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • On line 2 you create a variable called `el` (eee el), on line 3 you try to use a variable called `e1` (eee one). – Quentin May 01 '14 at 08:36
1

The issue is you try to attach the handler before the element exists. <script> tags are executed immediately and so the browser hasn't created the button element at that time.

A solution would be to wrap it in window.onload:

window.onload = function(){
    var el = document.getElementById('btn');
    e1.onclick=function()
    {
    //
        alert('hello');
    };
};

Alternatively you can use the DOMContentLoaded event. This differs from onload because it doesn't wait for images and CSS to be loaded. It isn't supported by IE8 or lower though:

document.addEventListener("DOMContentLoaded", function(event) {
    console.log("ready to attach events");
});
MrCode
  • 63,975
  • 10
  • 90
  • 112
0

yes as said by above 2 answers you can wrap your code in window.onload else you can write a function and call it onclick event of button as shown below

function myfunction() {
  alert('Hello');
  };

<input type="button" onclick="myfunction()" value="Click Me!" />

http://jsfiddle.net/wf8yJ/13/

Neel
  • 11,625
  • 3
  • 43
  • 61