When I adjust the page size, the navbar stays hidden after clicking

Trying to implement a toggle button for the navigation bar. The objective is to hide the navbar on screens smaller than 667px and display a toggle button instead. Clicking the button should toggle the visibility of the navbar items.

The toggle button works correctly when the screen width is below 667px, but the navbar remains hidden on screens wider than 667px.

HTML

            <div id="navbar" class="navbar">
                <div class="logo">
                    <a href="index.html"><img src="images/logo.png" width="125px" alt="logo"></a>
                </div>
                <nav>
                    <ul class="slide">
                        <li><a href="#home">Home</a></li>
                        <li><a href="#products">Products</a></li>
                        <li><a href="#contact">Contact</a></li>  
                    </ul>
                    <a class="navbar-toggle">
                        <i class="fa fa-bars"></i>
                    </a> 
                </nav>
            </div>

CSS


.navbar{
    display: flex;
    align-items: center;
    padding: 20px;
}

.slide {
    display: block;
}

.navbar-toggle {
    flex: 1;
    text-align: right;
    display: inline-block;
    list-style: none;
    cursor: pointer;
    display: none;
}


@media screen and (max-width: 667px) {
    .navbar-toggle {
        display: block;
    }
    .slide {
        display: none;
    }
}

JS

$(document).ready(function() {
  
      $('.navbar-toggle').on('click', function(){
        $('.slide').toggle();
        return false;
      });

});

Answer №1

To fix the issue, add the !important flag to the min-width property like below:

@media screen and (min-width: 667px) {
  .slide {
    display: block!important;
  }
}

$('.navbar-toggle').on('click', function(){
        $('.slide').toggle();
        return false;
      });
.navbar{
    display: flex;
    align-items: center;
    padding: 20px;
}

.slide {
    display: block;
}

.navbar-toggle {
    flex: 1;
    text-align: right;
    display: inline-block;
    list-style: none;
    cursor: pointer;
    display: none;
}


@media screen and (max-width: 667px) {
    .navbar-toggle {
        display: block;
    }
    .slide {
        display: none;
    }
}

@media screen and (min-width: 667px) {
  .slide {
    display: block!important;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div id="navbar" class="navbar">
      <div class="logo">
          <a href="index.html"><img src="images/logo.png" width="125px" alt="logo"></a>
      </div>
      <nav>
          <ul class="slide">
              <li><a href="#home">Home</a></li>
              <li><a href="#products">Products</a></li>
              <li><a href="#contact">Contact</a></li>  
          </ul>
          <a class="navbar-toggle">
              <i class="fa fa-bars"></i>
          </a> 
      </nav>
  </div>

Answer №2

To ensure dynamic responsiveness on your website, it is important to set up a dedicated event listener that will execute a function each time a specific event occurs. With jQuery, you can easily achieve this by listening for window resizing events using the .on('resize') method. This event is triggered whenever the window is resized. Simply integrate the following code snippet into your JavaScript file:

$(window).on('resize', function () {
    if ($(window).width() > 667) {
        $('.slide').show();
    }
});

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

Error: The function openCity() has not been defined

I'm currently working on creating a form that will allow me to store images into a PostgreSQL database. The database contains a single table with two fields: ID and IMG, which is of type bytea. The page has 2 tabs, and I have a function called 'o ...

Guide to embedding a component within another component using route based rendering

My routing configuration looks like this: <Provider store={store}> <BrowserRouter> <Route path="/" component={App} /> <Route path="/customers" component={Customers} /> <Route path="/tickets" componen ...

Tips for sending php data to javascript efficiently

I'm wondering about the best way to retrieve HTML table rows and display the values on another page upon clicking a button. Ideally, I would like to store these variables in a session for future use. Any advice on how to proceed? ...

The area surrounding inline content, both above and below

Can you explain the space above and below inline content? This phenomenon can be seen here: http://jsbin.com/vertical-spacing-weirdness/ If you look closely, there is a white area between the div/table and the span even though the span does not have ...

When a page is changed, the Vue.js Active Menu color remains enabled

Check out my website at . I want to customize the navigation bar so that only the active page's navbar li is colored in red. <div class="navigation-items"> <ul class="nav-list"> <li class="nav-item"><nuxt-link to="/en" ...

Showing PHP array in the JavaScript console

I have a straightforward AJAX script that sends 3 variables to an external PHP script. The external script then adds them into an array and sends the array back. I want to output this array in the JavaScript console to check if the variables are being pass ...

Design interactive images in NativeScript

I need assistance setting up clickable images in NativeScript. My goal is to arrange 5 images horizontally, and when one image is clicked, the images to its left should change their values. Here's what I've attempted: <Label col="0" row="0" ...

I am looking to automatically add a line of HTML text to the notifications list without requiring the user to manually refresh the page

Having trouble articulating the correct term or language I need, making it difficult to search. Q: How can I push a line of text from the server side to the user? I am developing an MVC 4 application using asp.net and c# in .net4. One page will feature a ...

Error in ng-repeat loop: detecting duplicates when none are present

$scope.subjects = [ "Computer Security", "Graphics and Multimedia", "Networks", "Computer Science and Engineering", "Game Design", "Programming", "Information Technology", "Software Engineering", "Technology Manageme ...

Different methods to retrieve content within a div that is located on a separate, included page

It's a bit tricky to come up with a title for this topic, but essentially, I'm trying to figure out how to get content from an included page into a specific div using HTML and PHP. Let me break it down: In the header.php file, we have the follo ...

Change justify-content-between to something else

After successfully fixing the issue with aligning the navbar brand in the middle of my navigation bar, I am now facing a new challenge. I want to add a button right before the right navigation toggle, but all my attempts have been unsuccessful so far. I&ap ...

Tips for concurrently and asynchronously executing multiple AJAX requests

I am working with a javascript object named Agendamento which includes the following key parts: const Agendamento = { // ... storeResultados: async function (consulta) { //... $.ajax({ type: 'POST', ...

Implementing Gatsby-js for client-side JavaScript directly within a blog post is a powerful

I've been working on setting up a blog using Gatsby-JS and have run into a bit of an issue. My posts, written in markdown, include inline javascript like this: <script>window.alert("hello");</script> When I test the site with "Gatsby ser ...

Transmitting an image encoded in base64 using Ajax and form data

My client has a requirement to collect form data and capture a signature using the SignaturePad library. I have managed to create a solution using Ajax, but I am facing difficulty in making both functionalities work together. When I send image data like t ...

Is there a more effective way to structure my code than using multiple "IF/ELSE" statements?

Here is the current code snippet that I have: (category=="Ljud & Bild") ? byId("nav_sub_ljud_bild").style.display='block' : byId("nav_sub_ljud_bild").style.display='none'; (category=="Datorer") ? byId("nav_sub_datorer").style.disp ...

Issues arise when attempting to enforce type-safety in TypeScript while using the JSON.parse

Is it possible that type-safety is compromised in TypeScript when dealing with JSON parsing? I should be triggering an error, but I'm not: interface Person { name: string } const person: Person = somePossibleFalsey ? JSON.parse(db.person) : undefi ...

Track user engagement across multiple platforms

Looking for solutions to log system-wide user activity in my Electron app. I want to track mouse-clicks and keystrokes to determine if the user is inactive for a certain period of time, triggering a timer reset within the application. I believe I may nee ...

Eliminating the need for RequireJS in the Typescript Visual Studio project template

After integrating RequireJS into my Typescript template using the nuget package manager, I found that it was more than what I needed and decided to uninstall it. Even though I removed the package through nuget and the files were deleted properly, my Typesc ...

Issue with Angular FormControl Pattern Validator failing to validate against regex pattern

My goal is to restrict a text input field to specific characters only. I am looking to allow: alphanumeric characters (a-z A-Z 0-9) 3 special characters (comma, dash, single quotation mark) : , - ' A few accented characters: à â ç è é ê î ô ...

Permit the use of the "&" character in mailto href links

When including an email mailto href link and using a & character in the subject, it can cause issues with code rendering. For example, if the subject is "Oil & Gas," only "Oil" may show up. In most cases, you could simply replace the & with th ...