El Dj El Dj - 6 months ago 42
CSS Question

How to make tooltip stay visible after cursor is no longer hovering it

I have a tooltip that I want it to be permanently visible if clicked on it and disappear when clicked again. Right now the code I wrote is working fine when you hover on and off the image.

Can anyone please help on making it stay visible on click and invisible on click again.

Here's my code:


.tooltip {
position: relative;
display: inline-block;
cursor: pointer;

.tooltip .tooltiptext {
visibility: hidden;
width: 285px;
background-color: black;
color: #fff;
text-align: left;
border-radius: 6px;
padding: 5px 10px;
position: absolute;
z-index: 1;
top: -23px;
right: 125%;

opacity: 0;
transition: opacity 1s;

.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 20%;
left: 100%;
margin-top: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent transparent transparent black;
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;


<div id = "help">
<div class="tooltip">
<img type = help src="help.png" alt = "Support">
<p class="tooltiptext">
<b>Support: </b> <br />


You would need a little javascript which you could do inline. The code below, toggles an attribute on the .tooltip div every time it is clicked.


<div id = "help" >
    <div class="tooltip" onclick="event.currentTarget.setAttribute('data-active', event.currentTarget.getAttribute('data-active') != 'true')">
    <img type=help src="help.png"/>
        <p class="tooltiptext">
            <b>Support:  </b> <br />

Then change your CSS to use the 'data-active' attribute instead of the hover pseudo-class. This will make the tooltiptext visible only when the .tooltip div has an attribute: data-active="true"


 .tooltip[data-active='true'] .tooltiptext {
      visibility: visible;
      opacity: 1; 

Here is a working fiddle: https://jsfiddle.net/ofpnr514/

NOTE: Inlining the javascript right in the HTML is generally not how you would want to do anything more complex. I did it inline here just to minimize the javascript. The javascript that is inline as the onclick="..." attribute, would be better as a separate JS function.

function toggleActive(event) {
            event.currentTarget.getAttribute('data-active') != 'true')

Then just call this method from your HTML