Event listeners allow us to execute [[JavaScript]] based on user input. For example, we might want to add a button that allows the user to write some data to the spreadsheet. This tutorial illustrates the use of event listeners in a [[base/Google Apps Script/Google Apps Script|Google Apps Script]] [[web app]].
First, create a button on the page in `index.html`.
```HTML title="index.html"
<body>
<h1>
<?= title; ?>
</h1>
<ul>
<?!= list ?>
</ul>
<button id = 'run'>
Run
</button>
</body>
```
Next, add the required JavaScript in a script tag index.html (located within the body tag below the button). You could also move this to your `JavaScript.html` file.
```HTML title="index.html"
<script>
document.getElementById('run').addEventListenter('click', logData);
function logData(){
google.script.run.userClicked();
}
</script>
```
We added an Event Listener to the button listening for the click event. Once the button is clicked, the `logData` function is run. The `logData` function will "call back" to the `Code.gs` file and run the `UserClicked` function in `Code.gs`, which could be:
```JavaScript title="Code.gs"
function userClicked(){
console.log("Someone Clicked the Button");
}
```
This will simply write to the log every time the button is clicked.
Often, all Event Listeners are included in a general Event Listener called `DOMContentLoaded` which listens for the page to load. This would look like this (in a script tag in `index.html`):
```HTML title="index.html"
<script>
document.AddEventListener('DOMContentLoaded', function(){
document.getElementById("run").addEventListener("click", logData)
///
})
///
</script>
```
> [!Warning]
> All of the code in `index.html` is visible to the world. You don't want to include anything sensitive in your html file. Instead, you should use the pattern above where we "call back" to the server-side code using `google.script.run` and run the function stored there. This does slow load times because the code has to round-trip to a server but is safer when interacting with your underlying spreadsheet.