Conditional Bootstrap tooltip

I have this very simple Javascript code:

$("#myinput").hover(function(){
    if(condition){
        $(this).tooltip({placement: "bottom", title: "mytitle"}); 
    }
);

with its HTML:

<input data-toggle="tooltip" type="password" placeholder="Enter your Password" id="myinput" name="password" required />

When I load the page the condition it’s false so the tooltip correctly doesn’t show and when it becomes true it starts showing. The problem is that when the condition goes back to false the tooltip keeps showing when hovering even if it shouldn’t. How can I fix this?

>Solution :

You will need to add an else statement for your false condition and call $(this).tooltip("dispose"); to get rid of the tooltip. Otherwise tooltip will always be enabled.

Bootstrap 5 documentation on #dispose and all its tooltip methods.

Small demo of toggling tooltip.

let condition = true;

$("#myinput").hover(function () {
    if (condition) {
        $(this).tooltip({ placement: "bottom", title: "mytitle" });
    } else {
        $(this).tooltip("dispose");
    }
});

const button = document.querySelector("#button");
button.addEventListener("click", function () {
    condition = !condition;
    if (condition) {
        button.textContent = "Turn Tooltip Off";
    } else {
        button.textContent = "Turn Tooltip On";
    }
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap@latest/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@latest/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-toggle="tooltip" type="password" 
       placeholder="Enter your Password" 
       id="myinput" name="password" 
       required />


<button id="button">Turn Tooltip Off</button>

Leave a Reply