Executing an onscroll function based on window.innerWidth in JavaScript

I want to trigger my scroller function only when the window width exceeds 599 pixels and the user is scrolling. The function itself works fine during scrolling, but adding an event listener seems to cause it not to work. Can anyone offer guidance on how to fix this issue?

//only execute scroller if window size is greater than 599
window.addEventListener('resize', function(){
  if(window.innerWidth > 599){
    window.onscroll = function() {scroller()}
  }
};  

const scroller = () => {
  //PROGRESS SCROLL BAR
  var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
  var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var scrolled = (winScroll / height) * 100;
  document.getElementById("scrollBar").style.width = scrolled + "%";

  //COLLAPSE HEADER WHEN SCROLLING
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    document.querySelector("header").style.height = "5rem";
    document.querySelector("h1").style.display = "none";
    document.querySelector("nav ul").style.top = "1rem";
    document.getElementById("wrapper").style.marginTop = "10rem";
    document.getElementById("scrollContainer").style.top = "5rem";
    document.getElementById("scrollBar").style.top = "5rem";
  } else {
    document.querySelector("header").style.height = "15rem";
    document.querySelector("h1").style.display = "inherit";
    document.querySelector("nav ul").style.top = "3rem";
    document.getElementById("wrapper").style.marginTop = "15rem";
    document.getElementById("scrollContainer").style.top = "inherit";
    document.getElementById("scrollBar").style.top = "inherit";
  } 
}; 

Answer №1

To determine if the viewport is wider than 599 pixels, you can monitor the innerWidth property within the scroll event listener.

window.addEventListener("scroll", function(){
    if(window.innerWidth > 599) scroller();
});

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

why doesn't the promise return the record after it has been updated

After completing the form, I proceed to send it as an object to the API NodeJS. The following is the execution function: .post('/create/card', function (req, res) { var rb = req.body, obj = { query: { $set ...

Express server continuously returning 404 error for all requests originating from the index page

Experiencing a challenge with the express/gulpfile.js code. Express can serve the index.html without issue, but it fails to navigate to the lib/* directory resulting in all requests for resources at the top of my index.html returning 404 errors. Browser-s ...

The data from the server is inaccessible to node.js

I am a beginner in nodejs and jquery, trying to retrieve data from a server and use it to update a webpage: Using jquery on the client side: I would like to change the text inside '#info' element with the data fetched from the server. $('# ...

What is the best way to make text appear as if it is floating in Jade or HTML?

Currently, I am facing an issue with a Jade file that displays an error message when a user tries to log in with incorrect credentials. The main problem is that this error message disrupts the alignment of everything else on the page, as it is just a regul ...

Does the first Ajax call always finish first in the order of Ajax calls?

In my code, I have an ajax call that triggers another ajax call based on its return value. The URL parameter of the second call is modified by the output of the first one. These two calls are interrelated as the first call feeds the URL parameter for the s ...

Is Aurelia-Fetch reliant on whatwg-fetch as a dependency in its codebase?

I am currently in the process of updating my Aurelia project from a beta version to the March version. One of the issues I encountered is: Cannot locate name 'Request'. Searching online led me to this problem on GitHub: https://github.com/au ...

Using two distinct buttons to submit information using various methods

When button 1 is clicked, I want it to update the row. When button 2 is clicked, I want it to create another row. This is the controller code for updating: public function update(Request $request, $id){ $pay = Payroll::find($id); $pay ->idnumb ...

The data seems to have disappeared from the HTTP requests in my Express and Mongoose project

I'm currently working on some files for a recipe app project. One of the files is recipe.js, where I have defined the Mongoose Schema for recipes and comments. The code snippet from the file looks like this: const express = require('express&apos ...

A guide on performing CRUD operations on locally stored JSON data using React JS

Retrieve the JSON data from any endpoint and store it locally fetch("any endpoint") .then((response) => response.json()) .then((responseJson) => { this.state ={ data:responseJson } }) How to perform CRUD operations on a sample JSO ...

How can I modify the parent form element to only evaluate the expression at the text node, without affecting Angular interpolation?

Currently, I am in the process of developing an eCommerce platform and utilizing angular to construct a widget on product detail pages. Unfortunately, my control over the initial HTML rendered for the browser is quite limited. While most tasks related to m ...

Sorting data in a Footable table by an unfinished line

My data table contains various lines like: 97.5%, 10/30, 41 RPM, 3.6 seconds, $4750, $100 When I set the type data-type = "number" in the rows, everything is stripped except for the numbers. However, I need the output to remain complete as shown in the ex ...

JavaScript Glitches

Embarking on the journey of web design and programming, I am venturing into the world of creating a simple gallery using JavaScript. Despite the convenience offered by jQuery, unfortunately, it is off-limits for this particular assignment. The challenge l ...

Unable to establish API connection in node.js

As a novice, I recently delved into the world of APIs using node.js. My goal was to fetch data from a simple API for practice. This venture is just an experiment and any assistance or guidance on connecting to APIs, especially those requiring an API key, ...

Ways to conceal components of an external widget on my site

I'm attempting to add a chat widget to my website and I'm looking to hide specific elements within the widget. The chat function is provided by Tidio, but I believe this applies to most widgets. My main goal is to conceal a button that minimize ...

Nextjs throws an error indicating that the element type is invalid when an object is passed into the export function

Currently, I am in the process of developing a blog page and facing an issue while attempting to pass generic data stored in an object inside an array. The specific error message I am encountering is "Error: Element type is invalid: expected a string (for ...

Error message occurred stating "error running npm start due to spawn C:WINDOWSSystem32WindowsPowerShellv1.0powershell ENOENT"

Whenever I attempt to run npm start, this is the issue that arises. It seems like there might be a problem with PowerShell rather than npm because npm successfully starts the development server. By the way, I created a basic React app using npx create-reac ...

The function in the method (in quasar) is not activated by the @change event

When I select an option, I am trying to retrieve the selected value in a function called within my methods. However, the function does not seem to be triggering. This is my code: From the template : <q-select filled v-model="invoice_product.tarri ...

Load a form using ajax and submit it using jQuery

For a while now, I have been facing challenges in figuring out what's going wrong with my code. The issue arises when I try to submit a form using jQuery that was loaded through ajax. The form loads perfectly fine within a div after invoking the ajax ...

The size of Bootstrap 3 columns adjusts dynamically based on the width of the window as the page is being

I am facing an issue with the layout of my bootstrap site when resizing the 3 horizontal columns based on the window size upon page load. Currently, I have a script that adjusts the height of each column to match the tallest one so they appear uniform whe ...

Adjust the checked state of the checkbox based on the outcome of the promise's data

Whenever the checkbox is clicked and the resolved data in a promise is false, I want the checkbox to remain unchecked. If the data is true, then the checkbox should be checked. I have set up a codesandbox for this purpose. This example utilizes react and ...