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

Reducing code for animation of expanding menus

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

Problem

I wonder if I can reduce the code to optimize it better?

$(document).ready(function () {
    $('#menu-1, #menu-event-1').hover(function () {
        $('#menu-deco-1').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-1').stop().animate({
            right: -280
        }, 'fast');
    });
    $('#menu-2, #menu-event-2').hover(function () {
        $('#menu-deco-2').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-2').stop().animate({
            right: -280
        }, 'fast');
    });
    $('#menu-3, #menu-event-3').hover(function () {
        $('#menu-deco-3').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-3').stop().animate({
            right: -280
        }, 'fast');
    });
    $('#menu-4, #menu-event-4').hover(function () {
        $('#menu-deco-4').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-4').stop().animate({
            right: -280
        }, 'fast');
    });
    $('#menu-5, #menu-event-5').hover(function () {
        $('#menu-deco-5').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-5').stop().animate({
            right: -280
        }, 'fast');
    });
});

Solution

@Bludream came quite close, he noticed the code that was copy pasted, turned the common parts into a function, and then he used a loop to execute everything. The error is in doing both animations on the hover event. This should work:

var mouseLeaveAnimation = { right: -280 };
var mouseEnterAnimation = { right: 0 };

for(var i = 1; i < 6; i++) {

  $('#menu-' + i + ', #menu-event-' + i).hover(function() {
    $('#menu-deco-' + i).stop().animate(mouseEnterAnimation, 'fast');
  }, function() {
    $('#menu-deco-' + i).stop().animate(mouseLeaveAnimation, 'fast');
  });
}

Code Snippets

var mouseLeaveAnimation = { right: -280 };
var mouseEnterAnimation = { right: 0 };

for(var i = 1; i < 6; i++) {

  $('#menu-' + i + ', #menu-event-' + i).hover(function() {
    $('#menu-deco-' + i).stop().animate(mouseEnterAnimation, 'fast');
  }, function() {
    $('#menu-deco-' + i).stop().animate(mouseLeaveAnimation, 'fast');
  });
}

Context

StackExchange Code Review Q#66749, answer score: 2

Revisions (0)

No revisions yet.