Search⌘ K
AI Features

Clear Messages

Explore how to add a clear button to your Firebase chat application that deletes all messages in real time. Learn to set up event listeners, perform Firestore queries to retrieve and remove message documents, and handle promises in JavaScript for asynchronous operations. This lesson equips you to manage message data efficiently within your chat app.

Set Up Your Clear Button

We start by creating an HTML button. We will add an id to it so we can attach an event listener.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://www.gstatic.com/firebasejs/6.3.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.3.0/firebase-firestore.js"></script>
</head>
<body>
<div id="container">
<div id="user-options">
<div>Chatting as: <span id="name"></span></div>
<div id="change-name">change name</div>
</div>
<form id="message-form">
<input type="text" id="message-input" placeholder="message" required>
<button class="orange-button">send</button>
</form>
<div id="messages"></div>
<button id="clear" class="purple-button">Clear All Messages</button>
</div>
</body>
</html>

Make an Event Listener

Since it’s a button, the event we want to listen for is click.

Javascript (babel-node)
document.querySelector('#clear').addEventListener('click', () => {
})

Place the Firestore Query Into the Click Event

To delete, we ...