DenaliHardtail DenaliHardtail - 3 months ago 9
Javascript Question

How do I setup a callback on a button?

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?

Answer

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>