Question

I have a jquery animation script that is working properly, however, I feel like there is a way to reduce the overall overhead for the script. Here is a link to the development page:

http://dev.abinstallations.com

There are two parts to the animation, and these animations apply to six individual div elements. A separate script is applied to each element. For example:

//First
$("#first_flip").hide();
$("#first_button_show").click(function(){
  $('#first_flip').animate({
     opacity: 'toggle',
     top: '+=524',
     height: 'toggle'}, 600, function() {
       // Animation complete.
  });
});
$("#first_button_hide").click(function(){
  $('#first_flip').animate({
     opacity: 'toggle',
     top: '-=524',
     height: 'toggle'}, 400, function() {
       // Animation complete.
  });
});

//Second
$("#second_flip").hide();
$("#second_button_show").click(function(){
  $('#second_flip').animate({
     opacity: 'toggle',
     top: '+=524',
     height: 'toggle'}, 600, function() {
       // Animation complete.
  });
});
$("#second_button_hide").click(function(){
  $('#second_flip').animate({
    opacity: 'toggle',
    top: '-=524',
    height: 'toggle'}, 400, function() {
      // Animation complete.
  });
});

...and so on for the remaining four elements. Is there a condensed way to achieve this?

Was it helpful?

Solution

You could pull it out as a function:

Hook("first");
Hook("second");

function Hook( id )
{
    $("#" + id + "_flip").hide();
    $("#" + id + "_button_show").click(function(){
      $("#" + id "_flip").animate({
         opacity: 'toggle',
         top: '+=524',
         height: 'toggle'}, 600, function() {
           // Animation complete.
      });
    });
    $("#" + id + "_button_hide").click(function(){
      $("#" + id + "_flip").animate({
         opacity: 'toggle',
         top: '-=524',
         height: 'toggle'}, 400, function() {
           // Animation complete.
      });
    });
}

Or even make the function take several parameters and loop over them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top