JavaScript can be utilized to eliminate bootstrap tooltip attributes

Having trouble with adding and removing bootstrap tooltip attributes using JavaScript. The tooltip is added on mouseover, but not removed on mouseleave.

The script adds the tooltip attributes on mouseover and should remove them on mouseleave.

'use strict'

document.addEventListener("DOMContentLoaded", function () {
    // Function to get element font
    const getfont = (element, property) => {
        return window
            .getComputedStyle(element, null)
            .getPropertyValue(property)
    }
  
    // Function to get element ID
    const getId = (obj) => {
        return obj.id
    }
  
    // Add or remove tooltip
    const addTooltip = (element) => {
        element.setAttribute("data-bs-toggle", "tooltip")
        element.setAttribute("data-bs-placement", "bottom")
        element.setAttribute("data-bs-title", "Tooltip on top")
        new bootstrap.Tooltip(element)
        console.log(`Tooltip added`)

        // Remove the tooltip when the mouse leaves the element
        element.addEventListener("mouseleave", (event) => {
            const element = event.target

            element.removeAttribute("data-bs-toggle");
            element.removeAttribute("data-bs-placement");
            element.removeAttribute("data-bs-title");
            
            new bootstrap.Tooltip(element);
            console.log(`Removed`)

        })
    }

    // Event listeners
    addEventListener("mouseover", (event) => {
        console.log(getId(event.target));
    })

    addEventListener("mouseover", (event) => {
        const element = event.target
        const id = getId(element)
        if (id) {
            addTooltip(element)
        }
    })
})

Answer №1

Your code is encountering an issue with how tooltips are handled. Each time a mouseover event occurs, a new tooltip instance is created without explicitly showing it, resulting in multiple instances being generated for the same element. Similarly, during a mouseleave event, instead of disposing of the existing tooltip instance, the code attempts to create yet another tooltip.

The corrected code rectifies this by displaying the tooltip post-initialization using tooltipInstance.show(). Furthermore, during the mouseleave event, it properly disposes of the existing tooltip instance, ensuring not only its concealment but complete removal.

document.addEventListener('DOMContentLoaded', function () {
  const addTooltip = (element) => {
    element.setAttribute('data-bs-toggle', 'tooltip');
    element.setAttribute('data-bs-placement', 'bottom');
    element.setAttribute('data-bs-title', 'Tooltip on top');

    const tooltipInstance = new bootstrap.Tooltip(element);
    tooltipInstance.show();
    console.log(`Tooltip added`);

    element.addEventListener('mouseleave', (event) => {
      const element = event.target;

      const tooltip = bootstrap.Tooltip.getInstance(element);
      if (tooltip) {
        tooltip.dispose();
      }
      console.log('Removed');
    });
  };

  document.addEventListener('mouseover', (event) => {
    const element = event.target;
    const id = element.id;
    if (id) {
      addTooltip(element);
    }
  });
});

For convenience, here's a sample snippet that you can copy and paste to test and debug the functionality on your own workstation:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Tooltip Test</title>
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8defe2e2f9fef9ffecfdcdb8a3bfa3be">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afcdc0c0dbdcdbddcedfef9a819d819c">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>

<div class="container mt-5">
  <button id="btn-test" class="btn btn-primary">Hover over me!</button>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const addTooltip = (element) => {
    element.setAttribute('data-bs-toggle', 'tooltip');
    element.setAttribute('data-bs-placement', 'bottom');
    element.setAttribute('data-bs-title', 'Tooltip on top');

    const tooltipInstance = new bootstrap.Tooltip(element);
    tooltipInstance.show();
    console.log(`Tooltip added`);

    element.addEventListener('mouseleave', (event) => {
      const element = event.target;

      const tooltip = bootstrap.Tooltip.getInstance(element);
      if (tooltip) {
        tooltip.dispose();
      }
      console.log('Removed');
    });
  };

  document.addEventListener('mouseover', (event) => {
    const element = event.target;
    const id = element.id;
    if (id) {
      addTooltip(element);
    }
  });
});
</script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the Popover appears in ShadCN, the input field unexpectedly takes focus

This unique component incorporates both Popover and Input functionality from shadcn. An issue I have encountered is that when I click on the Input to trigger the Popover, the Input loses focus and the cursor moves away from it. Expected outcome: Upon c ...

Validating a particular value using Regex in React Formik

First, I need to ensure that the field is validated for any characters not included in this set: /[ùûüÿ€’“”«»–àâæçéèêëïîôœ]/. If a user enters a character outside of this set, I want Yup to trigger an error message. Secondly, I ...

Arrow functions do not function properly with Typescript decorators

I've created a typescript decorator factory that logs the total time taken to execute a function, along with the actual function execution results and parameters passed to the decorator. For example: export function performanceLog(...args: any[]) { ...

What is the process of encrypting a password using AngularJS on the client side, transferring it securely to the server through ExpressJS, and then decrypting it on the server

Looking for a simple method to encrypt a password on the client side using angular.js, send it to the server with express.js, and then decrypt it? While there are libraries like angular-bcrypt and similar ones in nodeJS, they may not be suitable as they ma ...

Having difficulty accessing the ::after element on Firefox when attempting to click

I've encountered an issue with my HTML and CSS code - it functions perfectly on Chrome, yet behaves differently on Firefox. button#groupToggle { background: 0 0; border: 1px solid #e6e6ed; color: #222; float: none; margin: 0 0 ...

Having trouble resolving '@auth0/nextjs-auth0' during deployment on Vercel? Check out this error message: "Can't resolve '@auth0/nextjs-auth0' in '/vercel/path0/pages'"

I recently deployed a project on Vercel and have been working on enhancing the layout to achieve a minimum viable product (MVP). As part of this process, I decided to switch my authentication method to @auth0/nextjs-auth0 package for Next.js. After running ...

The error message that appeared states: "TypeError Object[object object] does not have the SubSelf method, TypeError Object[object object] does not

As I delved into a WebGL project, leveraging the powerful Sim.js and Three.js libraries, an unexpected obstacle emerged: At a certain point, within the code, the constructor for THREE.Ray is utilized in this manner: var ray = new THREE.Ray( this.camera.p ...

Searching within a container using jQuery's `find` method can sometimes cause jQuery to lose control

I am trying to extract information from an input field within a table in a specific row. Here is the code I am using: var myElements = $('#myTable tbody').find('tr'); console.log(myElements); This correctly displays the items in the ...

Encrypting sensitive information in JavaScript and Angular 2: SecureString

Is there a way to securely copy sensitive data to the clipboard in javascript/Angular2, ensuring that the string remains confidential by removing it from computer memory when no longer needed? In Microsoft .Net, there is a feature called System.Security.S ...

Is it necessary to implement clustering for each route in an Express.js application?

Currently, I am utilizing the cluster module to fork my application within my index.js, which serves as the primary file in the root directory of my website. My application consists of numerous routes. Should I incorporate the cluster code to encapsulate a ...

How to best handle dispatching two async thunk actions in Redux Toolkit when using TypeScript?

A recent challenge arose when attempting to utilize two different versions of an API. The approach involved checking for a 404 error with version v2, and if found, falling back to version v1. The plan was to create separate async thunk actions for each ver ...

Identifying Inactivity in Cordova Android Applications

Hey there! So, I've created a flashlight/torch app that can be found at the following link: https://github.com/Skelware/Fancy-Flashlight. This app utilizes a Cordova plugin available here: https://github.com/Skelware/Cordova-Flashlight. For now, my m ...

When async/await is employed, the execution does not follow a specific order

I'm curious about the execution of async/await in JavaScript. Here are some example codes: async function firstMethod(){ new Promise((resolve, reject)) => { setTimeout(() => { resolve("test1"); }, 3000); }); } async ...

What measures can be taken to guarantee that a user is only able to delete designated records?

When it comes to writing SQL commands directly, it's simple to specify which records to delete using identifiers like ID. However, when dealing with webpages that contain a list of links pointing to different records (with the ID embedded as a query ...

How can I stop json_encode() from including the entire page in the JSON response when submitting a form to the same PHP script?

I only have a single index.php file in my project. I am aware that it's recommended to separate the logic from the view and use different files for PHP, JS, and HTML. This is just a test: <?php if($_SERVER["REQUEST_METHOD"] == "P ...

Attempting to modify the information within the #content division of a webpage through the activation of a linked image within a jquery slideshow

I'm completely stuck on this one, even though I'm relatively new to jquery. My goal is to design a webpage where there is a slideshow of products at the top, and when a user clicks on one of the products, it should update the main #content div w ...

Parsing of the module failed due to an unexpected character appearing when trying to insert a TTF file into the stylesheet

As a newcomer to Angular, I recently completed the tutorial and am now working on my first app. While trying to add an OTF file, everything went smoothly. However, when I made a change to my app.component.css file and included this code snippet: @font-fa ...

Divide the sentence using unique symbols to break it into individual words, while also maintaining

Is there a way to split a sentence with special characters into words while keeping the spaces? For example: "la sílaba tónica es la penúltima".split(...regex...) to: ["la ", "sílaba ", "tónica ", "es ", "la ", "penúltima"] ↑ ...

What are the steps to effectively implement the useEffect hook in React?

I'm facing an issue where I am trying to return a function that utilizes useEffect from a custom usehook, but I keep getting the error "useEffect is called in a function which is neither a react function component nor a custom hook." Here's what ...

Having trouble locating the correct JSON array syntax for Highcharts

Hey there! I'm currently facing a bit of a challenge while trying to set up a JSON array using PHP and integrate it into Highcharts. Currently, I am creating the array in this manner: $stack[] = array($commname => $countit); $stack = json_encode( ...