Modify CSS using JavaScript at a specific screen size

Currently, I am in the process of designing a responsive navigation system which involves implementing a button that dynamically changes the styling of the div #navigation using Javascript. The aim is to toggle between display: none; and display: block; based on user interaction. Everything seems to be working as intended when viewed on small screens. However, an issue arises when I show and hide the navigation on a small screen, then resize the window – the navigation remains hidden. Is there a way to automatically adjust the CSS based on window size?

Below you can find the code snippet that I am currently utilizing (please note that I am new to Javascript): Feel free to experiment by resizing the window, opening and closing the navigation, and resizing again. You will notice that the navigation remains hidden: http://codepen.io/HannesDev/pen/grjdqK


HTML:

<div class="btn-Nav">Navigation</div>
<nav id="nav-hor" role="navigation">
<ul>
   <li>One</li>
   <li>Two</li>
   <li>Three</li>
 </ul>
</nav><!-- #site-navigation -->

CSS:

html{
  background: lime;
}
/* The Button */
.btn-Nav{
  border: 2px solid grey;
  cursor: pointer;

}
/* The button changes to the greyed out closed area on the right */
.btn-Nav_open{
  position: fixed;
  margin-left: 80vw;
  left: 0;
  top: 0;
  width: 20vw;
  height: 100vh;
  background-color: black;
  color: white;
  opacity: .2;
  padding: .2em;
  text-align: center;
  font-size: 3em;
}

/* The Navigation on small screens */
#nav-hor{
  display: none;
  position: fixed;
  overflow-y: scroll;
  top: 0;
  width: 80vw;
  height: 100vh;
  background-color: white;
  z-index: 999;
  border-right: 1px solid grey
}


@media (min-width: 50em) { 
  html{
    background: red;
  }
  /* Don't show the button on bigger screens */
  .btn-Nav{
    display: none;
  }

 /* The Navigation for bigger screens */
  #nav-hor {
    /* Clean up */
    display: flex;
    position: relative;
    overflow: visible;
    width: 100%;
    height: auto;

}

JS:

window.onload = function(){
  document.querySelector('.btn-Nav').onclick = function(){
    // closed
      if(this.className.match('btn-Nav btn-Nav_open')) {
          this.className = 'btn-Nav';
          document.getElementsByClassName("btn-Nav")[0].innerHTML = "Navigation";
          document.getElementById('nav-hor').style.display = "none";
          document.body.style.overflow = "auto";

      }
      // open
      else {
          this.className = 'btn-Nav btn-Nav_open';

          document.getElementsByClassName("btn-Nav")[0].innerHTML = "&#215;";
          document.getElementById('nav-hor').style.display = "block";
          document.body.style.overflow = "hidden";
      }
  };
};

Answer №1

How can I adjust the CSS automatically based on the size of the browser window?

Yes, there is a way to achieve this without using Javascript. CSS provides media queries which allow you to modify styles based on specific conditions. For instance, you can use the following code:

@media only screen and (max-width: 500px) {
    #navigation {
        display: block;
    }
}

In this example, the display of the #navigation element will change to block when the browser window width is less than 500px. You can customize the max-width value as needed. Media queries offer various possibilities, and you can explore more examples at: http://www.w3schools.com/css/css_rwd_mediaqueries.asp.

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

Troubleshooting a JavaScript project involving arrays: Let it pour!

I'm a beginner here and currently enrolled in the Khan Academy programming course, focusing on Javascript. I've hit a roadblock with a project called "Make it rain," where the task is to create raindrops falling on a canvas and resetting back at ...

The requested path /releases/add cannot be located

In my CRUD application, I have a feature that allows users to create releases by adding a version and description. This is achieved through a button and input fields for the details. <button (click)="addRelease(version.value, description.value)" [d ...

Disabling the child element from triggering the parent element's onclick function, while still allowing it to respond to its own content

My list elements have onclick-functions that change the display of each element and its child div, moving them to the top of the list. Clicking again reverses this effect. The issue arises because the child div contains search fields, clickable pictures, ...

Personalized design created using v-for

I have an array being passed through v-for and I want to use the values within the "style" attribute. Essentially, I need to append the value from v-for to style:"left"+EachValue+"px", but I'm having trouble with the syntax. I'm unsure if this ap ...

Creating a Consistent Look for Italic Font Formatting in Tailwind

In an effort to establish consistent typography on a website being developed by my team, we have devised custom utility classes in Tailwind. One of these classes, small-italicized, also requires the text to be italicized. However, it seems that the fontSiz ...

Difficulty in vertical alignment of inline-block elements

Greetings, I am currently working on creating a Resume in HTML. However, I seem to be facing an issue with the inline-block property as the two div elements that should be placed next to each other are not displaying as expected - one of them appears sligh ...

What about employing the position:fixed property to create a "sticky" footer?

I've come across various methods for creating a sticky footer, such as Ryan Fait's approach found here, another one here, and also here. But why go through the trouble of using those techniques when simply applying #footer{position:fixed; bottom ...

Why does my jQuery map code work in version 2.0 but not in version 3.0?

I've encountered an error with a jQuery map snippet that I'm trying to troubleshoot. It was working fine under jQuery 2, but after upgrading to version 3, it doesn't work anymore and I can't figure out why. Feeling stuck! var menuIte ...

Formik: encountering target as undefined while passing Material UI Date Picker as prop to React Component

I'm currently working on developing a component that can be reused. The idea is to pass form fields as props, but I ran into an issue when clicking on the datepicker field. The error message that pops up is: TypeError: target is undefined Any sugge ...

Modifying the value of a local variable results in a corresponding adjustment to the original global variable's value

Within my Node.js program, I have set up an array named "list" in the routes section. This array is populated with values from a function defined in the model. The code for this route looks like: var express = require('express'); var router = ex ...

Issue encountered while importing dependency in Cypress Cucumber framework

Currently facing an issue with importing certain dependencies in Cucumber. The error message I received is as follows: Running: features\my_feature.feature... (1 of 1) Browserslist: caniuse-lite is outdated. P ...

Adjust the panel size accordingly for smaller screens

My application is utilizing the Spotify API to retrieve names and images. These are then displayed on my webpage within cards/panels in the following format: <div class="col-md-4" v-if="type == 'tracks'" v-for="(track, index) in tracks"> ...

Can an excess of CSS impact the speed and performance of a website?

After conducting thorough research on this specific topic, I was unable to locate the precise answer that I require. For instance, there are numerous divs within my project that necessitate a border. One approach is to create a distinct CSS class such as ...

Struggling with a character entity in Javascript? Learn how to escape it and avoid any display issues (such as showing

document.title = ("welcome &rarr; farewell"); Trying to display the arrow symbol "→" but it's not showing correctly. Any tips on how to properly escape it? ...

Removing custom scrollbars using jQuery from an element

Utilizing mCustomScrollbar with jQuery UI dialog boxes. When attempting to initialize mCsutomScrollbar on $(window).load as instructed, it fails because the dialogs are not yet visible. As a workaround, I've had to initiate mCsutomScrollbar on the op ...

Get the selected row value from a Table and convert it into an array. Then, pass this array as a parameter to another function

I need help with logging and storing selected values from a Table component in React My Table component displays data from an API with checkboxes on each row. I'm using the <Table /> Material UI component for React. The documentation states th ...

Navigating through the nested object values of an Axios request's response can be achieved in React JS by using the proper

I am attempting to extract the category_name from my project_category object within the Axios response of my project. This is a singular record, so I do not need to map through an array, but rather access the entire object stored in my state. Here is an ex ...

Display a loading dialog for several asynchronous requests being made via AJAX

When making two asynchronous ajax calls, a loading dialog box is displayed for each call using the code below: jQuery('#msg_writter').show(); After a successful request, the loading dialog is hidden with the following code: jQuery('#msg_w ...

When trying to load AJAX, it does not function properly unless the page is refreshed

I'm currently working on a web page and encountering some difficulties. Within my HTML, I have two divs that are refreshed using AJAX. The issue is that the content loading seems to be inconsistent unless I manually refresh the page or implement a tim ...

Organize pictures and words side by side on both sides at the same time

I am currently facing an issue while trying to load images and quotes vertically on the left and right side of the page. The problem arises with the 3rd image and quote due to an unexpected margin in the CSS code. Despite my efforts, I have not been able t ...