medzi
medzi

Reputation: 407

how to reuse same function or variable repeatedly - jQuery

I guess this is a rather trivial question.

How do I create a global function for "animation" so that I don't have to repeat the code?

I tried the below, but it is not working :(

$(document).ready(function(){ 

 var animate = ['one','two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];

 //i'd like use this repeatedly
 var animateThis = animate({"margin-top":"10px"});


 for(var i=0; i < animate.length; i ++){

      $('.'+animate[0]).animateThis;// this does not work :(
      $('.'+animate[2]).animateThis;

      $('.'+animate[4]).animateThis;
      $('.'+animate[6]).animateThis;


 }

});

Many thanks for your help.

Upvotes: 0

Views: 240

Answers (4)

Florian F.
Florian F.

Reputation: 4700

You could also go with something like :

jQuery.fn.animateMyMargin= function () {
    $(this).animate({"margin-top":"10px"});
};

And then call it this way :

$('.myClassForAllElements').animateMyMargin();

Guess it would be more DRY and jQuery-ed than looping over an array.

Upvotes: 3

Richard Dalton
Richard Dalton

Reputation: 35793

Create a function that contains the code to do the animation then call that inside the for loop:

function animateThis(element) {
    return $(element).animate({"margin-top": "10px"});
}

for(var i=0; i < animate.length; i ++){    
      animateThis($('.'+animate[i]));
 }

Upvotes: 1

CRABOLO
CRABOLO

Reputation: 8793

example

$(document).ready(function() {

var a = $('#div1');
var b = $('.classes1');
var c = $('#div2');
var d = $('#nav li');

function animate(x) {
    x.animate({'margin-top': '10px'}, 900);
}

animate(a);
animate(c);

});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$(document).ready(function () {

    var animate = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];

    //i'd like use this repeatedly
    var animateThis = function (el) {
        el.animate({
            "margin-top": "10px"
        });
    }


    for (var i = 0; i < animate.length; i++) {
        animateThis($('.' + animate[0]));
        animateThis($('.' + animate[2]));
        animateThis($('.' + animate[4]));
        animateThis($('.' + animate[5]));
    }

});

Upvotes: 1

Related Questions