简体   繁体   中英

Having trouble dynamically adding and removing classes with JS and SVG's

I'm trying to create an interaction where every-time you click on an icon, a green border appears below it, and the green border that was on the last icon clicked gets removed. But when the page loads, the green border, by default, will be under the first icon. I wanted it that way.

I tried to achieve this effect by adding and removing the class "side-effect" to the li elements under the ul-side parent container. For some reason my code isn't running at all.

Here is the Javascript I wrote. Other relevant code can be found in the fiddle link below. const sideNavList=document.getElementsByClassName("ul-side")[0]; const navigationChildren=sideNavList.children;

sideNavList.addEventListener('click', function(e){
    if (e.target.classList.contains("side-item")) {
        liNavTarget=e.target;
        for (let i=0; i<navigationChildren.length; i+=1) {
            if (navigationChildren[i].classList.contains("side-effect")) {
                navigationChildren[i].classList.remove("side-effect");
                liNavTarget.classList.add("side-effect");
            }
        }
    }
});

https://jsfiddle.net/apasric4/mg2Lu0no/4/

Could anyone help me correct my code?

You should learn to use console.log() -- call it like console.log(e.target) at the top of your function and you'd see that your click events are registering on the SVG elements, not the <li> s. There are several workarounds for this, one of which is to prevent pointer-events on the SVG and anchor elements:

https://jsfiddle.net/1zt0vxm4/

.side-anchor {
  pointer-events: none;
}

.side-svg {
  pointer-events: none;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM