Search code examples
javascripthtmlfirefoxkeygreasemonkey

How to set a key to change style of a node?


I'm doing an userscript of Greasemonkey and I want set a key to change style display:"" of none to block and vice versa of a node by press a key ("Home" in this case).

var bluebar = document.getElementById('pagelet_bluebar');
bluebar.style.display = "none";
document.addEventListener("keydown", function (e) {
    if (e.keyCode == 36) {
        showhideui();
    }
}, false);
function showhideui() {
    if (bluebar.style.display = "none") {
        bluebar.style.display = "block";
    } else if (bluebar.style.display = "block") {
        bluebar.style.display = "none";
    }
}

The solution was add == instead = in the conditions:

if (bluebar.style.display == "none")
else if (bluebar.style.display == "block")

Solution

  • Use == or === instead of single = sign in your comparison.
    Check this link about comparison operators

     var bluebar = document.getElementById('pagelet_bluebar');
       document.addEventListener("keydown", function (e) {
           if (e.keyCode === 36) { //press "Home" key change to block/none
               showhideui();
           }
       }, false);
       function showhideui() {
           if (bluebar.style.display == "none") { //if is none
               bluebar.style.display = "block" ; //change to block
           } else if (bluebar.style.display == "block" || bluebar.style.display == "") { //if is block
               bluebar.style.display = "none"; //change to none
           }
       }
    

    Ps: If there is only those two possibilities, you could even use a more synthetic way :

    (bluebar.style.display == "block" || bluebar.style.display == "") ? bluebar.style.display = "none" : bluebar.style.display = "block";