How to condense this into a single function?

61 views Asked by At

I am really new to JS/JQuery, I cant figure out how to keep this code D.R.Y, if its even possible at all I don't know. I am using JQuery for an on hover effect with an image. Box1 being the div and the img_hover_effect being the overlay on hover.

JS:

$('.box1').hover(function () {
    $('.img_hover_effect').fadeIn(500);
}, function () {
    $('.img_hover_effect').fadeOut(400);
});
$('.box2').hover(function () {
    $('.img_hover_effect_2').fadeIn(500);
}, function () {
    $('.img_hover_effect_2').fadeOut(400);
});
$('.box3').hover(function () {
    $('.img_hover_effect_3').fadeIn(500);
}, function () {
    $('.img_hover_effect_3').fadeOut(400);
});
4

There are 4 answers

8
Walter Chapilliquen - wZVanG On BEST ANSWER

You can use a loop to do that.

An anonymous function inside the loop is used to prevent breakage jQuery events, try:

for(var i = 1; i <= 3; i++){
    (function(num){
        $('.box' + num).hover(function() {
            $('.img_hover_effect' + (num == 1 ? "" : num)).fadeIn(500)
        }, function(){
            $('.img_hover_effect' + (num == 1 ? "" : num)).fadeOut(400)
        })
    })(i)
}

Demo

0
sfrutig On

How about:

function hover(div, overlay) {
    $(div).hover(function() {
        $(overlay).fadeIn(500);
    }, function() {
        $(overlay).fadeOut(400);
    });
}

Then you can call it for each div and overlay as follows:

hover('.box1', '.img_hover_effect');

So you have a function which can be used for fadeIn of 500ms and fadeOut of 400ms. If you would need different fadeIn- and fadeOut-intervalls, you could even adjust the function with these as additional parameters.

0
guest271314 On

Try combining selectors

$(".box1, .box2, .box3").hover(function (e) {
    $(".img_hover_effect_" + e.target.className.slice(-1)).fadeIn(500);
}, function (e) {
    $(".img_hover_effect_" + e.target.className.slice(-1)).fadeOut(400);
});
0
Tushar On

Use data attribute on .box elements to store the target element selector.

Also, add a same class to all the .boxn elements to bind event on all the elements.

HTML:

<div class="mybox box" data-target=".img_hover_effect"></div>
<div class="mybox box2" data-target=".img_hover_effect_2"></div>
<div class="mybox box3" data-target=".img_hover_effect_3"></div>

Javascript:

$('.mybox').hover(function () {
    $($(this).data('target')).fadeIn(500);
}, function () {
    $($(this).data('target')).fadeOut(400);
});