Having trouble toggling the navbar on and off in mobile. Error message: Unable to read parentnode of undefined

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...

Answer №1

It appears that there is a logical error in the code. When a section is selected from the menu, two classes - animate and navigation--mobile--hidden are added in the toggleLinkClick listener. However, when the menu is clicked again, the toggleClass function fails to update the class properly. To resolve this issue, you can modify the toggleClass function as shown below:

 var toggleClass = function(el) {
    if ($(el).hasClass('navigation--mobile--hidden')) {
      el.className = 'navigation--mobile--flex';
    } else if ($(el).hasClass('navigation--mobile-flex')) {
      el.className = 'navigation--mobile--hidden';
    } else {
      el.className = 'navigation--mobile--hidden';
    }
  }

Please note: I have used jQuery to check for the existence of a class since you have utilized jQuery.

Alternatively, another way to address this issue is to remove the animate class once the animation is completed in your toggleLinkClick listener, like so:

 var toggleLinkClick = function(el) {
    el.onclick = function() {
        console.log('I was clicked from: ' + el)
        if (navBarUlEl.classList == 'navigation--mobile--flex') {
          navBarUlEl.classList.add('animate');
          navBarUlEl.classList.remove('navigation--mobile--flex');
          navBarUlEl.classList.add('navigation--mobile--hidden');
          navBarUlEl.classList.remove('animate');
        }
        console.log(navBarUlEl.classList);
      }
  }

In this scenario, you won't need to modify your toggleClass function to include an if statement.

For a demonstration of the second solution, visit this CodePen link. And for the first solution, refer to this CodePen link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Increase the value by one of the number enclosed in the <h3> element

I have a variable number of <h3> tags with the same class .love_nummer <h3 class="love_nummer">1</h3> Each of these tags contains a number, and alongside each .love_nummer tag is another tag with the class .give_love <h3 class="give ...

What is the most effective method for manipulating and slicing a string based on character matching?

In this particular scenario, we are dealing with strings that follow this pattern: CP1_ctl05_RCBPAThursdayStartTimePicker_0_dateInput CP1_ctl05_RCBPAFridayStartTimePicker_3_dateInput CP1_ctl05_RCBPAMondayStartTimePicker_1_dateInput The goal is to extract ...

Unable to properly connect my CSS file to the header partial

I am struggling to include my CSS file in the header partial Here is the link I am using: <link rel="stylesheet" href="stylesheets/app.css"> This is what my directory structure looks like: project models node_modules public stylesh ...

Employing the GET method to retrieve the values of two text inputs

I'm struggling to retrieve the values from two text input fields: <form action="search.php"> <input type="text" name="q1"> <input type="text" name="q2" > <input type="submit" name="submit" value="Search" /> </form> On t ...

Utilizing a PHP-scripted multidimensional array in an AJAX success function

I've encountered an issue while trying to access a multidimensional array passed to my AJAX success function. Here's how I'm sending the data: $response = array(); $response['message']['name'] = $name; $response['m ...

The top margin in CSS relative positioning is not being displayed

My client has a specific requirement for the webpage to be positioned in the center of the screen. To achieve this, I have enclosed the entire webpage within a div element called "mainpage". Here is the CSS code: #mainpage { position:relative; wi ...

Utilizing Express.js for reverse proxying a variety of web applications and their associated assets

I am looking to enable an authenticated client in Express to access other web applications running on the server but on different ports. For instance, I have express running on http://myDomain and another application running on port 9000. My goal is to re ...

Creating Your Own Image Hosting Website: Learn how to consistently display an HTML file with a specific image from the URL

I'm currently in the process of developing my own image hosting site at Everything is functioning as intended, but I am looking to make a change. Currently, when a shared image link is opened, it only displays the image. However, I would like it to ...

Steps to send a table to PHP and store it as a text file

I have this program for a form data entry. It includes text boxes to input values, and upon clicking 'Submit', the input values should be displayed below while resetting the text box for another set of inputs. The issue I am facing is with the sa ...

Troubleshooting Symfony2 and Assetic: Why are my CSS-linked images not loading?

I've encountered an issue with my CSS sprite sheet that my CSS file seems unable to locate the image. Despite following the provided solution here, I'm still facing the same problem. The directory structure of my bundle is as follows: src/ v ...

`Inquiry into AJAX form submission problem`

Here is the HTML markup and JS code for my signup page. I encountered an issue where, if I leave all text inputs blank and click submit for the first time, it validates and shows an error message. However, when I click submit a second time, it directly sen ...

Enhancing Angular with Plotly: Implementing click events on bar chart legends

I'm currently working on implementing color pickers for my plotly-plot charts within an Angular template. I am looking to add a function that triggers when the chart legend is clicked. How can I achieve this and get a click event for the chart legends ...

Is there a way to retrieve and gather all data from various scopes and then access them collectively?

I attempted to scrape information from a website using Node.JS + Cheerio + Axios. I was able to retrieve all the necessary data, but encountered an issue with returning the data from different scopes in order to receive it. Currently, I can only obtain the ...

Issues arising with transferring information between components

My webpage had a header with a search engine input, a list of posts, and pagination all on one page. I made the decision to separate the header into its own component in a different Vue file. However, after making this change, searching for posts by their ...

Alignment of text varies between canvas and HTML

How can I ensure that the labels in both canvas and HTML display overlap exactly, regardless of font family and size? The current code fails to center text inside an area when switching between canvas and HTML view. let canvas = document.getElementById( ...

What is the method to retrieve JSON data from a URL and showcase the content on a JavaScript page?

I am currently developing a custom MS Teams application and I am facing an issue with fetching JSON data from a URL to display its contents later. Unfortunately, the fetch operation is failing. My objective is to retrieve a list of data from a specified UR ...

Vue js: Stop Sorting array items; only display the resulting array

I recently came across a tutorial on voting for a Mayoral Candidate. The tutorial includes a sort function that determines the winner based on votes. However, I noticed that the sort function also rearranges the candidate list in real time, which is not id ...

What are the steps to resolving an issue in a Jest unit test?

In my ReactJs/Typescript project, I encountered an issue while running a unit test that involves a reference to a module called nock.js and using jest. Initially, the import statement was causing an error in the .cleanAll statement: import nock from &apos ...

What specific CSS attribute changes when an element is faded out using jQuery's FadeOut method?

When we make an element fade in or out, which specific CSS property is being altered? Is it the visibility attribute, or the display property? I am hoping to create a code snippet with an if statement condition that reads (in pseudo code): if the div is ...

JavaScript functions flawlessly when run on a local machine, but encounters issues when transferred to a server

My JavaScript code is functioning perfectly on my local machine, but as soon as I upload it to my web server, it stops working. The website in question is www.turnbulldesigns.co.uk if you want to take a look. I have transferred the complete folder structu ...