<p id="specialp">some content</p>
<script>
document.getElementById('specialp').onclick=alert('clicked');
</script>
I’m just starting out with Javascript, and I don’t understand why the alert is executed when page loads, but not when I click that paragraph.
The handler works as I expect when I put it inline, like this:
<p id="specialp" onclick="alert('clicked')" >some content</p>
This is because you didnt wrap the
onclickassignment as an actual function, so it attempts to assign the result ofalert('clicked')to the onclick event handler (which means it’s probablyundefinedwhen assigned). What you need to do is assign a function to that handler like so:When you do the same thing in HTML, the DOM automatically wraps that content in a function for you.