Skip to main content
edited tags; edited title; edited tags; edited title
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

How can I achieve DRY principle in this code? Toggling animations

edited tags
Link
palacsint
  • 29.9k
  • 9
  • 81
  • 156
Source Link

How can I achieve DRY principle in this code?

In the following piece of code I use the same trick three times. But cannot figure out how to write a common function that will do it for all of them. I know there is a toggle method in jQuery that does something similar but in this situation I wasn't able to get it do the job for me, so I wrote this:

// fallback for ie
if (navigator.appName == "Microsoft Internet Explorer") {
    var flag = true;
    $(".right-arrow").click(function () {
        if (flag) {
            $(".slider-frame").animate({ left: "-130px" }, 1000);
            flag = false;
        }
        else {
            $(".slider-frame").animate({ left: "236px" }, 1000);
            flag = true;
        }
        return false;
    });
}
    // more smooth CSS3-animation with move.js
else {
    var flag = true;
    $(".right-arrow").click(function () {
        if (flag) {
            move(".slider-frame").set("left", -130).duration("1s").end();
            flag = false;
        }
        else {
            move(".slider-frame").set("left", 236).duration("1s").end();
            flag = true;
        }
        return false;
    });
}

// eye that make passwords visible
var state = true;
$(".login-form form").append("<div class='eye'></div>");
$(".eye").click(function () {
    if (state) {
        $("#password").attr("type", "text");
        $(".eye").css("background-position", "0 -49px");
        state = false;
    }
    else {
        $("#password").attr("type", "password");
        $(".eye").css("background-position", "0 0");
        state = true;
    }
});