Ways to turn off JavaScript when reaching a certain breakpoint, similar to a media query

I am facing an issue with my <header> and <nav> blocks which are impacted by JavaScript. Is there a way to create a JavaScript solution similar to a media query that would deactivate this JavaScript code if the window width is less than or equal to 1200px?

This is my current JavaScript, running continuously (placed just before </html>):

<script>
    $(window).scroll(function() {
        if ($(this).scrollTop()>119)
         {
            $('header').fadeOut();
            $('nav').css({position: 'fixed', top: '0px'});
         }
        else
         {
          $('header').fadeIn();
          $('nav').css({position: 'absolute', top: 'auto'});
         }
    });
</script>


I have attempted enclosing the code within

if (document.documentElement.clientWidth <= 1200) {
    // scripts
}

and

if (screen.width <= 1200) {
    // scripts
}

but without success.

Answer №1

The best way to handle this situation is by wrapping the code. Given that jQuery is already in use, you can utilize the following:

if($(window).width() > 1200) {
  // Add the remaining code here
}

It's important to note that I've opted for > instead of <= as you specified that it should be executed when over 1200px and disregarded when below or equal to 1200px.

Answer №2

Here's a helpful code snippet for your project:

<script>
    var screenWidth = $(window).width();

    if(screenWidth >= 1200)
    {
        $(window).scroll(function() {
            if ($(this).scrollTop()>119)
            {
                $('header').fadeOut();
                $('nav').css({position: 'fixed', top: '0px'});
            }
            else
            {
                $('header').fadeIn();
                $('nav').css({position: 'absolute', top: 'auto'});
            }
        });
    }
</script>

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

What strategies can I employ to prevent my div tags from shifting positions relative to each other?

I spent time formatting a div tag for my main content and then placed that div inside another wrapper div. However, when I tried to add my logo to the site, everything shifted. It appeared as though the div containing the logo had pushed the wrapper down. ...

Retrieve the scrollTop, scrollLeft properties, and other scroll-related data from an element using Selenium

When testing a Python/Django element that is scrolled using scrollTop, I am trying to retrieve the value of scrollTop. In JavaScript, I can access this value with: element.scrollTop I attempted to do this in Python using: element.get_attribute('sc ...

Tips for adding React components to an array with the help of backticks

Currently, I am attempting to populate an array with icons by extracting the name from data and concatenating "<" and "/>" around it in order to convert it into an Mui Icon. Despite renaming the imported icons to match the names in the data, when I ...

Integrate a resizable sidebar on the webpage's right side that dynamically adjusts the layout

As I develop a Chrome Extension, my goal is to incorporate a sidebar into all webpages without overlapping the existing content. The sidebar should be placed beside the content, effectively reducing the width of the body of the webpage to the initial width ...

When using AJAX POST requests, HTML links may become unresponsive

Scenario: Currently, I am developing a small-scale web application. The AJAX functionality is successfully sending data to create.php which then executes the necessary MySQL query. Upon completion of the AJAX request, a success message is appended to the d ...

How to Align Navigation Bar Items to the Right in Bootstrap 4

I need some help with bootstrap. I've looked at various discussions on this topic and tried numerous solutions, but I still can't get it right. I want the logo to be on the left and the navigation links aligned to the right. Here's what I&ap ...

subscriptions to behavior subjects may not function properly across all components

When setting up my global service, I instantiate a BehaviorSubject variable dataWorkflowService: export class CallWorkflowService { url = 'http://localhost:3000/'; selectedNode : BehaviorSubject<Node> = new BehaviorSubject(new Node(&a ...

Changing the order of rows and columns with CSS3 and DOM manipulation

I have implemented the following CSS code to alternate the background color of li elements. However, I am facing an issue where I need the CSS styling to remain consistent even if the rows have the .hidden class applied to them (with .hidden class having d ...

Obtaining JSON data in a separate JavaScript file using PHP

I have an HTML file with the following content: // target.html <html xmlns="http://www.w3.org/1999/xhtml"> ... <script src="../../Common/js/jquery-ui-1.10.3.js"></script> <script src="../../Common/js/select.js" type="text/javascript"& ...

Is there a way to extract information from the HTML source code of an external website and display it in my application?

Seeking a method to search an external URL for content that matches "title" and then display the results on my HTML page using Javascript. Despite my efforts with Javascript, I have not come across any resources that address this issue. Could it be that I ...

Utilize underscore's groupBy function to categorize and organize server data

I am currently utilizing Angular.js in conjunction with Underscore.js This is how my controller is structured: var facultyControllers = angular.module('facultyControllers', []); facultyControllers.controller('FacultyListCtrl', [' ...

having trouble with my lambda function reading the basic json object

I recently joined Lambda and have been attempting to create a simple JSON object. However, I keep encountering an error that says "parsing error, unexpected token." Here is my code, which I have verified to be valid JSON: { "metadata": { ...

Choose an element at random

I am trying to figure out how to select all div elements with the same class of "dot" under a parent div in JavaScript. Here is an example structure: <div id="dots"> <div class="dot"> . </div> <div class="dot"> . </div> ...

Sauce Labs encountering issues when running JavaScript code

Currently, I am using Selenium WebdriverJs along with Mocha to conduct tests on Sauce Labs via Travis CI. After isolating the issue without any project dependencies, I am seeking help. The interesting observation is that defining an additional object with ...

Steps to resolve the Angular observable error

I am trying to remove the currently logged-in user using a filter method, but I encountered an error: Type 'Subscription' is missing the following properties from type 'Observable[]>': _isScalar, source, operator, lift, and 6 more ...

AngularJS default ngOptions for parent and child models

Is there a way to set default ngOptions through parent/child models? Here, the OP demonstrates using ngOptions with parent/child relationships. template <select ng-model="x.site" ng-options="s.site for s in data"></select> <select ng-mode ...

Locating the CSS pixel value without being affected by the browser's zoom settings

Check out this JS fiddle I created to illustrate my issue. As you zoom in and out of the browser page, the value of max-width that appears in the console keeps changing. However, in the CSS code it is always set to 500px. How can I retrieve the original CS ...

Has the new version of Bootstrap, Bootstrap 5, eliminated the spacing between rows

After switching to bootstrap 5, I couldn't help but notice the lack of spacing between rows. Is it necessary to use the spacing utility like mb-3 or mb-2 to add vertical spacing? I'm curious about the rationale behind this change. <script s ...

Python Flask login application failing to redirect to login page

Currently, I'm building a login application with Python Flask and MongoDB integration at the backend. While everything else seems to be running smoothly, there's an issue with redirecting to the login page upon login. # See below for my code @ap ...

Stunning CSS Image Showcase

When hovering over my image gallery, it works fine. However, I would like the first image in the gallery to automatically appear in the enlarged section instead of displaying as a blank box until hovered over. <!DOCTYPE html> <html lang="en"> ...