I am trying to make a script that will hide chat and show it again after pressing the H button but I don’t know how I need to make the <div> elements from the website show again after I remove it. Here’s my code:
// ==UserScript==
// @name Cytos Additions
// @namespace http://tampermonkey.net/
// @match https://cytos.io/
// @grant none
// ==/UserScript==
var isToggled = false;
function doc_keyUp(e) {
switch (e.keyCode) {
case 72: // h
if (isToggled) {
}
else {
document.getElementsByClassName('_1FlWeEtrJKCnvzX-Y50CLP')[0].remove()
}
var isToggled = true;
break;
default:
break;
}
}
document.addEventListener('keyup', doc_keyUp, false);
I don’t know what to put under the if(isToggled) statement to make the chat reappear again.
The opposite of removal is insertion; there are various ways to insert an element.
Since your element is at index 0, prepending it to its original parent element is what you need here.
If you just remove an element without retaining its reference, it’s going to be garbage-collected and you cannot use it anymore. So store a reference to the element; also, store one to its parent, since that’s the target you need to prepend the element to.
const chatElement = document.getElementsByClassName('_1FlWeEtrJKCnvzX-Y50CLP')[0],
chatParent = chatElement.parentElement;
let isToggled = false;
function doc_keyUp(e) {
switch (e.code) {
case KeyH:
if (isToggled) {
chatParent.prepend(chatElement);
}
else {
chatElement.remove();
}
isToggled = !isToggled;
break;
default:
break;
}
}
document.addEventListener("keyup", doc_keyUp, false);
Toggling the variable isToggled can be done with isToggled = !isToggled;, but do not redeclare the variable inside the function, or else it will have no relation to your outer isToggled variable.
Note that keyCode is deprecated.
You should use code instead.
There are two more concerns:
case KeyH: chatElement.toggleAttribute("hidden"); break; instead.
See the documentation on toggleAttribute and on the hidden property._1FlWeEtrJKCnvzX-Y50CLP doesn’t look like a stable class name, but rather like a minified, randomized name.
It’s very likely to change and your user script is very likely to break.
Familiarize yourself with the DOM API, in particular with document.querySelector, and consider finding a more stable selector.