2

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.

1 Answer 1

6

Remove the parenthesis from the function name (doing so invokes it):

document.getElementById("clickMe").onclick = bar;

jsFiddle example

Sign up to request clarification or add additional context in comments.

1 Comment

-_- I guessed it was a syntax error, didn't think it would be that simple. Thanks.

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.