javascriptcssfacebookfbjs

Using FBJS to change CSS


I'm a bit stumped by the Facebook implementation of Javascript. I want to set up a listener on a checkbox so that when checked, it changes the class of an element I can get by ID.

I've been using the test console and have tried various permutations. Javascript is NOT my first language, nor my second, third... COuld anyone help me by translating my pseudocode?

<input class="one" type="checkbox" onclick="setcolor(this.checkedornot)">
    function setcolor(checkedornot){
        if checkedornot == true {set p.one to p.one.GREEN}
        if checkedornot == false {set p.one to p.one.RED}
    }

Obviously this is not javascript, but that is how I can best explain the functionality I need. In my short tests, FBJS doesn't even seem to register onClick events. Thanks!


Solution

  • FBJS has its own getters and setters. Getting "checked" and setting/removing classes are different. And, you would have to remove the red class if you are adding the green class and visa versa. Or, if you just want to overwrite all the classes of the element, you can use the setClassName(class) method instead, I'm going to use the add/remove class methods in my answer since it is less destructive.

    FBJS Docs: Manipulating Objects

    For the onclick event, I think you're supposed to use the addEventListener if onclick doesn't work. Events in FBJS

    Instead of this.checked, FBJS uses getChecked. So when you add the event listener (for click), add a this.getChecked() for the arg.

    setColor(this.getChecked());
    

    And for the function:

    function setColor (isChecked) {
        var p = document.getElementById(ID-OF-P);
        if (isChecked) {
            p.removeClassName("red");
            p.addClassName("green");
        } else {
            p.removeClassName("green");
            p.addClassName("red");
        }
    }
    

    I am a JS newb too though. I think this is right.