DenaliHardtail DenaliHardtail - 10 months ago 43
Javascript Question

How do I setup a callback on a button?

I have a page with the following:

<div id="container">
<input id="myButton" type=button'LandingPage.html'); value="Launch Search App">

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

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?


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

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

or call the function within an anonymous function.

    function callback(msg) { console.log(msg); }