MDP MDP - 7 months ago 43
HTML Question

How to pass variable to a Jquery function

I'm new to JQuery, and I'm trying to use a function found on the internet that shows a tooltip when you over a HTML element.

This is the function:

<script>
$(document).ready(function() {
$('#my-tooltip').tooltipster({
content: $('<span>This text is in bold case !</span>')
});
});
</script>

<img src="img.jpg" id="my-tooltip">


Let's say that I want to apply this function to many elements on the page, for example:

<img src="img1.jpg" id="my-tooltip1">
<img src="img2.jpg" id="my-tooltip2">
<img src="img3.jpg" id="my-tooltip3">


How should I edit the the function? I can't do

<img src="img.jpg1" id="my-tooltip1" onmouseover="javascript:functionName('tooltip1')" onmouseout="javascript:functionName('tooltip1')">


since ths function will not work the way it works now.

Thank you

Answer

As already suggested, use a CSS class to select your tooltip-enabled elements.

The text of the tooltip can be parametrized with a custom data- attribute.

$(document).ready(function() {
  $('.tooltip').each(function() {
    $(this).tooltipster({
      content: $(this).attr("data-tooltip")
    });
  });
});
.tooltip {
  cursor: help;
  height:100px;
  width:100px;
}
.tooltipster-base {
  display: inline-block;
  border: 1px solid #222;
  margin: 0;
  padding: 2px 4px;
  background: #ccc;
  border-radius:2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://grid.turtlespeak.net/upload/LMo6pu2bZ3pYC5QU/iH3dtwYF1tOwoBd8/jquery.tooltipster.min.js"></script>
<img class="tooltip" data-tooltip="I am a unicorn!" src="https://s-media-cache-ak0.pinimg.com/originals/e3/ab/d2/e3abd2c3b64151e4c1dfe59e5a2227dc.jpg">
<img class="tooltip" data-tooltip="Look at me!" src="http://cartoon-animals.disneyimage.com/_/rsrc/1367525874171/cartoon-unicorn-clipart/Unicorn-Clipart_7.png">
<img class="tooltip" data-tooltip="I poop rainbows" src="http://grid.turtlespeak.net/upload/LMo6pu2bZ3pYC5QU/iH3dtwYF1tOwoBd8/un1.png">