Is there a way to embed a JS media query inside the sticky navbar function for both the onscroll and onclick events?

I've been exploring media queries in JavaScript, and it seems like they work well when the window is resized. However, when nested within onscroll and onclick functions, things start to get a bit tricky.

If you run the following code and resize the window, everything seems to be fine. But if you set the width of your browser window to 768px, the media query kicks in. Unfortunately, when you start scrolling, it reverts back to the tablet media query, changing the elements' color to tablet mode instead of desktop mode. Even resizing the window doesn't seem to fix this issue when it's nested within a function. How can this be resolved? Make sure to run this code in Full Page mode to resize the window properly.

window.onscroll = function() {stickynavbar();}

var element1 = document.getElementById("element1");
var element2 = document.getElementById("element2");
var myBtn = document.getElementsByTagName("button")[0];

var desktop = window.matchMedia("(min-width: 768px)");
var tablet = window.matchMedia("(min-width: 600px)");

function stickynavbar() {

  function element1Query(desktop){
      if (desktop.matches){
          element1.style.background = "darkred";
      }
      else{
          element1.style.background = "black";
      }
  }
  element1Query(desktop);
  desktop.addListener(element1Query);

  function element1TQuery(tablet){
      if (tablet.matches){
          element1.style.background = "darkblue";
      }
      else{
          element1.style.background = "black";
      }
  }
  element1TQuery(tablet);
  tablet.addListener(element1TQuery);

  function element2Query(desktop){
      if (desktop.matches){
          element2.style.background = "darkgreen";
      }
      else{
          element2.style.background = "gray";
      }
  }
  element2Query(desktop);
  desktop.addListener(element2Query);

  function element2TQuery(tablet){
      if (tablet.matches){
          element2.style.background = "yellow";
      }
      else{
          element2.style.background = "gray";
      }
  }

  element2TQuery(tablet);
  tablet.addListener(element2TQuery);
}
.element1{
        position: absolute;
        top: 0;
        left: 0;
        width: 50%;
        height: 1000px;
        background: black;
    }
    .element2{
        position: absolute;
        top: 0;
        right: 0;
        width: 50%;
        height: 1000px;
        background: gray;
    }
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div class="element1" id="element1"></div>
<div class="element2" id="element2"></div>

</body>
</html>

Answer №1

Do you want it to look like this?

window.onscroll = function() {stickynavbar();}

var element1 = document.getElementById("element1");
var element2 = document.getElementById("element2");
var myBtn = document.getElementsByTagName("button")[0];

var desktop = window.matchMedia("(min-width: 768px)");
var tablet = window.matchMedia("(max-width: 600px)");

function stickynavbar() {

  function element1Query(desktop){
      if (desktop.matches){
          element1.style.background = "darkred";
      }
      else{
          element1.style.background = "black";
      }
  }
  element1Query(desktop);
  desktop.addListener(element1Query);

  function element1TQuery(tablet){
      if (tablet.matches){
          element1.style.background = "darkblue";
      }
      else{
          element1.style.background = "black";
      }
  }
  element1TQuery(tablet);
  tablet.addListener(element1TQuery);

  function element2Query(desktop){
      if (desktop.matches){
          element2.style.background = "darkgreen";
      }
      else{
          element2.style.background = "gray";
      }
  }
  element2Query(desktop);
  desktop.addListener(element2Query);

  function element2TQuery(tablet){
      if (tablet.matches){
          element2.style.background = "yellow";
      }
      else{
          element2.style.background = "gray";
      }
  }

  element2TQuery(tablet);
  tablet.addListener(element2TQuery);
}
.element1{
        position: absolute;
        top: 0;
        left: 0;
        width: 50%;
        height: 1000px;
        background: black;
    }
    .element2{
        position: absolute;
        top: 0;
        right: 0;
        width: 50%;
        height: 1000px;
        background: gray;
    }
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div class="element1" id="element1"></div>
<div class="element2" id="element2"></div>

</body>
</html>

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

Oops! An error occurred in AngularJs: "TypeError: $scope.todos.push is not a

I am currently facing an issue while using the $http.get method to add a todo from my controller to my database. The error message "TypeError: $scope.todos.push is not a function" keeps appearing, despite trying various solutions suggested by similar quest ...

What is the process for sending a POST request from a React app to a Node.js Express server?

I watched a tutorial video on resolving the CORS issue, which worked well for GET requests. However, I encountered an issue when attempting to send a POST request. Unfortunately, I do not have control over the third-party API and cannot make any changes to ...

An issue is preventing the Angular 2+ http service from making the requested call to the server

I am looking to create a model class that can access services in Angular. Let's say I have the following endpoints: /book/:id /book/:id/author I want to use a service called BooksService to retrieve a list of Book instances. These instances should ...

On successful completion of the $.post request, hide a group of div elements with a fade-out

I need help fading out a set of div elements based on the response received from an ajax call. The current code I have doesn't seem to be doing what I intended. Can someone point out where I might be going wrong? $('.view_result').click(fu ...

Display the header on every single page using puppeteer

            Whenever I enable displayHeaderFooter, the header does not display. It only works if I add margin to @page in my CSS, but this causes the page height to increase by the margin value and content to overflow beyond the page boundaries. Is ...

Using vanilla JavaScript with AJAX, the second asynchronous post will only be sent once the first post has been successfully sent

I am in the process of creating a HotSpot that offers internet access once users input their email addresses. To make this function properly, I need to execute two separate AJAX posts: The first one sends hidden username and password details to the rout ...

Adding parameters to Angular HTML element selector directives can be achieved by utilizing the directive's input properties

I have created a straightforward directive that targets an img element. @Directive( { selector: 'img' } ) export class ImageDirective { ... } Is there a way for me to add a boolean parameter to this directive? @Input() enabled: boolean = fals ...

Searching for elements by tag name in JavaScript

Recently, I attempted to create JavaScript code that would highlight an element when a user hovers their cursor over it. My approach involves adding an event listener to every child within the first "nav" tag in the current document: let navigation = docum ...

What are some alternative methods for organizing folder structure in Express Handlebars when managing views?

Is there a more efficient way to render HTML files without constantly needing them to have different names? I'm looking for a method where handlebars can identify which file in which folder to render, without encountering conflicts with files of the s ...

IE9 causing trouble with CSS vertical alignment

I'm trying to center a button with text using Cuffon for the font, but I can't get it to align vertically and horizontally. The text-align property is working fine, but vertical align isn't. Here's the code for my div block: btndownlo ...

Shortcuts for $scope variables in AngularJS templates

Within my controller, I often set: $scope.currentThing.data For different parts of my template, sometimes I require currentThing.data.response[0].hello and other times currentThing.data.otherStuff[0].goodbye //or currentThing.data.anotherThing[0].goo ...

An error occurs when trying to load data into a grid upon clicking, resulting in an Uncaught TypeError: Unable to access properties of undefined (specifically 'dataState')

I have implemented a grid in React using a specific library, and I want to populate the grid with data fetched from an API call when the user clicks on a button labeled Fetch Products. However, I encounter an error during debugging: Uncaught (in promise) T ...

What is preventing me from successfully sending form data using axios?

I've encountered an issue while consuming an API that requires a filter series to be sent within a formData. When I test it with Postman, everything works smoothly. I also tried using other libraries and had no problems. However, when attempting to do ...

When I attempt to send a PUT request, the req.body object appears to be empty. This issue is occurring even though I have implemented the method override middleware

I am currently facing an issue with updating a form using the put method. To ensure that my form utilizes a PUT request instead of a POST, I have implemented the method override middleware. However, upon checking the req.body through console log, it appear ...

What are some solutions for repairing the issue of horizontal collapse?

I am currently using Bootstrap 5 to create my website template, and I have encountered a problem: After clicking the "Menu" button, not all of the sidebar elements fade out as expected (I'm attempting to use the horizontal collapsing plugin where the ...

Tips for choosing the parent's parent and applying a width of 100%

I am currently facing some challenges while creating a simple navigation bar from scratch. I am struggling with setting specific widths, especially wanting .navbarDropBtn to align its width with .navbarMain. However, it seems to only match the width of the ...

Strategies for successfully passing and showcasing the result of a calculation on a fresh view or component within Angular

I have developed a basic calculator application with two main components: Calculator and Result. The Angular router is used to navigate between these components. Now, I am looking for a way to dynamically display the calculation result from the Calculator ...

Adjust the height of the tabs bar in the Guake terminal

Is there a way to reduce the height of the tabs bar in the Guake terminal? I found a solution for GNOME terminal on this post, where they mentioned editing ~/.config/gtk-3.0/gtk.css. Is there a similar method for achieving this in Guake terminal? ...

Is it possible to automatically move text to the next line once it reaches a specific character limit using HTML/CSS/PHP?

Is there a way to handle text when it reaches the ceiling or exceeds a certain number of characters so that it goes to the next line instead of showing a scrollbar? I have a div element where I display text retrieved from a MySQL database, and sometimes th ...

Troubleshooting issues with media queries related to device pixel ratio

My media queries in LESS are functioning correctly on the desktop, but encountering issues when tested on an iPad2 or Samsung Galaxy 4 phone. It appears that the device-pixel-ratio is causing disruptions. I attempted to reduce the min-device-pixel-ratio to ...