0

What is the difference between the top two lines of javascript here?

HTML:

<html>

    <body>

        <form>

            <input type="button" value="one" id="one" />
            <input type="button" value="two" id="two" />

        </form>

        <script type="text/javascript" language="javascript" src="example.js"></script>

    </body>

</html>

javascript:

document.getElementById('one').onclick = one();
document.getElementById('two').onclick = function() {two();}


function one(){
    alert('this pops up before the button is clicked. Afterwards, the button doesn\'t work.');
}

function two(){
    alert('this pops up appropriately when the button is clicked.');
}

Popone display before the page loads, then the button becomes unusable. Popup two display when the second button is clicked and works appropriately.

Dagoth
  • 9
  • 1
  • 6
  • 2
    possible duplicate of [What is the difference between a function call and function reference?](http://stackoverflow.com/questions/15886272/what-is-the-difference-between-a-function-call-and-function-reference) – dsgriffin Apr 18 '14 at 03:31

1 Answers1

0

The difference is how you are passing the function to the onclick event. When you do =one(); it immediately evaluates the function and executes it. When you do function(){two();} instead, it waits until the click to execute the anonymous function that executes two(); If instead, you do ="one();" then it should work the same.

Helpful
  • 702
  • 4
  • 16
  • 1
    I'm not quite sure I understand, could you elaborate a little? What do you mean by "anonymous function"? – Dagoth Apr 18 '14 at 03:31
  • The "anonymous function" is the `function(){two();}` because it doesn't get a name. The compiler "evaluates" that - and knows how to execute it for the button click. When the compiler tries to evaluate just `one()` it ends up executing it. Putting `one();` into a string, like `"one();"` will make the compiler evaluate it only when the button is clicked. – Helpful Apr 18 '14 at 03:33
  • Glad to hear I was (removes shades) helpful! If you can, accept the answer or give an a +1 (click the up arrow next to my answer) to show appreciation. Cheers! – Helpful Apr 18 '14 at 03:37
  • Thanks! I can't upvote you yet, but I accepted your answer as soon as it let me! – Dagoth Apr 18 '14 at 03:44