Antonin Cezard
Antonin Cezard

Reputation: 2021

Reduce animations code repetition in jQuery

I'm creating an array of div animations and that produced a lot of repetitive code.

For instance :

$('#elem a:eq(0)').addClass("hiddenCSS").viewportChecker({
    classToRemove: 'hiddenCSS',
    classToAdd: 'animated bounceInLeft',
    offset: 200
});

$('#elem a:eq(1)').addClass("hiddenCSS").viewportChecker({
    classToRemove: 'hiddenCSS',
    classToAdd: 'animated bounceInUp',
    offset: 400
});

That's only two elements, but what if I have dozens ? My code becomes unusable very fast.

I wanted to create a function to make things easier but it is not working. Now I wonder if I'm supposed to create a class with a specific method. This is what I tried, doesn't work and is undefined :

function animation(elem,animation,offset) {
    $(elem).addClass("hiddenCSS").viewportChecker({
        classToRemove: 'hiddenCSS',
        classToAdd: 'animated' + animation,
        offset: offset
    });
}

animation('#elem a:eq(1)', 'bounceIn', 200);

Upvotes: 0

Views: 48

Answers (2)

mplungjan
mplungjan

Reputation: 177955

If you define a function inside

$(document).ready(function() {
  function myFunction() {}
  myFunction();
)};

it will NOT be globally available.

Move it outside

function myFunction() {}

$(document).ready(function() {
   myFunction();
)};

Upvotes: 3

The F
The F

Reputation: 3714

Your code should work with a document ready. It seems that your function declaration is not stacked before executing animation(...)

function animation(elem,animation,offset) {
    $(elem).addClass("hiddenCSS").viewportChecker({
        classToRemove: 'hiddenCSS',
        classToAdd: 'animated' + animation,
        offset: offset
    });
}

// $(function(){
// or more readable
$(document).ready(function() {    
    animation('#elem a:eq(1)', 'bounceIn', 200);
});

Upvotes: 1

Related Questions