The responsive navigation bar yielded an unforeseen outcome

Looking to create a responsive navigation bar similar to the one shown here

My code successfully shows and hides the navigation items, but it's not updating the burger icon

No console errors or warnings are present

This is my HTML:

<nav>
                <div class="container">
                    <div class="logo">Landing</div>
                    <ul class="menu">
                        <li class="toggle"><a href="#"><i class="fa fa-bars"></i></a></li>
                        <li class="item">Home</li>
                        <li class="item">Features</li>
                        <li class="item">Reviews</li>
                        <li class="item">Pricing</li>
                        <li class="item">FAQ</li>
                        <li class="item">Get Started</li>
                    </ul>
                </div>
            </nav>

CSS styling:

@media screen and (min-width: 481px) and (max-width: 768px) {
    nav ul{
        flex-wrap: wrap;
        justify-content: space-between;
        align-items: center;
    }
    nav .toggle {
        flex: 1;
        text-align: right;
        order: 2;
        display: block;
    }
    nav .item {
        order: 2;
        width: 100%;
        text-align: center;
        display: none;
    }
    .active-menu .item {
        display: block;
    }
    }

JQuery implementation:

const toggle = document.querySelector(".toggle");
const menu = document.querySelector(".menu");
function toggleMenu(){
    if($(menu).hasClass('active-menu')){
        $(menu).removeClass('active-menu');
        $(toggle).has('a').html('<i class="fa fa-bars"></i>');
    } else {
        $(menu).addClass('active-menu');
        $(toggle).has('a').html('<i class=\'fa fa-times\'></i>');
    }
}
$(toggle).click(toggleMenu)

The navigation uses a flex display layout

I haven't been able to publish it on GitHub since I'm not very familiar with the platform

Answer №1

The reason for the issue is that you are replacing <a>..</a> with

<i class="fa fa-bars"></i>
. As a result, when $(toggle).has('a') is called, it returns null and the HTML of your toggle element remains unchanged. A simple fix would be to modify the class of your <i></i> element like this:

const toggle = $(".toggle");
const menu = $(".menu");
function toggleMenu(){
    if(menu.hasClass('active-menu')){
        menu.removeClass('active-menu');
        toggle.find('i').removeClass().addClass('fa fa-bars');
    } else {
        menu.addClass('active-menu');
        toggle.find('i').removeClass().addClass('fa fa-times');
    }
}
toggle.click(toggleMenu)

It's worth noting that you could simplify

const toggle = document.querySelector(".toggle");
$(toggle)...

to

const toggle = $(".toggle");

Here is a working example: https://jsfiddle.net/t8gfbhyq/

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

When using jQuery with a large selectbox, you may encounter the error message: "Uncaught RangeError: Maximum

My select box works fine in IE and Mozilla, but throws an uncaught rangeError in Chrome when choosing the "Others" option to display a second select box with over 10k options. How can I diagnose and resolve this issue? <!DOCTYPE html> ...

Common issues encountered when using the app.get() function in Node.js

I've been attempting to develop a website that utilizes mongojs. I've implemented the code snippet below, but when I launch the site, it never reaches the app.get() section, resulting in a 500 error on the site. How can I ensure it responds to th ...

What's the reason behind the failure of bitwise xor within a JavaScript if statement?

I'm trying to understand the behavior of this code. Can anyone explain it? Link to Code function checkSignsWeird(a,b){ var output = ""; if(a^b < 0){ output = "The "+a+" and "+b+" have DIFFERENT signs."; }else{ output = ...

In Javascript, you can compare an array with a nested array and then store the values in a new array

Two arrays are at hand const arrayOne = [ {id: '110'}, {id: '202'}, {id: '259'} ]; const arrayTwo = [ {data: [{value: 'Alpha', id: '001'}]}, {data: [{value: 'Bravo', id: '202'}]}, ...

looking to retrieve the corresponding value of a specific array key

I am trying to determine the value of a complex array, but I keep getting values like 0,1,2,3,4,5 as answers. Here is the code snippet I am using to retrieve the state value of the array: var shardState = Object.keys(mydata.cluster.collections[collection ...

How can the spacing between Angular Material's mat-card-content and mat-card-actions be adjusted?

I am creating a mat card layout where there are two separate cards within the main card's content section. However, when I add a button for the actions section of the main card, there is no spacing between these two sections. How can I create a vertic ...

How do I utilize Protractor to target a specific div element with a distinctive class and verify its visibility on the page?

Below is the view.html for a unique class: <div class="appExperience small-tile"> </div> This is the code snippet that I attempted to use: var displayedTile = element(by.css('.appExperience small-tile')); expect(displayedTile.i ...

Arrange the elements within the anchor tag in a vertical line using Angular Material

Is there a way to style the elements within an anchor tag in Angular Material so that they display in a single line? I am looking for the CSS solution to achieve this outcome. This is my current HTML code: <a mat-list-item [routerLink]="['das ...

The jQuery .val() function does not function properly when using 'this'

This is an example with a textarea: <textarea id='ta' onkeydown='down(this)'></textarea> and here is the accompanying JavaScript code: <script> function down(input) { alert(input.val()); // not functioning ...

What methods can I use to automate the testing of a UI that relies on a lightbox feature?

As a tester utilizing crossbrowsertesting.com, I have come across a situation where developers integrated lightbox into a web app built on the Drupal platform. When users navigate to mysite.com/home and click on a div that triggers a lightbox effect, addit ...

Tips for Editing an HTML File

As a beginner in the world of coding, I am currently working on creating a quiz maker. My question is how can I use code to edit a file? For example, if a user inputs a question name, how can the code automatically update the corresponding question in th ...

What is the best way to ensure a multi-page form is validated using HTML5 and JavaScript before progressing to the next page?

Currently, there are two functionalities at play. The submit button is not being recognized while the functionality in JS $(".next").click(function(){..} is working as expected. HTML This section involves 4 fieldsets. I am attempting to validate ...

The function stringByEvaluatingJavaScriptFromString is failing to execute

I have tackled similar problems that have been posted in this forum, however my issue remains unresolved. I am attempting to utilize stringByEvaluatingJavaScriptFromString in swift, but it is not functioning as expected. Any assistance would be greatly app ...

Uncovering specific content within an html document with the help of BeautifulSoup

I am currently working with a code that involves using BeautifulSoup to scrape text from elements with the class 'product'. However, I am only interested in extracting the 2nd and 4th values ('Product 2' and 'Product 4') to be ...

"Trouble with Material-UI DataGrid: Column headers are being cut off

I am facing an issue where my column names are getting cut off even though they should fit in the available space. https://i.sstatic.net/kmKFi.png ...

Adjusting the width of the container <div> will automatically resize the inner <div> to match

I have a main container element. .wrapper{ border:1px solid blue; position:relative; top:20%; left:30%; height: 300px; width: 350px; } When I adjust the width of the parent container, the child box does not reposition itself accor ...

Can a jumbotron and navigation bar be permanently attached to the top of a screen?

Currently, I am in the process of constructing my website using Bootstrap and my goal is to ensure that the header and navigation bar remain fixed at the top of the page while the content below scrolls underneath. While I am aware that it is possible to fi ...

The function correctly identifies the image source without error

I possess a pair of images: <img id="img1" src="l1.jpg" usemap="#lb" height="400" border="0" width="300"> <img src="images.jpg" id="img2"> Next up is some JavaScript: function validateImages () { if (document.getElementById('img2&ap ...

The Comparison of Time Complexity between Dynamic Array Pushing and Assigning to a Fixed Size Array in JavaScript

Consider the following example with dynamic arrays: let numbersArray = []; for(let i = 0; i < 5; i++) numbersArray.push(i+1); and then we have another array: let valuesArray = Array(6); //Keep in mind that this array has a size of 6 compared t ...

Dynamic parameters can be passed in Rails using the link_to method

Feeling a bit stuck, maybe this is just a simple question. I have a sort button that I need to use to organize my list of questions. To do this, I create a link_to like this: <%= link_to xx_path(:is_sort => true, :remote=> true , :method=> :p ...