Navbar remains stuck in expanded position after screen size decreases

I'm currently in the process of developing a football-focused website and am tackling the navigation bar. I've implemented code that allows the navbar to collapse with a hamburger button when the screen size shrinks. However, once I resize the screen back to its original width, the navbar content disappears.

Below is the snippet of my code:

const navbar = document.getElementById('navbar')
let number = 0

function toggleFunction() {

  console.log(getComputedStyle(navbar).display)
  if (number === 1) {
    navbar.style.display = 'none'
    number -= 1
  } else {
    navbar.style.display = 'inline-block'
    navbar.style.position = 'absolute'
    navbar.style.top = '75px'
    navbar.style.width = '100%'
    navbar.style.textAlign = 'center'
    navbar.style.padding = ' 5px 0'
    navbar.style.background = 'orange'
    navbar.style.height = "auto";
    number += 1
  }

  console.log(navbar)
}
.toggle-btn {
  width: 35px;
  position: absolute;
  right: 80px;
  top: 25px;
  display: none;
}

.toggle-btn span {
  display: inline-block;
  width: 100%;
  height: 2px;
  background-color: #fff;
  float: left;
  margin-bottom: 8px;
}

@media (max-width: 800px) {
  .toggle-btn {
    display: block;
  }
  #navbar {
    display: none;
  }
  #header {
    display: block;
  }
}

@media (min-width: 801px) {
  #navbar {
    display: inline-flex;
    width: 100%;
    justify-content: space-evenly;
    padding-left: 15%;
    align-self: center;
    height: 75px;
    align-items: center;
  }
}

#header {
  display: inline-flex;
  width: 100%;
  color: #fff;
  background-color: #000;
  height: 75px;
}

#navbar {
  display: inline-flex;
  width: 100%;
  justify-content: space-evenly;
  padding-left: 15%;
  align-self: center;
  height: 75px;
  align-items: center;
}
<div class="toggle-btn" onclick="toggleFunction()">
  <span></span>
  <span></span>
  <span></span>
</div>

<nav id="header">
  <img src="pantherlogo.png" alt="Beverly Panthers Logo" id="logo">
  <div id="navbar">
    <h3><a href="index.html">HOME</a></h3>
    <h3><a href="news.html">NEWS</a></h3>
    <h3><a href="team.html">TEAMS</a></h3>
    <h3><a href="history.html">HISTORY</a></h3>
    <h3><a href="contacts.html">CONTACTS</a></h3>
  </div>
</nav>
<div id="top">
  <img src="footballimg.png" alt="football" id="footballimg">
  <div id="motto">
    <h1>Restore our pride.</h1>
  </div>
</div>

Answer №1

Here are two scenarios to consider:

Scenario 1:

When resizing the screen, the navigation items will be hidden and a burger button will appear. Clicking on this button will expand it to reveal the items. If you resize the screen without clicking the burger button first, it will return to its original appearance.

Scenario 2:

Similarly, resizing the screen will hide the nav items and display the burger button. However, clicking on the burger button triggers an event listener that runs the toggleFunction, resulting in the navbar element being hidden with the CSS property style.display = "none". This inline styling overrides media queries and CSS classes.

A recommended solution (general):

To address this issue, create utility classes for "hidden" and "visible" states of your navbar and apply them through event handlers. For example:

.visible {
  display: inline-flex;
}

@media screen and (max-width: 800px) {
  #navbar {
    display: none;
    /* other styling modifications */
  }
}

Then, utilize JavaScript to toggle the visibility of the navbar by adding or removing the "visible" class as needed.

A specific suggestion:

In your case, remove the conflicting styles for navbar at the bottom of your file to prevent CSS specificity conflicts. Instead, insert the following rule within the mobile view media query:

@media (max-width: 800px) {
    /* Other rules */

    #navbar.visible {
        display: inline-block;
        position: absolute;
        top: 75px;
        width: 100%;
        text-align: center;
        padding: 5px 0px;
        background: orange;
        height: auto;
    }
}

This adjustment ensures that the desired styling is applied only when the navbar has the "visible" class. Update your toggleFunction accordingly to manage the visibility state effectively.

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

Using CSS to Position a Circle at the Top of a Border

Breaking down the complex issue into a simple statement, I am dealing with a blue circle inside a box with a red border. How can I ensure that the circle remains centered while overlapping the top horizontal line of the box's border? I tried differe ...

What is the method to calculate row height in bootstrap framework?

I have limited knowledge of HTML and CSS, so I am struggling to address an issue on my website. Despite using jQuery and Bootstrap in my template, adjusting the stylesheet has not resolved the problem. The issue seems to be related to the line-height set b ...

"Utilizing AngularJS's ng-options feature to dynamically populate a select dropdown

Is there a way to set a default value in ng-options based on ajax results? <select ng-model="model.stuff" ng-options="o.name for o in options track by o.id"></select> In my controller, I fetch data using the following code: $http.get("myurl" ...

Essential components to include in Bootstrap 4 customization

In my current application, I am utilizing bootstrap and aiming to solely customize the primary color in the provided scss file below: // Custom.scss $theme-colors: ( "primary": #243B55 ); // Option A: Include all of Bootstrap @import "../node_module ...

Having trouble with array slicing functionality?

I received a json list and stored it in an array. {"event_date": "2016-12-07 01:39:41","created_at": "15/11/2016 às 06:10"} Within this list, there is an attribute called "_date": "2016-12-07 01:39:41". I am attempting to extract the year '2016&apo ...

Troubleshooting Promise Rejection in AWS Lambda with Node.js

I encountered a problem with one of my AWS Lambda Node JS functions when making the function call from axios in my Next JS frontend. The initial invocation of the function is successful and returns the expected result, however, on subsequent calls I rece ...

The Datetimepicker component outputs the date in datetime format rather than a timestamp

Currently, I am utilizing the datetimepicker JavaScript script with specific implemented logic: <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth(); var yy = today.getF ...

What is the best way to extract a substring separated by two line breaks using a specific index?

Consider having the following string: Apple Banana Pear Pineapple Grapefruit Kiwi Lime Lemon Cherry If I am interested in extracting the line: Pineapple Grapefruit Kiwi how can I achieve this by identifying any index within the second line and locatin ...

"Enhance Your Website Navigation with a Expand/Collapse Menu Using

After stumbling upon this code that allows a menu to collapse when the user clicks on the minus sign, I noticed that it displays all the contents within the Main Item when the page first loads. My goal is to only show the Main Item when the page initially ...

Utilizing Node and MongoDB to generate a shareable Favorites list with a unique URL

After spending a significant amount of time searching, I seem to be using the wrong search terms because I am struggling to find what I need. Essentially, my goal is to allow users to select items to add to a favorites list and then generate a unique URL t ...

What is the method for defining a schema property as a SubDocument type in Mongoose?

I'm looking to achieve something along these lines: var userSchema = new Schema({ local: localSchema, facebook: facebookSchema, twitter: twitterSchema, google: googleSchema }); However, it appears that a Schema is not considered a valid Sche ...

working with variables in javascript

let elements = new Array("apple", "banana", "orange"); let elementsRef = elements; elements.push("grape"); console.debug(elementsRef); console.debug(elements); I find it confusing how elements and elementsRef are considered the same even after adding "gra ...

Display Material Popup in Angular before user leaves the page

My goal is to display an Angular Material Dialog Box (Popup window) when the user clicks the Chrome Window Close button. The Dialog modal should prompt the user if they want to save changes or cancel. However, the modal only appears for a brief moment and ...

In JavaScript, we are comparing two arrays that contain objects. We will then segregate the identical objects into one array and the unique objects into another

Here are sample arrays: const firstArray = [ { name: "q", age: 10, size: "M", }, { name: "w", age: 10, size: "S", }, { name: "e", age: 10, size: "M", ...

What is the best way to create text that dynamically wraps or moves to the next line?

My design has a slight issue: https://i.sstatic.net/riLOQ.png The text in the middle sometimes ruins the look. For reference, check out this https://i.sstatic.net/mdNd8.png I need the text to go down and continue from where it started after reaching a c ...

Refresh the page without submitting any information

Can anyone help me figure out how to refresh the page without triggering any posting when I press F5 or Ctrl+F5? I attempted the following code, but it doesn't seem to be working for me. $(document).ready(function(){ $(document).keyup(functio ...

When working with React and trying to update data using the useEffect hook, I encountered an issue with an Array data. Unfortunately, using map or Object.keys(data).map did not produce the desired results. Can anyone provide guidance on

After using the useEffect hook to update the data, I noticed that the data is an array when inspected in the DEV tools. However, when attempting to traverse the data using the map function, an error stating 'data.map is not a function' is returne ...

MongoDB's implementation of prototypal inheritance within stored objects

Is it possible for MongoDB to save an object with another object as its 'prototype' in the same schema? For example: Assume we have this object in the database: { name : 'foo', lastName : 'bar', email : '<a hre ...

Adding one class at a time, with each new class being added every second

My goal is to add classes one by one [test0 test1 test2] up to 10, with each class being added after one second. $('.rating-block').AddClass('test0 test1 test2 ... test10' ); I am experimenting with the following code, but I don' ...

AngularJS ng-repeat filter fails to function with changing field names dynamically

Here is a code snippet I am working with: <input type="text" ng-model="filteredText"> <ul> <li ng-repeat="item in data | filter: {Name : filteredText}"> </li> </ul> Initially, when the Name property is static, every ...