treehouse : what would you like to learn today?
Web Design Web Development iOS Development

jQuery: Passing argument to functions

  • What is the proper way to pass an argument to a function in jQuery?

    I want to pass a color to a function to update multiple css attributes

    I would think it would be something like below, but I can't seem to get it to work.

    ----------------------------------------

    Calling the function and passing the color:
    colorChange(#f00)


    jQuery:

    function colorChange(passedcolor)

    $(\"a, h2\").css(\"color\",passedcolor);
    $(\"#wrap, h3\").css(\"border-color\",passedcolor);
    $(\"#header, #footer\").css(\"background-color\",passedcolor);

    });


    The final plan is to set the page "theme" based on time of day, but using a single function that I pass a color to.

    Here's a concept model that changes based on what third of the minute it is (0-20,20-40,40-60) but it uses separate functions.
    http://home.comcast.net/~vonholdt/test/style_switch.htm

    Any help would be much appreciated. The jQuery bug has bit me of late.
    von
  • Is it tacky to answer my own question?

    So, it looks like I needed a couple of "s to get the job done. Say I want to pass a color and two positions to a function I would do like so

    colorTheme(\"#f00\", \"-100px\", \"-40px\")


    and then read them within the function like so


    function colorTheme(hex, pos1, pos2){
    $(\"#top, #bot\").css(\"background\",hex);
    $(\"a, h2\").css(\"color\",hex);
    $(\"#wrap, h3\").css(\"border-color\",hex);

    $(\"#top\").css(\"background-position\",\"0 \" + pos1);
    $(\"#bot\").css(\"background-position\",\"0 \" + pos2);
    };


    Seems to work like a charm.
    http://home.comcast.net/~vonholdt/test/style_switch_fix.htm

    I did notice something odd about .css in jQuery

    - you can .css("property","value")
    - or .css({ property: "value", property: "value" })
    but in the second instance the property names are not css standard.

    - Thus .css("margin-left","10px") has to be .css({ marginLeft: "10px" })
    - or .css("border-color","red") has to be .css({ borderColor: "red" })

    I suppose I much prefer chaining several with the right property name.
  • it is not tacky to answer your own question, I used to do this over at javaranch when I was learning java.

    sometimes you just have to put your problem down and explain it to someone else to see exactly what your trying to do, this way you get a slightly better understanding of your problem.

    plus answering your own problem shows others, who might have that problem, the solution.