I'm making a dropdown responsively. I made two dropdown-divs for both desktop version and mobile version. The problem is, as I initialize the mobile-version dropdown with a property 'display:none;', the addEventListener bound to it throws an error.
userinfoBtnMobile.addEventListener('click',function() {
const userinfoDropdownStyle = window.getComputedStyle(userinfoDropdownMobile);
const userinfoDropdownDisplayValue = userinfoDropdownStyle.getPropertyValue('display');
if(userinfoDropdownDisplayValue === 'none') {
userinfoDropdownMobile.style.display = 'block';
} else {
userinfoDropdownMobile.style.display = 'none';
}
});
Below is an error shown in console of the browser.
Uncaught TypeError: Cannot read property 'addEventListener' of null
However, as I changed it to the one using jQuery, this error disappears. (Please ignore internal logic. It logically do a same function.)
userinfoBtnMobile.click(function() {
if(userinfoDropdownMobile.is(':visible')) {
userinfoDropdownMobile.slideUp();
} else {
userinfoDropdownMobile.slideDown();
}
})
So, I assume that it seems like, as 'addEventListener' is triggered before the div's value of display property turned into 'block', it finds 'null' when targeting while jQuery's .click() is triggered when the specific 'click' event trigger so that it does not throw any error. Is that right?
What's difference between two ways?