1

I have created two tooltips with jQuery. I only want the content of the clicked tooltip to be shown and not both the tooltip content at once when either is clicked. This is because I don't have an attribute assigned to the tooltip that is being clicked I guess. I'm new to jQuery so I tried to only add a class when the .tooltip is clicked, and it then shows all the hidden .tooltip-text.

I'm doing this in WordPress so switched out the $ for jQuery. I would also like to hide the .tooltip-text when you click outside the .tooltip but haven't really figured that out either so if someone wants to help with that, it would be appreciated.

I tried to create a tooltip with a hidden checkbox and a hidden content that gets shown when someone clicks on a tooltip

This is how I have it now for one tooltip:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  <i class="fas fa-info-circle tooltip">
  <span class="tooltiptext"> 
   Some content that gets shown when hovered or clicked
  </span>
 </i>
</p>
jQuery(function() {
  jQuery('.tooltip').click(function() {
    jQuery('.tooltiptext').addClass("tooltip-clicked");
  })
})
.tooltip {
  position: relative;
  display: inline-block;
}

.tooltip:hover .tooltiptext {
  opacity: 1;
  visibility: visible;
  transition: all .25s;
}

.tooltiptext {
  position: absolute;
  z-index: 1;
  opacity: 0;
  visibility: collapse;
  transition: all .25s;
  pointer-events: none;
}

.tooltip-clicked {
  /*  When tooltip is clicked this style gets added to it */
  visibility: visible !important;
  opacity: 1 !important;
  pointer-events: all !important;
  cursor: auto !important;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Krullmizter
  • 529
  • 8
  • 28

2 Answers2

1

(Posted answer on behalf of the question author).

Got it working now thanks to @Rory McCrossan.

This is the jQuery now:

jQuery(function(){
 jQuery('.tooltip').click(function (){
  jQuery(this).find('.tooltiptext').addClass("tooltip-clicked");
 })
})
halfer
  • 19,824
  • 17
  • 99
  • 186
0
jQuery(function() {
jQuery('.tooltip').click(function() {
  $(this).children('.tooltiptext').addClass("tooltip-clicked");
})
jQuery('body').click(function(e) {
  if(e.target.className !="tooltiptext"){
     $(".tooltiptext").removeClass("tooltip-clicked");
  }
})
})

Above code snippet will work for you. The problem you faced is that you were adding the active class on all elements. What it does in this code snippet is that it only add the active class on the child of the clicked element.

Anoxy
  • 873
  • 7
  • 17