Reputation: 407
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
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
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
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
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