javascripthtmltwitter-bootstraptwitter-bootstrap-tooltip

Bootstrap tooltip feature not working even after initializing in js


My custom tooltip wasn't displaying at all so I striped my document down to the bare bones and actually plucked an example from the bootstrap website. It still won't work.

https://jsfiddle.net/swagat123/pwzs397b/2/

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
  </head>
  <body>
    <script>
        const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
        const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
        // const exampleEl = document.getElementById('example');
        // const tooltip = new bootstrap.Tooltip(exampleEl, options);
        
        //Tried this; didn't work:
        // $(function () {
        //     $('[data-toggle="tooltip"]').tooltip()
        // })

    </script>
    <h1>Hello, world!</h1>

    <button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Tooltip on top">
        Tooltip on top
      </button>
      <button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-title="Tooltip on right">
        Tooltip on right
      </button>
      <button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Tooltip on bottom">
        Tooltip on bottom
      </button>
      <button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="left" data-bs-title="Tooltip on left">
        Tooltip on left
      </button>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
  </body>
</html>```


Tried bunch of different examples and different ways of initializing to no avail. I need a tooltip to pop up. 

Solution

  • The selector is running before the HTML is loaded, so no tooltip elements are found and initialized. If you run it after the window has loaded, it works:

    <script>
    window.addEventListener('load', function(){
      const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
      const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
    })
    </script>
    

    Alternatively, you could move the block to the end of the document.