tlaverdure
tlaverdure

Reputation: 522

jQuery Repeat Element with A Following Number

How do I use less code here? I do not want to repeating the same steps for each element.

$('.slider1').stop().hover(function () {
    $('#slider_1').fadeIn('fast');
});
$('.slider1').stop().mouseleave(function () {
    $('#slider_1').hide('fast');
});

$('.slider2').stop().hover(function () {
    $('#slider_2').fadeIn('fast');
});
$('.slider2').stop().mouseleave(function () {
    $('#slider_2').hide('fast');
});

$('.slider3').stop().hover(function () {
    $('#slider_3').fadeIn('fast');
});
$('.slider3').stop().mouseleave(function () {
    $('#slider_3').hide('fast');
});

Upvotes: 2

Views: 122

Answers (1)

ShankarSangoli
ShankarSangoli

Reputation: 69905

Try this

$.each([1,2,3,4], function(i, val){
    $('.slider' + val).stop().hover(function(){
          $('#slider_' + val).fadeIn('fast');
    }, 
    function(){
        $('#slider_' + val).hide('fast');
    });
});

Upvotes: 3

Related Questions