javascriptsvghovermouseovermouseout

Is it possible to deactivate addeventlistener (mouseover/mouseout) on a specific condition in Javascript?


let currentColor = 0

function makeHover () {
        console.log(currentColor);
            svgAll.forEach(item => {
                item.addEventListener('mouseover', event => {
                    event.target.style.fill = "rgb(168,168,168)";
                    event.target.style.pointerEvents = "all";
                    event.target.style.cursor = "pointer";
                    event.target.style.strokeOpacity = "1";
                    event.target.style.fillOpacity = "0.3";
                    event.target.style.transitionDuration = "0.5s";
                    event.target.style.transitionTimingFunction = "ease-in";
                })
            })

            svgAll.forEach(item => {
                item.addEventListener('mouseout', event => {
                    event.target.style.fill = "none";
                    event.target.style.stroke = "white";
                    event.target.style.pointerEvents = "all";
                    event.target.style.strokeOpacity = "1";
                    event.target.style.fillOpacity = "0.1";
                    event.target.style.transitionDuration = "0.5s";
                    event.target.style.transitionTimingFunction = "ease-out";
                })
            })
        }

In this Code I only want to enable the hover effect when:

if (currentColor === 0)
        {makeHover ()}

I am using this effect on an SVG and the console gives currentColor = 1 when another condition is met that is setting currentColor = 1. Still the hovering works when currentColor = 1, is it even possible to deactivate the hover effect ones activated?


Solution

  • You just need to wrap the styling in if statements:

    svgAll.forEach(item => {
      item.addEventListener('mouseover', event => {
        if (currentColor === 0) {
          event.target.style.fill = "none";
          event.target.style.stroke = "white";
          event.target.style.pointerEvents = "all";
          event.target.style.strokeOpacity = "1";
          event.target.style.fillOpacity = "0.1";
          event.target.style.transitionDuration = "0.5s";
          event.target.style.transitionTimingFunction = "ease-out";
        }
      })
    })
    svgAll.forEach(item => {
      item.addEventListener('mouseout', event => {
        if (currentColor === 0) {
          event.target.style.fill = "none";
          event.target.style.stroke = "white";
          event.target.style.pointerEvents = "all";
          event.target.style.strokeOpacity = "1";
          event.target.style.fillOpacity = "0.1";
          event.target.style.transitionDuration = "0.5s";
          event.target.style.transitionTimingFunction = "ease-out";
        }
      })
    })