Having read through this thread I found that the answer from user ybentz appears to best suite the solution I am looking for as if I do get it working will allow me to greatly reduce my overall JS and CSS.
Basically I have a header with multiple mega-menu items that contain an li.class (sub-menu) with each containing an a.class element. Upon hover::before I am trying to then update the property variable depending upon scroll position. But am getting the following error:
(index):1591 Uncaught TypeError: Cannot read property 'setProperty' of undefined
at (index):1591
at NodeList.forEach ()
at (index):1591
My code appears as follows;
HTML:
<a class="mega-menu-link"></a>
CSS:
#mega-menu-wrap-primary #mega-menu-primary li.mega-menu-item > ul.mega-sub-menu a.mega-menu-link:hover::before {
background-color: var(--mega-menu-link-background-color);
}
I am then attempting to change the property in an if else based upon the scroll position. I first set my color on page load as scroll is greater than 0. I'll leave all that out as the function works only breaks on the code below.
/* var menuSlideColor = document.querySelectorAll('#mega-menu-primary .mega-menu-item > .mega-sub-menu .mega-menu-link'); */
var menuSlideColor = document.querySelectorAll('#mega-menu-wrap-primary #mega-menu-primary li.mega-menu-item > ul.mega-sub-menu a.mega-menu-link:hover::before');
menuSlideColor.forEach(function() {
this.style.setProperty('--mega-menu-link-background-color', 'green');
});
if (currentScrollPos > 0) {
menuSlideColor.forEach(function() {
this.style.setProperty('--mega-menu-link-background-color', 'green');
});
}
else {
menuSlideColor.forEach(function() {
this.style.setProperty('--mega-menu-link-background-color', 'white');
});
}
I have tried the following as well.
menuSlideColor.forEach((mega-menu-link) => {
mega-menu-link.style.setProperty('--mega-menu-link-background-color', 'white')
});
And
menuSlideColor.forEach((mega-menu-link) => {
mega-menu-link.style.setProperty('--mega-menu-link-background-color', 'green')
});
Anything fundamentally wrong with my code?