asimes
asimes

Reputation: 5894

Pass CSS property as argument to JavaScript function

I have a few nearly identical CSS animation functions for a JavaScript "class". The one I am posting below is for height, but I also have some for width, left, etc. It seems fairly redundant to me to have different functions for what is basically the same task, can I replace height in the function below with some kind of CSS property argument?

WindowItem.prototype.animateHeight = function(inElement, inTarget) {
    var selfCall = true;
    var currHeight = parseInt(inElement.style.height, 10);

    if (this.isExpanded) {
        if (currHeight < inTarget) {
            currHeight += ((inTarget-currHeight)>>3)+1;
            if (currHeight >= inTarget) {
                currHeight = inTarget;
                selfCall = false;
            }
        }
    }
    else {
        if (currHeight > inTarget) {
            currHeight -= ((currHeight-inTarget)>>3)+1;
            if (currHeight <= inTarget) {
                currHeight = inTarget;
                selfCall = false;
            }
        }
    }
    inElement.style.height = currHeight+"px";

    if (selfCall) {
        var self = this;
        setTimeout(function() {
            self.animateHeight(inElement, inTarget);
        }, 33);
    }
}

Edit: I probably should have also posted how I am calling this, I am not sure what to be passing the function to specify height in this example: this.animateHeight(this.imgWindow, 0);

Upvotes: 0

Views: 683

Answers (1)

user2264587
user2264587

Reputation: 474

as I wrote in my comment:

if you want to use this one function for any property given, you can use a parameter

this.animateProperty(this.imgWindow, 0, "height");

where

WindowItem.prototype.animateHeight = function(inElement, inTarget, cssProperty)
...

and instead of

inElement.style.height

use

inElement.style[cssProperty]

Upvotes: 1

Related Questions