Search code examples
jqueryfunctionmouseoverjquery-hovermouseout

How can this be shortened?


Have several hotspots by ID. The ID specific hotspots show an area (#ID-ed textarea) at mouseover and then hide the textareas at mouseout (note the CSS display:hidden was remarkably faster than hide). Have about 50. I have written this out verbosely - aka a function for every one.

Would like to learn a better, wiser, efficient, and shorter way to do this.

    //// POP 1_1
$('#pop_01_01').hover(
    function() {
    $('#text_01_01.textarea').fadeIn('fast');          
    },
    function() {
    $('#text_01_01.textarea').css({'display':'none'});
    }
);
//// POP 02_01
$('#pop_02_01').hover(
    function() {
    $('#text_02_01.textarea').fadeIn('fast');          
    },
    function() {
    $('#text_02_01.textarea').css({'display':'none'});
    }
);
//// POP 02_01
$('#pop_02_02').hover(
    function() {
    $('#text_02_02.textarea').fadeIn('fast');          
    },
    function() {
    $('#text_02_02.textarea').css({'display':'none'});
    }
);
//// POP 02_03
$('#pop_02_03').hover(
    function() {
    $('#text_02_03.textarea').fadeIn('fast');          
    },
    function() {
    $('#text_02_03.textarea').css({'display':'none'});
    }
);

Solution

  • You can do the following:

    1. Combine all the objects that have this behavior into one jQuery selector so they can all run the same code.
    2. Remove the textarea from the selector since the ids are unqiue anyway so it isn't needed and should be faster without it.
    3. Extract the id you want from the object's id that is being hovered and grab the ending characters so you can use it to create the other id you want.
    4. Use .hide() instead of .css({'display':'none'}); as a built-in shortcut.

    Resulting Code:

    $('#pop_01_01, #pop_02_01, #pop_02_02').hover(
        function() {$('#text_' + this.id.substr(-5)).fadeIn('fast');},
        function() {$('#text_' + this.id.substr(-5)).hide();}
    );