šŸ“• Build AI Agents using LangGraph.js is now out!

Adding a close icon for an HTML dialog

After publishing the short intro to the dialog element I've received an email asking how can we add a close icon to that icon.

I've made the below example to show how can we do this:
Adding a close icon for an HTML dialog

There are two ways to close an HTML dialog:

  1. programmatically, using the close() method of the dialog element
  2. using a submit button, without any extra Javascript. When a user submits the dialog form, the data is maintained. While there is a submit event it will go through constraint validation and therefore the user data is neither cleared nor submitted.

The HTML code will look like this:

<dialog id="my-dialog">
    <form method="dialog">
        <button type="submit">āŒ</button>
        <p>This dialog can be closed using both the <code>close()</code> method or using a <code>submit</code> button.</p>
        <a href="#" data-dialog-with-js>Close dialog using Javascript</a>
    </form>
</dialog>
<button data-open-dialog>Open the dialog</button>

And the needed JS code:

// open the dialog
const btnShowDialog = document.querySelector('[data-open-dialog]')
const dialog = document.querySelector('#my-dialog')
btnShowDialog.addEventListener('click', () => dialog.showModal())

// close the dialog with Javascript
const closeDialogWithJs = document.querySelector('[data-dialog-with-js]')
closeDialogWithJs.addEventListener('click', () => dialog.close())

You can play with the live example here and the full code is on my github.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

Your email address will not be published. Required fields are marked *