0

My HTML code is below: My question is, why does it show "before" dialog when clicking Button 1, but show "after" dialog when clicking Button 2?

<html>
    <body>
        <button id="b1">Button 1</button>
        <button id="b2" onclick="OnClick();">Button 2</button>

        <script>
            var OnClick = function(){alert("before");};
            document.getElementById("b1").addEventListener("click", OnClick);
            var OnClick = function(){alert("after");};
        </script>
    </body>
</html>

JSFiddle link: https://jsfiddle.net/72chrqnf/

Sarath Chandra
  • 1,850
  • 19
  • 40
william
  • 13
  • 3
  • @Ivar that's probably not the problem though. `OnClick` isn't being set to another value in the first place. – Luca Kiebel Oct 13 '18 at 12:15
  • 1
    @LucaKiebel I'm not sure I follow you. If a reference was passed instead of the value, the "after" would've been shown. But that is not the case here. – Ivar Oct 13 '18 at 12:19
  • Because this happens, step by step: 1. The page is loaded 2. The page is being parsed/evaluated 3. The – Nurbol Alpysbayev Oct 13 '18 at 12:21
  • @Ivar Thanks a lot. I understand now. – william Oct 13 '18 at 12:28

1 Answers1

0

Cause OnClick gets evaluated to the first function before you change the variable pointing to a different function. When this line gets evaluated:

  document.getElementById("b1").addEventListener("click", OnClick);

it evaluates OnClick and results in:

 document.getElementById("b1").addEventListener("click", [a reference pointing to the function])

and therefore changing OnClick does not affect it afterwards.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151