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

Choose the grandparent of an element's parent

Is there a way to select the grandparent element of a child in Javascript without having to chain the .parentElement method twice? Specifically, I am looking for a method that can substitute .parentElement.parentElement when selecting the desired element, ...

Exploring the world of Typescript and Angular Filter functionalities

I am looking to utilize one of my Angular Filters in my controller as a function. I came across a solution on this page: How to use a filter in a controler The last answer provided exactly what I needed, so I implemented it in my JS code: var MyFunc ...

Updating Vue component property when Vuex store state changes: A step-by-step guide

As I work on developing a straightforward presentation tool using Vue js and Vuex to manage the app state, I am facing a challenge in implementing a feature that tracks changes in the presentation such as title modifications or slide additions/removals. Cu ...

Retrieving localStorage data from another webpage

I recently created an account and I hope my question is clear. I have two separate pages on my website - one for a menu and the other for an HTML game. The menu has two buttons, one to start a new game and the other to continue from where you left off. How ...

Discover the process of generating streams from strings in Node.Js

I am currently working with the library ya-csv, which requires either a file or stream input. However, I only have a string available. Is there a way to convert this string into a stream in Node.js? ...

Using Firebase to connect and disconnect from state in React with Re-base

I'm encountering some issues with React and Firebase while using the re-base module. When attempting to retrieve content from Firebase across different components in my app, I run into a problem. On one component/"page," which is home, I have the abi ...

Having difficulty invoking a JavaScript function through PHP

My goal is to achieve the following: <html> <script type="text/javascript" src="jquery.js"></script> <a id="random">before</a> <script> function test(a) { document.getElementById('random').innerHTM ...

Storing new li and ul elements to the database by utilizing an array for dynamic saving

I am in the process of creating a user interface for an application where users can add unordered lists and list items by clicking on "add question". I have successfully designed the front end part and here is a preview: However, I am facing difficulties ...

Updating Variable Values in PHP

Currently, I am working on a project about online shopping using PHP. However, I have encountered an issue regarding changing the currency value. I need to convert the currency to another based on the exchange rate provided. <select onchange=""> ...

Styling may vary between the CSS used in the development environment and the one

After launching my web page on a server yesterday, I noticed some differences compared to the development environment. There are a few elements with altered colors, but my main concern is the appearance of the jQuery autocomplete search widget. Instead o ...

The JSColor onChange event is throwing an error indicating that the function is not defined

When attempting to use the onChange event for JSColor to call a function, I consistently encounter an error indicating that the function is not defined. The code snippet below illustrates the issue: export class NavBar extends React.Component { constr ...

Create a variable to store the sum value when iterating through a range using jQuery's

Currently, I am in the process of developing a specialized calculator that requires me to calculate the sum of variables within my jQuery.each loop for a specific range from 0 to 4 (equivalent to 5 years). While I have come across several informative reso ...

Determine the Size of an Image File on Internet Explorer

Is there an alternative method? How can I retrieve file size without relying on ActiveX in JavaScript? I have implemented an image uploading feature with a maximum limit of 1 GB in my script. To determine the size of the uploaded image file using Java ...

What is the method to retrieve values passed to the next() function in Node.js?

For my current project, I am utilizing Node.js in combination with Express.js to develop the back-end. In middleware functions, next() is commonly used to progress through the chain until reaching the final app.VERB() function. My question is, at what poi ...

passing commands from a chrome extension to a content script

I want to set up a hotkey that will activate a function in my content script. The content script (main.js) is run when the page loads from my popup.js file. I've included the command in my manifest.json and I can see in the console log that it is tri ...

Submit information from an HTML form to a PHP script and then send the response back to the client using AJAX,

Looking to run a PHP script using AJAX or JavaScript from an HTML form and then receive the results on the HTML page. This is what my changepsw.php file looks like: <?php // PHP script for changing a password via the API. $system = $_POST['syst ...

Converting a blob to base64 and then back to a blob in Node.js may result in varying sizes between the two

I am currently implementing this code in a Node.js application. I have a blob that I am converting to a base64 string and then back to a blob using the following method: // Converting Blob to base64 string via Buffer const buffer = Buffer.from(await myBlob ...

The Angular 9 custom directive is malfunctioning on mobile devices

I recently created a custom directive in Angular 9 that allows users to input only digits and one decimal point. While the directive works perfectly on desktop, it seems not to function at all on mobile devices - almost as if it doesn't exist within t ...

Display the returned view following an AJAX request

Currently, I am trying to search for a specific date in the database using ajax to trigger the function. However, I am encountering a 404 error when I should be receiving the desired outcome, and the ajax call is entering an error mode. Here is the snippet ...

How can I pass the content of a pug input element to a JavaScript function?

Attempting to manipulate data on a database using HTML buttons and encountering an issue when trying to insert data. The setup involves a Pug page called by Node Express, which generally functions well until the insertion process. Here is a snippet from th ...