This is my code.
var scoreResults = document.querySelectorAll(".flex-blackjack-row-1 h3");
var scores = document.querySelector(".flex-blackjack-row-1 span");
const config = {childList: true};
const busted = function (mutationList, observer){
var bustedMessage = document.createElement('h2');
bustedMessage.textContent = 'BUSTED!';
scoreResults[0].before(bustedMessage);
hitButton.setAttribute('disabled', 'true');
}
const observer = new MutationObserver(busted);
observer.observe(scores, config);
I have defined bustedMessage variable in a callback function and I want to use it outside of that callback function. Still after successfully invoking the busted function (that means still after initiating the bustedMessage variable ), that variable can not be used outside of the callback function.
But when I take out this code block,
var bustedMessage = document.createElement('h2');
bustedMessage.textContent = 'BUSTED!';
to the outside from "busted" callback function, I can use bustedMessage variable in other functions too. Please explain why is this happening? I can not understand it because bustedMessage is a var type variable which is ought to use in anywhere.
Define bustedMessage outside first
var bustedMessage;
const busted = function (mutationList, observer){
bustedMessage = document.createElement('h2');
bustedMessage.textContent = 'BUSTED!';
scoreResults[0].before(bustedMessage);
hitButton.setAttribute('disabled', 'true');
}
you are now free to use bustedMessage anywhere in this script, of course it's undefined until you call busted for the first time.