1

Why is simple JavaScript code not running ?

<script type="text/javascript" charset="utf-8">

var btn = document.getElementById("myBtn");
btn.onclick = function(){
alert("Clicked");
};
    
</script>

</head>


<body>
    
    <a id="myBtn" href="#">click me </a>
    
</body>
1
  • Does it work if you add return false; to the end of the function? And have you tried it on another browser? I have a feeling the alert's being blocked Commented May 23, 2011 at 2:17

3 Answers 3

2

Assign your onclick handler after document is loaded.

<script type="text/javascript" charset="utf-8">

function assignHandler() {
    var btn = document.getElementById("myBtn");
    btn.onclick = function() {
        alert("Clicked");
    };
}

</script>

<body onload="assignHandler()">
<a id="myBtn" href="#">click me </a>
</body>
Sign up to request clarification or add additional context in comments.

Comments

0

the order

<a id="myBtn" href="#">click me </a>
<script type="text/javascript" charset="utf-8">

var btn = document.getElementById("myBtn");
btn.onclick = function(){
alert("Clicked");
};

</script>

1 Comment

This worked, but what if the script is assigned to external file and included in header ?
0

Have a look at this. The javascript block needs to be after the html element:

Your code works but is better to use like this:

var btn =
document.getElementById('myBtn');
btn.addEventListener('click',function
(e) {   alert('my click works after the html element has been created');
},true);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.