Search code examples
javascriptuserscripts

Tampermonkey: display an element if it's hidden (and vice versa)


I would like to hide/show some div on Youtube based on a keyboard shortcut. I am able to hide the div but not to display them, once I have hidden them.

// ==UserScript==
// @name         Youtube enhanced
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Youtube enhanced
// @author       You
// @include     *youtube.com/watch*
// for change CSS
// @grant    GM_addStyle

// ==/UserScript==


window.addEventListener("keydown", dispatchkeyboard, false);

function dispatchkeyboard(key) {
    // frontcolor

    if (key.altKey && key.code === "KeyC") { // KeyX
        alert("c")
        var hidden_or_display = document.getElementsByClassName("ytp-gradient-bottom")[0].style.display;
        alert(hidden_or_display)
        if (hidden_or_display == "none") {
            alert('none')
            var display = ".ytp-gradient-bottom,.ytp-gradient-top,.ytp-chrome-top,.ytp-chrome-bottom{display:block;}"
            var tag = document.createElement("style");
            tag.type = "text/css";
            document.getElementsByTagName("head")[0].appendChild(tag);
            tag[(typeof document.body.style.WebkitAppearance == "string") ? "innerText" : "innerHTML"] = display
        } else {
            alert('else')
            var goaway = ".ytp-gradient-bottom,.ytp-gradient-top,.ytp-chrome-top,.ytp-chrome-bottom{display:none;}";
            var tagd = document.createElement("style");
            tagd.type = "text/css";
            document.getElementsByTagName("head")[0].appendChild(tagd);
            tagd[(typeof document.body.style.WebkitAppearance == "string") ? "innerText" : "innerHTML"] = goaway
        }
    }

}

Solution

  • Inline style has a greater priority over style declared in stylesheet. Changing the style of an element via stylesheet won't change the inline style value.

    I've not got tampermonkey installed so untested, change

      var hidden_or_display = document.getElementsByClassName("ytp-gradient-bottom")[0].style.display;
    

    to

      var element = document.getElementsByClassName("ytp-gradient-bottom")[0];
      var hidden_or_display = element.style.display;
    
      // toggle inline style
      element.style.display = hidden_or_display == "none" ? "block" : "none";