2
<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>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Atheus
  • 94
  • 1
  • 7

1 Answers1

5

This is because you didnt wrap the onclick assignment as an actual function, so it attempts to assign the result of alert('clicked') to the onclick event handler (which means it's probably undefined when assigned). What you need to do is assign a function to that handler like so:

document.getElementById('specialp').onclick = function()
{
    alert('clicked');
};

When you do the same thing in HTML, the DOM automatically wraps that content in a function for you.

Tejs
  • 40,736
  • 10
  • 68
  • 86
  • Isn't alert() a function itself? Does that imply that if, somehow, alert() returned true this approach would work? Plus, why is it executed after the page loads? – Atheus Apr 27 '12 at 18:30
  • `alert` is a function, but you're not assigning it that function, you're assigning the expression `alert('clicked')` to the onclick object. The expression is evaluated as part of the assignment. What you did is technically no different than `var x = 4 + 2`. The script runs on load, and would assign 6 to `x`, not at some later point when `x` is used. – Tejs Apr 27 '12 at 18:36
  • If I wanted to use some attribute of the element in the function, how would I pass the object in an argument to that function, and what would it be like? I'm using this for all elements on the page, so I can't use the getElementById() function. – Atheus Apr 27 '12 at 18:53
  • `this` would be the context of the calling element for the function. IE: `function() { alert(this.id); }` – Tejs Apr 27 '12 at 18:56
  • var x=document.getElementsByTagName("a"); for(i=0;x[i]!=null;i++) {x[i].onclick=function() {alert(this.href);this.preventDefault();this.stopPropagation();};} Could you please tell me the reason for this not to work? – Atheus Apr 27 '12 at 19:06
  • Define 'not work' - Are you talking about the alert constantly displaying the same thing? – Tejs Apr 27 '12 at 19:07
  • Sorry, I meant the default event prevention. – Atheus Apr 27 '12 at 19:08
  • You can always just `return false` - it means the same as `preventDefault` + `stopPropagation`. – Tejs Apr 27 '12 at 19:12
  • Works. Thank you, that's all I needed to know for now. – Atheus Apr 27 '12 at 19:15