2

problem: the page executes the javascript onclick propertise before get clicked. here is my code

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>demo</title>
<meta charset="UTF-8"/>
</head>
<body>
<h1 id="demo">Hello World!</h1>
<script>
var x = document.getElementById("demo");
x.onclick = alert("clicked");
</script>
</body>
</html>

solution: when I change the line x.onclick = alert("clicked"); to x.onclick = function() {alert("clicked")}; It works. I want to understand the reason behind this behavior of onclick.

2 Answers 2

2

The reason for that behaviour is, that you simply make a function call and when the JavaScript interpreter comes to that line it will be directly executed. You need to implement a reference to a function or a function definition itself to avoid this (as you did in your solution).

x.onclick = myMethod() // NOT working due to directly execution
x.onclick = () => myMethod() // working
x.onclick = myMethod // working
x.onclick = function() { myMethod() } // working 
Sign up to request clarification or add additional context in comments.

Comments

0

I f you write the code this way also works same

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>demo</title>
<meta charset="UTF-8"/>
</head>
<body>
<script>
var x; 
x.onclick = alert("clicked");
</script>
</body>
</html>

SO your code not understand where you try to send this alert so automatically display so that's not a good way If you try to display alert when clicked on text then do this method

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>demo</title>
<meta charset="UTF-8"/>
</head>
<body>
    <h1 id="demo" >Hello world!</h1>
<script>

document.getElementById('demo').onclick = function(){
    alert("clicked");
}
</script>
</body>
</html>

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.