Google PageSpeed Insights is flagging a website of mine with “Use passive listeners to improve scroll performance”. I’ve successfully resolved this issue for scroll event listeners, but I’ve run into an issue with a “touchstart” listener that I can’t get around.
I have the following code, for users on touch devices, that when tapping a top-level main navigation menu link that has a dropdown, on the first tap it will expand the dropdown (via toggled CSS class), and not follow the top level link. If you tap the top level link a second time, when the dropdown is already expanded, it will follow the link.
document.querySelectorAll( "#primary-nav>ul>li.menu-item-has-children>a" ).forEach( elem => {
elem.addEventListener( 'touchstart', (e) => {
let parent = elem.parentElement;
parent.classList.toggle( 'expand' );
if( parent.classList.contains( 'expand' ) ) {
e.preventDefault();
}
}, { passive: true } );
});
Adding { passive: true } towards the end broke the code. I get a console error which says “Unable to preventDefault inside passive event listener invocation”, and it follows the link on the first tap. If I remove the “e.preventDefault()” as suggested here, then it also follows the link on first tap.
Can anyone suggest a way around this? Your help would be greatly appreciated.