Search code examples
javascripthtmlformsbootstrap-5

How to Add Tooltips to Bootstrap 5 Floating Labels Form?


Is it possible to add tooltips or popovers to Bootstrap 5 floating labels text?

I have a form that uses floating form fields and I want to add instructions to certain form fields using the tooltip or popovers functionality. I can get it to work on the standard form implementation (non-floating), but not when I use floating labels.

Can this be done? How?

<div class="form-floating">
   <input type="email" class="form-control" id="floatingInput" placeholder="[email protected]">
   <label for="floatingInput">
      Email address <button href="#" class="btn badge text-bg-primary" type="button" data-bs-toggle="tooltip" title="Tooltip Title!">Tooltip</button>
   </label>
</div>

Solution

  • Add the pe-auto class to the <label> or the element with the tooltip (in this case, the <button>) to allow pointer events.

    new bootstrap.Tooltip(document.querySelector('[data-bs-toggle="tooltip"]'));
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
    <div class="form-floating">
      <input type="email" class="form-control" id="floatingInput" placeholder="[email protected]">
      <label for="floatingInput">
          Email address <button class="btn badge text-bg-primary pe-auto" type="button" data-bs-toggle="tooltip" title="Tooltip Title!">Tooltip</button>
      </label>
    </div>