The Javascript navigation bar is not displaying properly on mobile devices as it should

After customizing the responsive navbar tutorial from W3Schools using CSS and JS, I encountered an issue. I wanted to include a logo and a web page title before the navbar, which worked perfectly when the webpage was maximized. However, when I resized the page to be smaller, the navbar overflowed and the menu icon disappeared when clicked, making it impossible to return to its original form without refreshing. View my CodePen example here

function myFunction() {
      var x = document.getElementById("myTopnav");
      if (x.className === "topnav") {
        x.className += " responsive";
      } else {
        x.className = "topnav";
      }
    }
 @media screen and (max-width: 600px) {
      .topnav a:not(:first-child) {
        display: none;
      }
      .topnav a.icon {
        float: right;
        display: block;
      }
    }
    
    /* Additional CSS styles */
    
    
 <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8>
       
       <!-- Rest of the HTML content -->
       
    </body>
    
    </html>


    

Answer №1

I successfully completed this task on my own by utilizing Mediaquery to determine the maximum width of the navigation bar (including both logo and menu). As an added bonus, I included jQuery within a script tag to change the menu icon to a close icon when it is opened.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
    <link rel="stylesheet" href="..\Css\style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Rubik:wght@400;500;600&display=swap" rel="stylesheet">
</head>
<body>
    <div class="top-bar">
        <span>
            <ion-icon name="call" clasa="call"></ion-icon>
            123 456 789
        </span>
        <ul>
            <li><a href="#">
                    <ion-icon name="logo-facebook"></ion-icon>
                </a></li>
            <li><a href="#">
                    <ion-icon name="logo-twitter"></ion-icon>
                </a></li>
            <li><a href="#">
                    <ion-icon name="logo-instagram"></ion-icon>
                </a></li>
        </ul>
    </div>
    <nav>
        <div class="logo">
            <a href="#"><img src="..\Images\logo.png" alt="logo">MoviesHub</a>
        </div>
        <div class="toggle">
            <a href="#">
                <ion-icon name='menu'></ion-icon>
            </a>
        </div>
        <ul class="menu">
            <li><a href="#" class="select">Home</a></li>
            <li><a href="#">Movies</a></li>
            <li><a href="#">Blog</a></li>
            <li><a href="#">About</a></li>
        </ul>
    </nav>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(function() {
            $(".toggle").on("click", function() {
                if ($(".menu").hasClass("active")) {
                    $(".menu").removeClass("active");
                    $(this).find("a").html("<ion-icon name='menu'></ion-icon>");
                } else {
                    $(".menu").addClass("active");
                    $(this).find("a").html("<ion-icon name='close'></ion-icon>");
                }
            });
        });
    </script>
    <script type="module" src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d242223242e22233e0d786378637f">[email protected]</a>/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa3a5a4a3a9a5a4b98affe4ffe4f8">[email protected]</a>/dist/ionicons/ionicons.js"></script>
</body>

</html>

Css

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

a,
a:hover {
    text-decoration: none;
}

.top-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 25px;
    background: rgba(32, 51, 71, 1);
}

.top-bar span {
    color: white;
    font-weight: 400;
    font-size: 12px;
}

.call ion-icon {
    position: relative;
    top: 20px;
}

.top-bar ul {
    list-style: none;
    display: flex;
}

.top-bar li {
    margin: 0px 10px;
}

.top-bar a {
    color: white;
    font-size: 15px;
}

.top-bar a:hover {
    color: rgba(2, 13, 24, 1)
}

nav {
    background: rgba(2, 13, 24, 1);
    padding: 15px 20px;
    display: flex;
    align-items: center;
    box-shadow: 0 1 25px 0 rgba(2, 13, 24, 1);
}

.logo img {
    width: 40px;
    margin-right: 10px;
}

nav a {
    color: white;
}

.menu a.select{
    color: rgba(213, 255, 0, 1);;
}

nav a:hover {
    color: rgba(213, 255, 0, 1);
}

.logo {
    flex: 1;
}

.logo a {
    display: flex;
    align-items: center;
    font-size: 14px;
    font-weight: 500;
}

.logo a:hover {
    color: rgba(213, 255, 0, 1);
}

.menu {
    display: flex;
    align-items: center;
    list-style: none;
}

.menu li {
    margin: 0px 10px;
    padding: 12px 8px;
    font-size: 14px;
}

.toggle {
    font-size: 18px;
    display: none;
}

@media screen and (max-width: 600px) {
    nav {
        display: block;
        position: relative;
        padding: 15px 20px;
    }

    .menu {
        margin-top: 15px;
        display: none;
    }

    .menu.active,
    .toggle {
        display: block;
    }

    .toggle {
        position: absolute;
        top: 25px;
        right: 20px;
    }
}

body {
    background: linear-gradient(to bottom,
            rgba(30, 59, 112, 0.6),
            rgba(2, 13, 24, 0.6)) no-repeat center center fixed,
        url("../Images/Background.jpg");
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
    font-family: 'Rubik', sans-serif;

}

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

Is it possible to receive returned string values using fetch()?

I have implemented a fetch method in my separate register.js file to handle registration on the front end. However, I am encountering an error when trying to POST the data and receive the following message in the browser console: "Uncaught (in promise) Syn ...

Unable to launch the Express application on a 64-bit Windows 7 operating system

After successfully installing Node for Windows/64bit and being able to run the server with an example from the Node homepage, I encountered an issue when setting up an Express app. Despite installing Express using the command npm install -g express and r ...

Utilizing the '<' or '>' operator in combination with an if statement within a Repeater component

Is it possible to use an if statement in a repeater like this? <%#Eval("FN").ToString().Count > 0 ? "SB" : "" %> When I try to implement this, I receive an error 73 indicating that the > operator cannot be used. How can I adjust it so that i ...

Navigate audio tracks with JavaScript

I'm currently facing an issue with using a button to switch between two audio tracks being played in the browser. The method I have implemented switches to the second track, but it doesn't change the audio that is played afterward - instead, it s ...

Develop your website layout with Flexbox (Bootstrap 4.2), using stacked grid designs similar to the float: left method

For my Wordpress theme, I am utilizing Bootstrap 4.2 to design a basic grid layout for a list of blog posts. In my design, I have a Card that is double the height of others and I am attempting to 'float' two single-height cards beside it. Previ ...

Enhance your Vue app with filtered categories using Vue-google-chart

What is the process for creating a filter category in a bar chart using the vue-google-charts wrapper in Vue.js? I have successfully created a stacked bar chart and now I am looking to add a filter by label inside the legend. Here is my vue application: ...

A JQuery function linked to the click event of the body element triggers another click event right away

$().ready(function(){ $("#move-to").click(function(){ $("body").bind("click",function(){ alert("foo"); }); }); }); Why do I receive an alert message of "foo" immediately after clicking on "move-to"? When I bind the " ...

Styling the select dropdown border in Google Chrome

I am encountering an issue with styling HTML select options in Chrome. Despite successfully applying borders to each option in Firefox, I cannot get it to work in Chrome. Can anyone advise on how this can be achieved? <select id="sortingOptions" class= ...

"Integrating `react-textarea-code-editor` with Remix: A Step-by-Step Guide

Upon loading the root of my web app, I encountered an error. The react-textarea-code-editor component is accessed via a separate route. The same error persisted even after following the suggestions provided here: Adding react-textarea-code-editor to the ...

When utilizing the --watch flag, Node-sass will fail to function properly

Encountering an issue with the "--watch" or "-w" flag when running node-sass. After installing node-sass as a devDependency and setting up a script to compile SCSS code, everything runs smoothly without any flags. However, adding the "--watch" flag causes ...

Is it possible to restart an animated value in React Native?

I'm facing an issue in my react native app where I have created a simple animated progress bar, but I am unsure how to reset the animation. I attempted the following approach without success: progressValue = 0; How can I reset the animation? Also, w ...

Issue encountered while deploying Next.js application on vercel using the replaceAll function

Encountering an error during deployment of a next.js app to Vercel, although local builds are functioning normally. The issue seems to be related to the [replaceAll][1] function The error message received is as follows: Error occurred prerendering page &q ...

Experiencing trouble with implementing multiple textboxes based on option selection using javascript

My JavaScript code is supposed to display multiple textboxes based on the user's selection, but for some reason, I can only select one textbox at a time. I'm not sure what's wrong with my code. Here's the snippet of the code: <ht ...

The Node.js promise failure can be unpredictable, despite being properly managed

In my journey to master MongoDB, I am currently exploring its capabilities by building a basic blog application. However, I have encountered an issue with the code responsible for saving blog posts - it seems to be inconsistent in its success rate, sometim ...

The functionality of if and else statements within local storage is not functioning as

I've been working on implementing a styleswitcher for my website. I successfully created a dropdown menu and saved it in localstorage. However, I'm facing an issue when trying to use the localstorage information to trigger an alert() through if a ...

Extending image across several rows within a form

I'm facing an issue with trying to display an image across multiple rows in a horizontal Bootstrap form. The current layout looks like the image below. However, I want the profile picture on the left to span multiple rows of the input field. As it sta ...

Encountering a TypeError when attempting to pass the onChange function as props to Grandchildren due to 'this' being undefined

Struggling to pass an onChange function from parent to grandchild component and encountering an error. TypeError: this is undefined The code snippet causing the issue: const TaskTable = React.createClass({ getInitialState: function() { return {dat ...

CSS: What's with the weird gray element appearing in Safari?

Does anyone have a solution for removing the grey layer (cf the image) in Safari? This issue does not occur in Chrome. The structure is as follows: <div class="class1"> <div class="class2"> <select> ... </selec ...

Coloring vertices in a Three.js geometry: A guide to assigning vibrant hues

This inquiry was previously addressed in this thread: Threejs: assign different colors to each vertex in a geometry. However, since that discussion is dated, the solutions provided may not be applicable to current versions of three.js. The latest versions ...

Is it possible to execute a function upon exiting my Node application?

Currently, I'm developing a project for my school using Node.js on a Raspberry Pi. The script I have created will be running for extended periods of time to control LEDs. Is there a method that allows me to execute a function upon exiting the program ...