Javascript onclick event triggering on page load - Stack Overflow

I have the following htmljavascript:<div id="clickMe" style="width:200px;height:100p

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 ment 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.

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 ment 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.

Share Improve this question asked Dec 2, 2013 at 3:26 James G.James G. 2,9044 gold badges29 silver badges55 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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

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

jsFiddle example

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745144667a4613592.html

相关推荐

  • Javascript onclick event triggering on page load - Stack Overflow

    I have the following htmljavascript:<div id="clickMe" style="width:200px;height:100p

    2小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信