I have some javascript code to change an element of text within a webpage to a random color. I'm new to this, but the code does work. Every three seconds the text color of a specific element changes to a new random color.
const handler = function() {
const genselector = "div.tw-c-text-alt-2.tw-flex > span";
const genel = document.querySelector(genselector);
var randcolor = Math.floor(Math.random()*16777215).toString(16);
genel.style.color = "#" + randcolor;
}
setInterval(handler, 3000);
If I move both const variables outside the function the program no longer works, which makes sense because the variables are defined outside of the function and they are not global variables.
const genselector = "div.tw-c-text-alt-2.tw-flex > span";
const genel = document.querySelector(genselector);
const handler = function() {
const specel = document.querySelector(specselector);
var randcolor = Math.floor(Math.random()*16777215).toString(16);
genel.style.color = "#" + randcolor;
}
setInterval(handler, 3000);
However if I move only the first variable outside of the function the code still works, even though I don't think it should.
const genselector = "div.tw-c-text-alt-2.tw-flex > span";
const handler = function() {
const genel = document.querySelector(genselector);
var randcolor = Math.floor(Math.random()*16777215).toString(16);
genel.style.color = "#" + randcolor;
}
setInterval(handler, 3000);
How is the genselector variable being accessed by the function when it was defined outside the function, and for whatever is causing it to work why doesn't the same thing happen when I move out the genel variable.