# Reducing code for animation of expanding menus

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


@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'); }); }  • ahh right!! I didn't notice, he is using multiple function argument of hover method!! this code is right – azerafati Oct 15 '14 at 13:35 • Thank you Konijn but your code don't work ^^ – Flocon Oct 15 '14 at 14:22 • That is possible, present us with a working example with snippet or jsbin and we can present 100% working code. The idea of code review is too provide a review, not necessarily to provide the working code. But out of courtesy, if you provide a working snippet we tend to always provide you actually working code. – konijn Oct 15 '14 at 17:15 of course you can, I guess this would do it: $(function() {
for (var index = 0; index < 6; index++) {
$('#menu-'+index+', #menu-event-'+index).hover(function () { stomAnim($('#menu-deco-'+index),true);
stomAnim( $('#menu-deco-'+index),false); }); } function stomAnim (obj,odd){ obj.stop().animate({ right: odd?0:-280 }, 'fast'); } });  • Thank you a lot but it does not work :'( – Flocon Oct 15 '14 at 11:13 • Change $('#menu-'+index+', to \$('#menu-'+index,. That should do it. – Abbas Oct 15 '14 at 11:27
• @Abbas Does not work – Flocon Oct 15 '14 at 12:22
• @Flocon, don't just say it does not work!! tell us what error you get?? or post a code from jsfiddle.net – azerafati Oct 15 '14 at 13:02
• so it means, code is correct! but you strategy is wrong, as I said send a jsfiddle – azerafati Oct 15 '14 at 13:33