how do i use a block of code without rewriting it over again

29 Views Asked by At

How can i reuse a block of jquery code without rewriting it all over again for example i got this animation and would want to repeat it in another line

    $("#sign_up_btn").mouseenter(function(){
        $("#sign_up_btn").animate({ opacity: "0.5" }, 300);
        $("#sign_up_btn").animate({ fontSize: "200%" }, 300);
      });
    $("#sign_up_btn").mouseleave(function(){
        $("#sign_up_btn").animate({ opacity: "0.2" }, 300);
        $("#sign_up_btn").animate({ fontSize: "100%" }, 300);
      });
1

There are 1 best solutions below

1
On BEST ANSWER

Make a function.

Also DRY (don't repeat yourself)

const anim = function(e) {
  const enter = e.type === "mouseenter";
  $(this)
    .animate({ opacity: enter ? "0.5" : "0.2"}, 300)
    .animate({ fontSize: enter ? "200%" : "100%" }, 300); // can possibly be merged
};

$("#sign_up_btn").on("mouseenter mouseleave", anim);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="sign_up_btn">Sign up</button>