Search code examples
javascripthtmleventsinlineinline-code

why don't inline events with function names work on divs?


I feel like this is such a noob question but I cannot for the life of me figure it out.

http://jsfiddle.net/37pj3bro/5/

<div onclick="dingo()">click me</div>
<div onclick="alert(this)">click me 2</div>

<script type="text/javascript">
function dingo()
{
    alert("hi");
}
</script>

The first click me does not alert but the second one does. I can't figure out why....


Solution

  • The code in your question works fine:

    <div onclick="dingo()">click me</div>
    <div onclick="alert(this)">click me 2</div>
    
    <script type="text/javascript">
    function dingo()
    {
        alert("hi");
    }
    </script>

    The code in JS fiddle doesn't work because you've configured it so dingo is not a global.

    Screenshot