addEventListener calls the function without me even asking it to









up vote
8
down vote

favorite
4












So we have a page:



<span id='container'>
<a href='#' id='first'>First Link</a>
<a href='#' id='second'>Second Link</a>
</span>


And want to add some click events:



first.addEventListener('click', function()alert('sup!');)


Works like a charm! However, when you make the second argument an external function:



function message_me(m_text)
alert(m_text)


second.addEventListener('click', message_me('shazam'))


It calls the function immediately. How can I stop this? So annoying!



Here's a live demo: http://jsfiddle.net/ey7pB/1/










share|improve this question

















  • 1




    Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined). Either call the function in an anonymous function (like your first example) or alter the function to return a function (probably not ideal).
    – Ian
    Apr 30 '13 at 23:17







  • 1




    Why is this not ideal? It seems against D.R.Y. to copypasta my function in the 4 or so addEventListeners that im setting, no?
    – LittleBobbyTables
    Apr 30 '13 at 23:20











  • Another option is to store the required message as an attribute on the element, then bind the function as second.addEventListener('click', message_me) and have it retrieve the message from the attribute rather than from a parameter.
    – nnnnnn
    Apr 30 '13 at 23:23










  • Possible duplicate of How to pass parameter to function using in addEventListener?
    – Xufox
    Jun 20 '16 at 3:46














up vote
8
down vote

favorite
4












So we have a page:



<span id='container'>
<a href='#' id='first'>First Link</a>
<a href='#' id='second'>Second Link</a>
</span>


And want to add some click events:



first.addEventListener('click', function()alert('sup!');)


Works like a charm! However, when you make the second argument an external function:



function message_me(m_text)
alert(m_text)


second.addEventListener('click', message_me('shazam'))


It calls the function immediately. How can I stop this? So annoying!



Here's a live demo: http://jsfiddle.net/ey7pB/1/










share|improve this question

















  • 1




    Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined). Either call the function in an anonymous function (like your first example) or alter the function to return a function (probably not ideal).
    – Ian
    Apr 30 '13 at 23:17







  • 1




    Why is this not ideal? It seems against D.R.Y. to copypasta my function in the 4 or so addEventListeners that im setting, no?
    – LittleBobbyTables
    Apr 30 '13 at 23:20











  • Another option is to store the required message as an attribute on the element, then bind the function as second.addEventListener('click', message_me) and have it retrieve the message from the attribute rather than from a parameter.
    – nnnnnn
    Apr 30 '13 at 23:23










  • Possible duplicate of How to pass parameter to function using in addEventListener?
    – Xufox
    Jun 20 '16 at 3:46












up vote
8
down vote

favorite
4









up vote
8
down vote

favorite
4






4





So we have a page:



<span id='container'>
<a href='#' id='first'>First Link</a>
<a href='#' id='second'>Second Link</a>
</span>


And want to add some click events:



first.addEventListener('click', function()alert('sup!');)


Works like a charm! However, when you make the second argument an external function:



function message_me(m_text)
alert(m_text)


second.addEventListener('click', message_me('shazam'))


It calls the function immediately. How can I stop this? So annoying!



Here's a live demo: http://jsfiddle.net/ey7pB/1/










share|improve this question













So we have a page:



<span id='container'>
<a href='#' id='first'>First Link</a>
<a href='#' id='second'>Second Link</a>
</span>


And want to add some click events:



first.addEventListener('click', function()alert('sup!');)


Works like a charm! However, when you make the second argument an external function:



function message_me(m_text)
alert(m_text)


second.addEventListener('click', message_me('shazam'))


It calls the function immediately. How can I stop this? So annoying!



Here's a live demo: http://jsfiddle.net/ey7pB/1/







javascript addeventlistener






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Apr 30 '13 at 23:12









LittleBobbyTables

1,45452245




1,45452245







  • 1




    Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined). Either call the function in an anonymous function (like your first example) or alter the function to return a function (probably not ideal).
    – Ian
    Apr 30 '13 at 23:17







  • 1




    Why is this not ideal? It seems against D.R.Y. to copypasta my function in the 4 or so addEventListeners that im setting, no?
    – LittleBobbyTables
    Apr 30 '13 at 23:20











  • Another option is to store the required message as an attribute on the element, then bind the function as second.addEventListener('click', message_me) and have it retrieve the message from the attribute rather than from a parameter.
    – nnnnnn
    Apr 30 '13 at 23:23










  • Possible duplicate of How to pass parameter to function using in addEventListener?
    – Xufox
    Jun 20 '16 at 3:46












  • 1




    Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined). Either call the function in an anonymous function (like your first example) or alter the function to return a function (probably not ideal).
    – Ian
    Apr 30 '13 at 23:17







  • 1




    Why is this not ideal? It seems against D.R.Y. to copypasta my function in the 4 or so addEventListeners that im setting, no?
    – LittleBobbyTables
    Apr 30 '13 at 23:20











  • Another option is to store the required message as an attribute on the element, then bind the function as second.addEventListener('click', message_me) and have it retrieve the message from the attribute rather than from a parameter.
    – nnnnnn
    Apr 30 '13 at 23:23










  • Possible duplicate of How to pass parameter to function using in addEventListener?
    – Xufox
    Jun 20 '16 at 3:46







1




1




Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined). Either call the function in an anonymous function (like your first example) or alter the function to return a function (probably not ideal).
– Ian
Apr 30 '13 at 23:17





Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined). Either call the function in an anonymous function (like your first example) or alter the function to return a function (probably not ideal).
– Ian
Apr 30 '13 at 23:17





1




1




Why is this not ideal? It seems against D.R.Y. to copypasta my function in the 4 or so addEventListeners that im setting, no?
– LittleBobbyTables
Apr 30 '13 at 23:20





Why is this not ideal? It seems against D.R.Y. to copypasta my function in the 4 or so addEventListeners that im setting, no?
– LittleBobbyTables
Apr 30 '13 at 23:20













Another option is to store the required message as an attribute on the element, then bind the function as second.addEventListener('click', message_me) and have it retrieve the message from the attribute rather than from a parameter.
– nnnnnn
Apr 30 '13 at 23:23




Another option is to store the required message as an attribute on the element, then bind the function as second.addEventListener('click', message_me) and have it retrieve the message from the attribute rather than from a parameter.
– nnnnnn
Apr 30 '13 at 23:23












Possible duplicate of How to pass parameter to function using in addEventListener?
– Xufox
Jun 20 '16 at 3:46




Possible duplicate of How to pass parameter to function using in addEventListener?
– Xufox
Jun 20 '16 at 3:46












3 Answers
3






active

oldest

votes

















up vote
8
down vote



accepted










function message_me(m_text)
alert(m_text)


second.addEventListener('click',
function()
message_me('shazam');

);


Here's an updated fiddle.






share|improve this answer






















  • Boom! Thanks. Will accept this answer when SO lets me :D
    – LittleBobbyTables
    Apr 30 '13 at 23:16










  • I think you should update your accepted answer because passing the function without calling it, and bind - is probably a better choice here.
    – IonicBurger
    Nov 2 '16 at 14:53






  • 1




    Can you explain why you think bind is a better choice?
    – clav
    Nov 2 '16 at 16:07

















up vote
10
down vote













Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined...because all the function does is alert and doesn't return anything). Either call the function in an anonymous function (like your first example) or alter the function to return a function.



You can do this:



function message_me(m_text)
alert(m_text);


second.addEventListener('click', function ()
message_me('shazam')
);


or this:



function message_me(m_text)
return function ()
alert(m_text);
;


second.addEventListener('click', message_me('shazam'));


DEMO: http://jsfiddle.net/tcCvw/






share|improve this answer





























    up vote
    7
    down vote













    or you can use .bind



    function message_me(m_text)
    alert(m_text);


    second.addEventListener('click', message_me.bind(this, 'shazam'));


    check MDN Documentation
    about 'closures'






    share|improve this answer




















    • This should be the accepted answer
      – IonicBurger
      Nov 2 '16 at 14:51










    • +1 binding should be the way to go — not sure if that was available 4 years ago, but is definitely the preferred way to today, as opposed to creating an anonymous function
      – vol7ron
      Mar 7 '17 at 0:40











    • Nice suggestion for the bind, definitely should be the accepted answer. Can OP change?
      – blueprintchris
      May 31 at 10:50










    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f16310423%2faddeventlistener-calls-the-function-without-me-even-asking-it-to%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    8
    down vote



    accepted










    function message_me(m_text)
    alert(m_text)


    second.addEventListener('click',
    function()
    message_me('shazam');

    );


    Here's an updated fiddle.






    share|improve this answer






















    • Boom! Thanks. Will accept this answer when SO lets me :D
      – LittleBobbyTables
      Apr 30 '13 at 23:16










    • I think you should update your accepted answer because passing the function without calling it, and bind - is probably a better choice here.
      – IonicBurger
      Nov 2 '16 at 14:53






    • 1




      Can you explain why you think bind is a better choice?
      – clav
      Nov 2 '16 at 16:07














    up vote
    8
    down vote



    accepted










    function message_me(m_text)
    alert(m_text)


    second.addEventListener('click',
    function()
    message_me('shazam');

    );


    Here's an updated fiddle.






    share|improve this answer






















    • Boom! Thanks. Will accept this answer when SO lets me :D
      – LittleBobbyTables
      Apr 30 '13 at 23:16










    • I think you should update your accepted answer because passing the function without calling it, and bind - is probably a better choice here.
      – IonicBurger
      Nov 2 '16 at 14:53






    • 1




      Can you explain why you think bind is a better choice?
      – clav
      Nov 2 '16 at 16:07












    up vote
    8
    down vote



    accepted







    up vote
    8
    down vote



    accepted






    function message_me(m_text)
    alert(m_text)


    second.addEventListener('click',
    function()
    message_me('shazam');

    );


    Here's an updated fiddle.






    share|improve this answer














    function message_me(m_text)
    alert(m_text)


    second.addEventListener('click',
    function()
    message_me('shazam');

    );


    Here's an updated fiddle.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited May 1 '13 at 0:58

























    answered Apr 30 '13 at 23:14









    clav

    3,4731933




    3,4731933











    • Boom! Thanks. Will accept this answer when SO lets me :D
      – LittleBobbyTables
      Apr 30 '13 at 23:16










    • I think you should update your accepted answer because passing the function without calling it, and bind - is probably a better choice here.
      – IonicBurger
      Nov 2 '16 at 14:53






    • 1




      Can you explain why you think bind is a better choice?
      – clav
      Nov 2 '16 at 16:07
















    • Boom! Thanks. Will accept this answer when SO lets me :D
      – LittleBobbyTables
      Apr 30 '13 at 23:16










    • I think you should update your accepted answer because passing the function without calling it, and bind - is probably a better choice here.
      – IonicBurger
      Nov 2 '16 at 14:53






    • 1




      Can you explain why you think bind is a better choice?
      – clav
      Nov 2 '16 at 16:07















    Boom! Thanks. Will accept this answer when SO lets me :D
    – LittleBobbyTables
    Apr 30 '13 at 23:16




    Boom! Thanks. Will accept this answer when SO lets me :D
    – LittleBobbyTables
    Apr 30 '13 at 23:16












    I think you should update your accepted answer because passing the function without calling it, and bind - is probably a better choice here.
    – IonicBurger
    Nov 2 '16 at 14:53




    I think you should update your accepted answer because passing the function without calling it, and bind - is probably a better choice here.
    – IonicBurger
    Nov 2 '16 at 14:53




    1




    1




    Can you explain why you think bind is a better choice?
    – clav
    Nov 2 '16 at 16:07




    Can you explain why you think bind is a better choice?
    – clav
    Nov 2 '16 at 16:07












    up vote
    10
    down vote













    Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined...because all the function does is alert and doesn't return anything). Either call the function in an anonymous function (like your first example) or alter the function to return a function.



    You can do this:



    function message_me(m_text)
    alert(m_text);


    second.addEventListener('click', function ()
    message_me('shazam')
    );


    or this:



    function message_me(m_text)
    return function ()
    alert(m_text);
    ;


    second.addEventListener('click', message_me('shazam'));


    DEMO: http://jsfiddle.net/tcCvw/






    share|improve this answer


























      up vote
      10
      down vote













      Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined...because all the function does is alert and doesn't return anything). Either call the function in an anonymous function (like your first example) or alter the function to return a function.



      You can do this:



      function message_me(m_text)
      alert(m_text);


      second.addEventListener('click', function ()
      message_me('shazam')
      );


      or this:



      function message_me(m_text)
      return function ()
      alert(m_text);
      ;


      second.addEventListener('click', message_me('shazam'));


      DEMO: http://jsfiddle.net/tcCvw/






      share|improve this answer
























        up vote
        10
        down vote










        up vote
        10
        down vote









        Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined...because all the function does is alert and doesn't return anything). Either call the function in an anonymous function (like your first example) or alter the function to return a function.



        You can do this:



        function message_me(m_text)
        alert(m_text);


        second.addEventListener('click', function ()
        message_me('shazam')
        );


        or this:



        function message_me(m_text)
        return function ()
        alert(m_text);
        ;


        second.addEventListener('click', message_me('shazam'));


        DEMO: http://jsfiddle.net/tcCvw/






        share|improve this answer














        Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined...because all the function does is alert and doesn't return anything). Either call the function in an anonymous function (like your first example) or alter the function to return a function.



        You can do this:



        function message_me(m_text)
        alert(m_text);


        second.addEventListener('click', function ()
        message_me('shazam')
        );


        or this:



        function message_me(m_text)
        return function ()
        alert(m_text);
        ;


        second.addEventListener('click', message_me('shazam'));


        DEMO: http://jsfiddle.net/tcCvw/







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 30 '13 at 23:42

























        answered Apr 30 '13 at 23:26









        Ian

        39.2k118097




        39.2k118097




















            up vote
            7
            down vote













            or you can use .bind



            function message_me(m_text)
            alert(m_text);


            second.addEventListener('click', message_me.bind(this, 'shazam'));


            check MDN Documentation
            about 'closures'






            share|improve this answer




















            • This should be the accepted answer
              – IonicBurger
              Nov 2 '16 at 14:51










            • +1 binding should be the way to go — not sure if that was available 4 years ago, but is definitely the preferred way to today, as opposed to creating an anonymous function
              – vol7ron
              Mar 7 '17 at 0:40











            • Nice suggestion for the bind, definitely should be the accepted answer. Can OP change?
              – blueprintchris
              May 31 at 10:50














            up vote
            7
            down vote













            or you can use .bind



            function message_me(m_text)
            alert(m_text);


            second.addEventListener('click', message_me.bind(this, 'shazam'));


            check MDN Documentation
            about 'closures'






            share|improve this answer




















            • This should be the accepted answer
              – IonicBurger
              Nov 2 '16 at 14:51










            • +1 binding should be the way to go — not sure if that was available 4 years ago, but is definitely the preferred way to today, as opposed to creating an anonymous function
              – vol7ron
              Mar 7 '17 at 0:40











            • Nice suggestion for the bind, definitely should be the accepted answer. Can OP change?
              – blueprintchris
              May 31 at 10:50












            up vote
            7
            down vote










            up vote
            7
            down vote









            or you can use .bind



            function message_me(m_text)
            alert(m_text);


            second.addEventListener('click', message_me.bind(this, 'shazam'));


            check MDN Documentation
            about 'closures'






            share|improve this answer












            or you can use .bind



            function message_me(m_text)
            alert(m_text);


            second.addEventListener('click', message_me.bind(this, 'shazam'));


            check MDN Documentation
            about 'closures'







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jun 19 '16 at 18:42









            Sehyun Kim

            7112




            7112











            • This should be the accepted answer
              – IonicBurger
              Nov 2 '16 at 14:51










            • +1 binding should be the way to go — not sure if that was available 4 years ago, but is definitely the preferred way to today, as opposed to creating an anonymous function
              – vol7ron
              Mar 7 '17 at 0:40











            • Nice suggestion for the bind, definitely should be the accepted answer. Can OP change?
              – blueprintchris
              May 31 at 10:50
















            • This should be the accepted answer
              – IonicBurger
              Nov 2 '16 at 14:51










            • +1 binding should be the way to go — not sure if that was available 4 years ago, but is definitely the preferred way to today, as opposed to creating an anonymous function
              – vol7ron
              Mar 7 '17 at 0:40











            • Nice suggestion for the bind, definitely should be the accepted answer. Can OP change?
              – blueprintchris
              May 31 at 10:50















            This should be the accepted answer
            – IonicBurger
            Nov 2 '16 at 14:51




            This should be the accepted answer
            – IonicBurger
            Nov 2 '16 at 14:51












            +1 binding should be the way to go — not sure if that was available 4 years ago, but is definitely the preferred way to today, as opposed to creating an anonymous function
            – vol7ron
            Mar 7 '17 at 0:40





            +1 binding should be the way to go — not sure if that was available 4 years ago, but is definitely the preferred way to today, as opposed to creating an anonymous function
            – vol7ron
            Mar 7 '17 at 0:40













            Nice suggestion for the bind, definitely should be the accepted answer. Can OP change?
            – blueprintchris
            May 31 at 10:50




            Nice suggestion for the bind, definitely should be the accepted answer. Can OP change?
            – blueprintchris
            May 31 at 10:50

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f16310423%2faddeventlistener-calls-the-function-without-me-even-asking-it-to%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

            Museum of Modern and Contemporary Art of Trento and Rovereto