When I try to make my mobile navbar full screen on a mobile device, the hamburger button works as expected when clicked. Initially, all the links are displayed in full page view, but once I click on a link, it disappears and takes me to the respective section of the page. However, the issue arises when I try to do two consecutive clicks – an error saying “Cannot read property parentNode of undefined” is thrown. It seems like the problem lies in how I am hiding the ul
element. On the first click, I change the display to none
(initially set to visible), but I have to wait until it becomes available again in the DOM before I can hide it once more.
I am currently exploring possible solutions to address this issue. You can find the codepen with the implementation here.
Thank you,
jade
// BEM terminology added, but not yet implemented. Just basic css down there
nav.desktop
ul
li
a(href="") Home
li
a(href="") About
li
a(href="") Labs
li
a(href="") Contact
nav.mobile
.hamburger
button.hamburger__btn Toggle
span.hamburger__top
span.hamburger__middle
span.hamburger__bottom
ul.navigation--mobile--hidden
li
a(href="") Home
li
a(href="#about") About
li
a(href="#labs") Labs
li
a(href="#contact") Contact
main
section#about
h1 About
p Lorem ipsum dolor sit amet, consectetur adipisicing elit. Esse dolorum, accusamus officiis possimus cupiditate facere, sequi illum nobis saepe quidem repudiandae magnam natus cum animi repellendus. Illum qui, nobis voluptas.
section#labs
h1 Labs
p Lorem ipsum dolor sit amet, consectetur ...
// Additional CSS styles follow...
// JavaScript
$(function () {
var hamburgerBtn = document.getElementsByClassName('hamburger__btn')[0];
var navBar = hamburgerBtn.parentNode.parentNode;
var navBarUlEl = navBar.getElementsByTagName('ul')[0];
// Makes the hamburger btn clickable
hamburgerBtn.onclick = function() {
toggleClass(navBarUlEl);
var ulNavFlex = document.getElementsByClassName('navigation--mobile--flex')[0];
var navBarFlex = ulNavFlex.parentNode;
console.log('This is the ulnavflex: ' + ulNavFlex);
console.log('This is the navflex: ' + navBarFlex.classList);
console.log('This is the navbar: ' + navBar.classList);
var ulNavFlexLinks = ulNavFlex.getElementsByTagName('a');
console.log(ulNavFlexLinks);
console.log(ulNavFlex)
for (var i = 0; i < ulNavFlexLinks.length; i++) {
toggleLinkClick(ulNavFlexLinks[i]);
}
}
// Toggles Link Clicks
var toggleLinkClick = ...
// The script continues...