Tooltip function does not work when running a second time

Asked

Viewed 135 times

1

I’m creating a tooltips sketch, so that when you click on a certain span, this span shows a message

HTML

<div class="banner-tooltips" id="banner-tooltips">
    <span id="primeira-tooltip">1°</span>
    <span id="segunda-tooltip">2°</span>
    <span id="terceira-tooltip">3°</span>
    <span id="quarta-tooltip">4°</span>
</div>

JS

function tooltips(){
    var caixaTooltips=document.getElementById("banner-tooltips");
    var tooltips=caixaTooltips.querySelectorAll("span");
    for(var i=0;i<tooltips.length;i++){
        tooltips[i].addEventListener("click",function(){
            var anterior=document.getElementsByClassName("banner-tooltip-active");
            console.log(anterior);
            if(anterior.length!=0){
                console.log(anterior);
                anterior.classList.remove("banner-tooltip-active");
            }
            console.log(anterior);
            this.classList.add("banner-tooltip-active");
        });
    }
}
tooltips();

When you click on the first tooltip, it opens a good one, but when you click a second time, it says that you cannot remove the Undefined class. Why this happens, and how can I solve the problem?

1 answer

2


Probably in the first click has no element with the class banner-tooltip-active, but in the second yes, and this error is generated because document.getElementsByClassName("banner-tooltip-active"); will return a array, then anterior.classList will not work. I suggest changing this section:

if(anterior.length){
    for (let i = 0 ; i < anterior.length ; i++){
        anterior[i].classList.remove("banner-tooltip-active");
    }
}

That way he will iterate all the others span removing active style, and finally enabling only what was clicked.

  • you know tell me, how can I do so that by clicking outside the main box, it removes all "banner-tooltip-active" classes from the child spans ?

  • 1

    Yes @Murilogambôa, it is a good question, it is better in another topic =]

  • I have created aheuhae :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.