0

I have a page with the following:

<body>
    <div id="container">
        <p>
            <input id="myButton" type=button onclick=window.open('LandingPage.html'); value="Launch Search App">
        </p>
    </div>

    <script>
        function callback(msg) { console.log(msg); }
        myButton.addEventListener('click', callback(msg));
    </script>
</body>

This page displays a button that when clicked launches a second page where the user performs some searching and data manipulation functions.

The addEventListener on this page is intended to add a callback function to the onClick event of the button. My intent was to setup the callback when the user clicks the button to launch the secondary page and let the first page wait for the secondary page to send a response to the callback.

When I run the above as-is, I get a message indicating msg is undefined. The secondary page should respond to the callback with msg so in this context, yes, msg is undefined.

What do I need to do in order to setup this callback function on the button's click event?

DenaliHardtail
  • 27,362
  • 56
  • 154
  • 233
  • `setTimeout` in the title is a red herring, the issues are the same so be sure to read the answers on the other question. – zzzzBov Aug 24 '16 at 16:29

2 Answers2

1

You need to set function reference as argument not the executed result.

<script>
    function callback() { console.log(msg); }
    myButton.addEventListener('click', callback);
</script>


or call the function within an anonymous function.
<script>
    function callback(msg) { console.log(msg); }
    myButton.addEventListener('click',function(){
       callback('msg');
    });
</script>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

this

myButton.addEventListener('click', callback(msg));

should be

document.getElementById("myButton".addEventListener('click', callback(msg));

check your console

barha
  • 709
  • 1
  • 7
  • 22