Riantori
Riantori

Reputation: 317

how to simplify jquery animation function code

i have two function to make some animation efect , how to shorthand this function and change it to simple code ?

   $('.box-1').hover(function() {
    $('.box-1').stop().animate({bottom:'0'});
    $('.dul-1').stop().animate({top:'0px'});
},
function() {
  $('.box-1').stop().animate({bottom:'-100px'});
  $('.dul-1').stop().animate({top:'-100px'});
   });

$('.box-2').hover(function() {
    $('.box-2').stop().animate({bottom:'0'});
    $('.dul-2').stop().animate({top:'0px'});
},
function() {
  $('.box-2').stop().animate({bottom:'-100px'});
  $('.dul-2').stop().animate({top:'-100px'});
   });

fiddle link

Upvotes: 1

Views: 41

Answers (1)

Nishit Maheta
Nishit Maheta

Reputation: 6031

check my updated FIDDLE .add data-index attribute to .box div. so when hover event call script will get index using $(this).attr('data-index');.

HTML :

<div class="wrapper">
  <div class="dul-1"></div>
  <div class="dul-2"></div>
  <div class="box box-1" data-index="1"></div>
  <div class="box box-2" data-index="2"></div>
</div>

Javascript :

$('.box').hover(function() {
    index = $(this).attr('data-index');
    $('.box-'+index).stop().animate({bottom:'0'});
    $('.dul-'+index).stop().animate({top:'0px'});
 },
 function() {
    $('.box-'+index).stop().animate({bottom:'-100px'});
    $('.dul-'+index).stop().animate({top:'-100px'});
   }
 );

Upvotes: 3

Related Questions