I am trying to hide and show tooltips depending on what element is hovered over. This works as expected and I could continue to rinse and repeat. However, I am wondering if there is a good way to simplify this or make it more compact. Also I was assuming I could use .hover(), but that didn't seem to work for me. So instead I am using mouseover and mouseout.




  • \$\begingroup\$ What is the HTML for .remove and .tooltip, how are they related in the DOM? \$\endgroup\$ – John Koerner Jul 12 '12 at 14:25

Use an .each "loop":

var tooltips = $('.tooltip');

$('.remove').each(function(i) {
    var tooltip = tooltips.eq(i);

        mouseover: function() { tooltip.show(); },
        mouseout:  function() { tooltip.hide(); }
| improve this answer | |
  • \$\begingroup\$ @KrisHollenbeck: No problem! Some more details about the ever-useful each can be found here: api.jquery.com/each \$\endgroup\$ – Ry- Jul 12 '12 at 14:36
  • \$\begingroup\$ Isn't an each loop unnecessary? Why just attach to all .remove elements at once? Like this. \$\endgroup\$ – iambriansreed Jul 12 '12 at 14:40
  • \$\begingroup\$ @anonymousdownvotingislame: Please see all my other comments about why index won't work. \$\endgroup\$ – Ry- Jul 12 '12 at 15:18
  • \$\begingroup\$ Also, I agree with @anonymousdownvotingislame's username. A comment when you downvote me would be much appreciated, random person. \$\endgroup\$ – Ry- Jul 12 '12 at 15:54
  • \$\begingroup\$ I see no comments regarding index()? \$\endgroup\$ – iambriansreed Jul 12 '12 at 15:59

If i'm not totally wrong try referencing your target through a custom attribute on the trigger:

<div id="tooltip1" style="display:none">TOOLTIP 1 CONTENT</div>
<div id="tooltip2" style="display:none">TOOLTIP 2 CONTENT</div>
<div id="tooltip3" style="display:none">TOOLTIP 3 CONTENT</div>

<a href="javascript:;" class="remove" data-ref="#tooltip1">TRIGGER 1</a>
<a href="javascript:;" class="remove" data-ref="#tooltip2">TRIGGER 2</a>
<a href="javascript:;" class="remove" data-ref="#tooltip3">TRIGGER 3</a>

<script type="text/javascript">


there's room for improvement but should help.

Happy coding!

| improve this answer | |

Have a single mouse move event handler that tracks the element id it's currently on and set the tooltip based on it. For improved performance you could instead poll mouse's position every say 500 ms and set the tooltip based on that.

You would have a single function to manage all your tooltips in a switch(){} block of code with a "default" case that sets the tooltip to empty.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.