0

I am attempting to optimize my code after seeing some repetition.

Here is the code:

function show($div, $change, $value){
    var $container = "#" + $div;
    var $class = $div + "-" + "hidden";

    //alert($class + $container + $change + $value);

    $($container).addClass($class);
    $($container).animate({
        $change: $value
    }, 1000, function(){
            $($container).removeClass($class);
        } 
    );
}

show('header', 'top', '0');
show('nav', 'left', '0');
show('wrapper', 'opacity', '0');

This area: $change: $value - is where I am having trouble in the script. Can I do this? Should they come in as strings?

2 Answers 2

2
function show($div, $change, $value){
    var $container = "#" + $div;
    var $class = $div + "-" + "hidden";

    //alert($class + $container + $change + $value);

    $($container).addClass($class);

    var animation = {}; // create another object
    animation[$change] = $value; // and set its property

    $($container).animate(animation, 1000, function(){
            $($container).removeClass($class);
        } 
    );
}
2
  • Geez I just noticed how confusing the $ to start the variable is. Just came from PHP land so a little stuck there... I'll try that. Can you explain the animation object and how this sets the property. I'm not quite getting it.
    – EZDC
    Aug 17, 2012 at 2:00
  • @user980988: it is just a regular javascript object var foo = {}; <--- do you know what this means?
    – zerkms
    Aug 17, 2012 at 2:08
1

I think you're trying to dynamically set the variable name in a literal. In JavaScript, you can do this like so objectname["variablename"] = value

There are actually two things you can do here:

  1. The literal that you are passing to the first argument of animate() can be pulled out
  2. The jQuery evaluation of $container can be pulled out, done once, and reused to speed things up.

Though some might call 2 an example of premature optimization, I think it makes your code more readable, anyway.

function show($div, $change, $value){

    var $container = "#" + $div;
    var $class = $div + "-" + "hidden";

    //alert($class + $container + $change + $value);

    var animation = {}; //declare a literal
    animation[$change] = $value; //create a name-value pair based on args

    var jqContainer = $($container);  //extract multiple jQuery evaluations
    jqContainer.addClass($class);
    jqContainer.animate(animation, 1000, function(){
            jqContainer.removeClass($class);
        } 
    );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.