0

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?

vitaliis
  • 4,082
  • 5
  • 18
  • 40

1 Answers1

0

Using this link I was able to resolve the issues and have it working as expected.

David Walsch Answer

:root {
--varMenuHoverColor: value;
--greenColor: #78a300;
--whiteColor: #ffffff;

}

#mega-menu-wrap-primary #mega-menu-primary li.mega-menu-item > ul.mega-sub-menu a.mega-menu-link:hover::before {
background-color: var(--varMenuHoverColor);

}

var cssVarGet = getComputedStyle(document.documentElement)
.getPropertyValue('--varMenuHoverColor');

var greenColor = getComputedStyle(document.documentElement)
.getPropertyValue('--greenColor');

var whiteColor = getComputedStyle(document.documentElement)
.getPropertyValue('--whiteColor');

var cssVarSet = function(name, val) {
document.documentElement.style.setProperty(name, val);
};

cssVarSet('--varMenuHoverColor', whiteColor);