DEV Community

Cover image for How to create confirm box using TippyJS
Milan Tarami
Milan Tarami

Posted on

How to create confirm box using TippyJS

Tippy.js is the complete tooltip, popover, dropdown, and menu solution for the web, powered by Popper.

Javascript default confirm box also works well but UX matters. In this example, I am showing the easiest way to create eye pleasant confirm box with a great user experience.

You can check out the below example in JS Fiddle

In this example I'm using TailwindCSS (a utility-first CSS framework) to style the document

Add this code to your head tag

<!-- TippyJS CDN -->
<script src="https://unpkg.com/@popperjs/core@2"></script>
<script src="https://unpkg.com/tippy.js@6"></script>

<!-- TailwindCSS CDN -->
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
Enter fullscreen mode Exit fullscreen mode

Let's add an HTML button element, on the click event of this button a confirm box must appear.

<button type="button" class="bg-red-600 px-2 py-1 rounded-md text-white">
Trash
</button>
Enter fullscreen mode Exit fullscreen mode

Let's add hidden HTML content for a custom confirm box innerHTML content.

<div id="template" class="hidden">
   <form action="http://myurl.domain/id" method="POST">
   </form>
   <div class="confirm__box p-3">
      <div class="confirm__text text-center mb-4">
         <strong>Are you sure ?</strong>
         <p>
            You won't able to revert this back.
         </p>
      </div>
      <div class="confirm__action flex justify-between">
         <button class="ok-btn w-10 text-white bg-green-600 px-1 rounded-sm">
         Yes
         </button>
         <button class="cancel-btn w-10 text-white bg-red-600 px-1 rouneded-sm">
         No
         </button>
      </div>
   </div>
</div>
Enter fullscreen mode Exit fullscreen mode

initialize button with tippyJS

const template = document.getElementById('template');
tippy('button', {

    content: template.innerHTML,
    allowHTML: true,
    theme: 'material',
    interactive: true,
    zIndex: 99999,
    placement: 'auto',
    trigger: 'click',
});
Enter fullscreen mode Exit fullscreen mode

adding submit or cancel functionality

    onCreate(instance) {
        instance.popper.querySelector('.cancel-btn').onclick = () => {
            instance.hide();
        }

        instance.popper.querySelector('.ok-btn').onclick = () => {
            instance.hide();
            instance.popper.querySelector('form').submit();
            alert('form submitted')
        }
    }
Enter fullscreen mode Exit fullscreen mode

You can check out the below example in JS Fiddle

Top comments (0)