Step 9: refresh button

Refreshing the post list

Thanks to code we added in the previous step, we only refresh the list when a user posts a new message.

Let's add a button to manually refresh the whole list.

8.1 – The refresh button's HTML

In the head add:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css">

And right after the <body> tag add:

<button type="button" class="btn btn-secondary" id="refresh-button" style="position: fixed; top: 0; right: 0;">
  <i class="bi-arrow-repeat" style="font-size: 2rem;"></i>
</button>

In order to give the button a nicer look, we make use of Bootstrap icons.

The inline style anchors the button to the top-right corner of the screen, even when the page is scrolled.

8.2 – The refresh button's javascript

Let's add a console.log() statement in the refreshMessages function, so that we can see the function being called when the user clicks the button.

console.log('refresh');

Let's move now to the end of the script, where we add the click handler to the button.

First of all, we get the reference to the refresh button with the good old document.querySelector:

var refreshButton = document.querySelector('#refresh-button');

Then we define the handler for the click event, in a similar way we did for the form's submit event. Inside the handler function we simply call the refreshMessages function.

refreshButton.onclick = function() {
  refreshMessages();
}

Last updated