0
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?

2
  • 2
    Why not change the settings with a :hover rule for a specific class and only toggle that class?
    – Andreas
    Commented Apr 29, 2021 at 13:09
  • 1
    Add the if() in the event handler
    – Andreas
    Commented Apr 29, 2021 at 13:10

1 Answer 1

2

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";
    }
  })
})

Not the answer you're looking for? Browse other questions tagged or ask your own question.