"var" isn't working when in addEventListener or my code just executing first

47 Views Asked by At

I was working on discord to test something about the bot commands. When I click on the command this code should be able to set tooltip and the parts in it but the code executes before the command one.

var commands = document.querySelectorAll(".commandName-1KhvGm.clickable-31pE3P")
var tooltip =  document.querySelector(".tooltip-1T4pLi")
var tooltipItem = document.querySelectorAll(".text-md-normal-2rFCH3")

commands.forEach(cmnd => {
    cmnd.addEventListener("click", () => {
        setTimeout(() => {
            tooltip = document.querySelector(".tooltip-1T4pLi")  
            tooltipItem = tooltip.querySelectorAll(".text-md-normal-2rFCH3")
        }, 0)
    })
})

How can I fix it. I'm working on the chrome console rn.

I tried setTimeout, and other small things that comes to mind first

1

There are 1 best solutions below

0
John Lord On

I have to make some assumptions here because your question is missing context.
It appears you want to store a reference to your tooltip and then assign to it. You cannot do it like you have there because you are assigning the entire element into the variable. That is ok but it only needs to be done once, and after you do so, it stays updated on its own. I suggest you want to do something like this, although i can't test it.

 tooltip.innerHtml(newTooltipValue);

you need to read the value you want to set to the tooltip from the proper place in the event. Note: Using "let" here instead of var is a bad recommendation as you will lose scope out of the event.

See this link for more info: Note: I think they are available multi-language. https://www.w3schools.com/js/js_htmldom_html.asp