Javascript onclick event triggering on page load
javascript
Solution
Remove the parenthesis from the function name (doing so invokes it):
document.getElementById("clickMe").onclick = bar;
jsFiddle example
Problem
I have the following html/javascript: ``` <div id="clickMe" style="width:200px;height:100px;background-color:red;"> click me </div> <script> function bar(){ alert("foo"); } document.getElementById("clickMe").onclick = bar(); </script> ``` When I load this page, the function triggers and the alert pops up, and then it doesn't trigger when I click `clickMe`. I tried switching the `div` out for a `button` and that worked fine (didn't trigger on page load, did trigger on click). When I comment out `document.getElementById("clickMe").onclick = bar();`, the function doesn't trigger at all. I also tried adding `onload` functions surrounding the whole thing, and just the function, and just the trigger, to no great effect. How do I trigger a javascript function by clicking on a div, and why is this not working? Thank you.