javascriptpassive-event-listeners

event fires before mouseover and Unable to preventDefault inside passive event listener due to target being treated as passive


I have the following javascript code that's not working:

function moveDown(subnavs) {
  const navbar = document.getElementsByClassName('main-navigation')[0]                
  const purpleDiv = document.getElementsByClassName('home-vision')[0] 
  console.log(navbar,subnavs,purpleDiv)

  var x= "250px"  
  purpleDiv.style.marginTop = x
}

(function(){    
  const subnavs = document.getElementsByClassName('sub-menu') 

  for ( let i = 0 ; i <subnavs.length ; i++ ) {
     subnavs[i].addEventListener('mouseover', moveDown(subnavs), {passive:false})
  }
})()

When the page comes up, purpleDiv is immediately moved down 250px. When subnav is mouseover, console says Unable to preventDefault inside passive event listener due to target being treated as passive.


Solution

  • I am not 100% clear on your intent but here I alter the code to put in semi-colons to not force the browser to guess where to insert those and put a function in to allow passing the event and the other parameter you have (not sure the intent here) but calling it instead when adding the event handler was probably not your intent.

    No clue on your preventDefault note as that was not in the illustrated code supplied but I illustrate some stuff in the function called.

    function moveDown(event, subnavs) {
      const navbar = document.getElementsByClassName('main-navigation')[0];
      const purpleDiv = document.getElementsByClassName('home-vision')[0];
      let defaultWasPrevented = event.defaultPrevented;
      // console.log(event.currentTarget);
      console.log(event.target, defaultWasPrevented);
      event.preventDefault();
      defaultWasPrevented = event.defaultPrevented;
      console.log(defaultWasPrevented);
      // console.log(navbar, subnavs[0], purpleDiv.innerText);
      let x = "100px";
      purpleDiv.style.marginTop = x;
    }
    
    (function() {
      const subnavs = document.getElementsByClassName('sub-menu');
      for (let i = 0; i < subnavs.length; i++) {
        subnavs[i].addEventListener('mouseover', function(event) {
          moveDown(event, subnavs);
        }, {
          passive: false
        });
      }
    })();
    .main-navigation {
      background-color: #FFFFCC;
      border: solid 1px #DDDDDD;
    }
    
    .home-vision {
      background-color: #DDAAFF;
      border: solid 1px #DDDDDD;
    }
    <div class="main-navigation">main
      <div class="sub-menu">Cheers</div>
      <div class="sub-menu">Winner</div>
      <div class="sub-menu">Chicken</div>
      <div class="sub-menu">Dinner</div>
    </div>
    <div class="home-vision">home vision
      <div class="sub-vision">Guess 0</div>
      <div class="sub-vision">Guess 1</div>
      <div class="sub-vision">Guess 2</div>
      <div class="sub-vision">Guess 3</div>
    </div>