HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Simplifying multiple mouseover and mouseout functions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mouseovermultiplesimplifyingandfunctionsmouseout

Problem

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();
});

Solution

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(); }
    });
});

Code Snippets

var tooltips = $('.tooltip');

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

    $(this).on({
        mouseover: function() { tooltip.show(); },
        mouseout:  function() { tooltip.hide(); }
    });
});

Context

StackExchange Code Review Q#13570, answer score: 6

Revisions (0)

No revisions yet.