# Simplifying multiple mouseover and mouseout functions

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.

$('.remove').eq(0).mouseover(function(){$('.tooltip').eq(0).show();
});

$('.remove').eq(0).mouseout(function(){$('.tooltip').eq(0).hide();
});

$('.remove').eq(1).mouseover(function(){$('.tooltip').eq(1).show();
});

$('.remove').eq(1).mouseout(function(){$('.tooltip').eq(1).hide();
});
• What is the HTML for .remove and .tooltip, how are they related in the DOM? – John Koerner Jul 12 '12 at 14:25

Use an .each "loop":

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

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

$('.remove').mouseout(function(){$(\$(this).attr("data-ref")).hide();
});
</script>

there's room for improvement but should help.

Happy coding!

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.