Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading