user3221685
user3221685

Reputation: 21

DIV & Animation

When i'm creating a menu with DIVs and animating it with JS, I found myself copying/pasting the same JS and CSS codes for every button of the menu. Is there a way to create the animation JS code and the CSS style code once, and call them when needed for any button I may have on my website?

Upvotes: 0

Views: 77

Answers (1)

agconti
agconti

Reputation: 18123

Modularize your code by pulling the animation to a function and then apply it to all buttons (or anything) of a particular class. Like this:

Example in a fiddle: http://jsfiddle.net/agconti/9299P/

html

<button class="my-btn-class"></button>

css:

.my-btn-class {
  /* no stylings just a target*/
}

js:

  function myAnimation(btn) {
     //do stuff to btn
     $(btn).animate({
         opacity: 0.25,
         left: "+=50",
         height: "toggle"
     }, 5000, function () {
         // Animation complete.
     });
 }
     $(function () {
         $(document).on("click", ".my-btn-class", function (e) {
             e.preventDefault();
             myAnimation(this);
         });
     });

you can paste your js animation inside the myAnimation function. that way every button with the class my-btn-class will do the same animation when clicked. It's a best practice to modularize code that you continue to reuse through out your site. This way that code can be easily maintained because it's all in once place.

Upvotes: 4

Related Questions