What is the best way to enable this JavaScript function exclusively for a particular width?

Is there a way to make this javascript function active only when the screen width is at least 1070px? Currently, I have two different headers for screens smaller than 1070px, causing padding to be added regardless of the presence of "navbar_top". Can media queries solve this issue?

window.addEventListener('scroll', function() {
    if (window.scrollY > 190) {
        document.getElementById('navbar_top').classList.add('fixed-top');
    } else {
        document.getElementById('navbar_top').classList.remove('fixed-top');
        document.body.style.paddingTop = 170 + 'px';
    }
});

Answer №1

If you need to verify a media query in JavaScript, you can utilize the matchMedia function.

const mediaQuery = window.matchMedia("(min-width: 1070px)");
if(mediaQuery) {
    // Execute your code here
}

Answer №2

The most practical approach to achieving this is by utilizing the media query within the fixed-top class. This ensures that it will consistently be added and removed, with the actual styling being controlled by the CSS rule.

If performance is a concern and you want to avoid unnecessary handler execution, consider using a named function that can be dynamically added and removed from the scroll handler upon initial setup and window resize events.

It's worth noting that the logic in your function regarding adding padding may need some adjustment, as the removal of said padding in the corresponding if condition doesn't seem coherent. It appears that either the padding should always be present or there may be an oversight in the implementation.

Answer №3

If you want the navbar to disappear when the screen size decreases, you have the option to customize your code to handle this action instead of relying on the existing code for fixing the navbar.

//your custom function
function handleScroll() {
    if (window.scrollY > 190) {
        document.getElementById('navbar_top').classList.add('fixed-top');
    } else {
        document.getElementById('navbar_top').classList.remove('fixed-top');
        document.body.style.paddingTop = 170 + 'px';
    }
}
// screen width check
function checkScreenWidth() {
    if (window.matchMedia('(min-width: 1070px)').matches) {
        window.addEventListener('scroll', handleScroll);
    } else {
        window.removeEventListener('scroll', handleScroll);
        // Remove fixed-top class and padding when the screen is small
        navbar.classList.remove('fixed-top');
        document.body.style.paddingTop = '0';
    }
}

checkScreenWidth();

window.addEventListener('resize', checkScreenWidth);

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

Ensuring Data Accuracy Prior to Saving in Zend Framework 1.12

My form includes validations and a function to save data using ajax. Here is the structure of my form: <form name="enquiry_form" method="post" id="enquiry_form"> Full Name: <input name="name" id="name" type="text" pattern="[A-Za-z ]{1,20}" on ...

Angular's ng-submit directive does not use the most up-to-date scope available

I'm currently learning Angular and have been struggling with a particular issue. I have created a form to edit user details. Upon page load, I make an AJAX call to fetch the data of the selected user and populate the scope with the values. Initially, ...

Issue with retrieving duration XML data using Jquery

Could there be a specific explanation as to why the term duration might not function properly in JQuery? For instance, consider this XML snippet: <video description="description etc" duration="43306" id="1144537378001" name="Fashion" thumbnail="http:// ...

What is the best way to have my transparent navigation bar float on top of my background in a parallax-scrolling website?

Currently, I am working on creating a website with a navigation bar that has no background and floats on top of a background image. However, I am facing an issue with my parallax-scrolling website. Whenever the page is scrolled to the second section, the n ...

tips for resizing bootstrap dropdown menu to fill entire page

The image clearly shows that the zabubi solution network platform has a dropdown menu with the label "no request for collaboration to be accepted" on top. The menu occupies half of the page and does not seem to be responsive. Even when the page is resized, ...

I can't seem to understand why the error "bash: ng: command not found" keeps popping up even though I

Ever since I installed Angular CLI and started working with Angular, something strange happened - the ng command suddenly became not found: ng serve -o Here's a screenshot for reference: bash: ng: command not found Oddly enough, when I use the npx c ...

The value of YOUR_VARIABLE in the Node.js process environment appears to be undefined

Having trouble hiding a discord token for my bot, even though I believe dotenv is set up correctly. However, all I keep getting back is undefined. I've gone as far as using nodemon to refresh the server when making changes, but the issue persists. Co ...

A collection of asynchronous requests stemming from a sole request

I am facing a unique ajax scenario that is proving to be quite challenging for me. Here is the specific sequence of events that I need to coordinate: An initial request returns an array of ID numbers. A separate request needs to be sent for each ID in ...

Python script utilizing Selenium to load only JavaScript content and excluding full HTML rendering

As I navigate through the link , I am on the lookout for the search bar marked with the class "search-field". The HTML snippet in question is as follows: from selenium import webdriver import time driver = webdriver.Firefox() driver.get("https://www.takea ...

What are the drawbacks of misusing await as a return statement?

Discovering a unique approach to writing linear code with promises in Javascript, I found the following intriguing but somewhat unconventional method: const return_by_death = new Promise((resolve) => {}); Additionally, const signup = async (req, res) = ...

Having trouble making axios a global instance in my Vue project

Previously, I used to import axios in each Vue component separately when making HTTP requests. An example of this can be seen below: <script lang="ts"> import axios from 'axios'; @Component export default class ExamplePage extend ...

Leverage the basename feature in React Router when rendering on the server side

My website is being hosted from the directory /clientpanel on my server, making the URL http://xxx.yy/clientpanel. The client-side code looks like this: const history = useRouterHistory(createHistory)({ basename: "/clientpanel" }); render( <Ro ...

Show additional information when a row in the Bootstrap Vue table is clicked

I am attempting to create a unique user experience by displaying row details when a row is clicked, rather than clicking on a button as described in the documentation. However, the documentation lacks specific instructions on how to implement this feature. ...

Seeking clarification on the distinction between using an input of type button versus an input of type submit when triggering a jQuery form submission

This particular code is designed to execute the following actions upon being clicked: Submit the form Disable the button in order to prevent double clicks Add a spinner to the button to indicate to the user that something is happening If the form is inva ...

Trouble with Bootstrap card dimensions: Height and width not functioning correctly

I specified a height and width for all card images, but the heights are inconsistent with one being too large and another too small. I want each card to have the same height and width. How can I achieve this? Here is what I tried. .card { height: 50%; ...

aiming for divs that have the css property "left=0"

While working with masonry.js, I find it challenging to add a class to the elements positioned on the far left of the viewport as they are not placed in a specific order by the plugin. Using the nth selector has been difficult to target them effectively. ...

Retrieve the most recent version based on the provided ID and date within the array

I am working with an array of JavaScript objects that have specific properties: _id, isVersionFrom, createdAt. The _id and isVersionFrom properties store MongoDB _ids (with isVersionFrom being false for the original object), while createdAt stores a timest ...

Loading local JSON data using Select2 with multiple keys can greatly enhance the functionality

Comparing the select2 examples, it is evident that the "loading remote data" example contains more information in the response json compared to the "loading array data" example. I am interested in knowing if it is feasible to load a local json file with a ...

Unlocking the Power of Strapi v4: Leveraging Context within a Service

By creating a custom controller in Strapi, convenient access to a Context object is granted. This allows for retrieving the current user and utilizing the user's data as needed: module.exports = createCoreController("api::event.event", ({ st ...

JS - reloading the location after a function has been carried out with a short delay

Currently, I am using a JS / AJAX script to update information in my table. After the script finishes running, I want to reload the page. Unfortunately, when using my current code, the page reloads instantly. Is there a way to add a delay of 3 seconds befo ...