jQuery is not active on responsive designs

I have implemented a script in my JavaScript code that changes the color of the navigation bar when scrolling. The navigation bar transitions to a white color as you scroll down. However, I am facing an issue with responsiveness and would like to deactivate this script for screen sizes between 768px and 991px.

$(document).ready(function(){       
var scroll_start = 0;
var startchange = $('.change-col-nav');
var offset = startchange.offset();
    if (startchange.length){
        $(document).scroll(function() { 
        scroll_start = $(this).scrollTop();
        if(scroll_start > offset.top)   {
            $(".navbar-inverse").css({
                        "background-color": "#fff", 
                        "border-bottom": "1px solid #febe10",
                        "transition": "all 0.4s cubic-bezier(0.000, 0.000, 0.580, 1.000)"
                    });
                }
               else
               {
                  $('.navbar-inverse').css({
                      'background-color': 'transparent',
                      "border-bottom": "0",
                    });
               }
           });
            }
        });

Could someone guide me on how to disable this script specifically for screen sizes between 768px and 991px?

Answer №1

To properly contain it within an if statement, do the following:

$(document).ready(function(){  

    // ... additional code goes here

    $(document).scroll(function() { 

        if ($(window).width() > 768 && $(window).width() < 991) {
            return;
        }

        // .... continue with the remaining code
    })
})

Answer №2

function adjustNavbarStyle() {
  var scroll_start = 0;
  var start_change = $('.change-col-nav');
  var offset = start_change.offset();
  
  if (start_change.length) {
    $(document).scroll(function() {
      scroll_start = $(this).scrollTop();
      
      if(scroll_start > offset.top) {
        $(".navbar-inverse").css({
          "background-color": "#fff",
          "border-bottom": "1px solid #febe10",
          "transition": "all 0.4s cubic-bezier(0.000, 0.000, 0.580, 1.000)"
        });
      }
      else {
        $('.navbar-inverse').css({
          'background-color': 'transparent',
          "border-bottom": "0"
        });
      }
    });
  }
}

$(document).ready(function() {
  var window_width = $(window).width();
  
  if(window_width < 768 || window_width > 991) {
    adjustNavbarStyle();
  }
});

$(window).resize(function() {
  var window_width = $(window).width();
  
  if(window_width < 768 || window_width > 991) {
    adjustNavbarStyle();
  }
});

Answer №3

An effective solution is to utilize window.innerWidth

$(document).ready(function(){       
var scroll_start = 0;
var startchange = $('.change-col-nav');
var offset = startchange.offset();
    if (startchange.length){
        $(document).scroll(function() { 


            // CHECK IF WITHIN SPECIFIED WIDTH
            if(window.innerWidth >= 768 && window.innerWidth <= 991) {
                return;
            }


        scroll_start = $(this).scrollTop();
        if(scroll_start > offset.top)   {
            $(".navbar-inverse").css({
                        "background-color": "#fff", 
                        "border-bottom": "1px solid #febe10",
                        "transition": "all 0.4s cubic-bezier(0.000, 0.000, 0.580, 1.000)"


                    });
                }

               else

               {
                  $('.navbar-inverse').css({
                      'background-color': 'transparent',
                      "border-bottom": "0",
                    });
               }

           });
            }
        });

Answer №4

I prefer using media queries over JavaScript to handle responsive design.

$(window).on("scroll", function () {
    var offset=100;
    $(document.body).toggleClass("scrolled-active", $(window).scrollTop() > offset);
    
});
body {
  padding-top: 50px;
}
.scrolled {
  
}
p {
  margin-bottom: 50px;  
}
#foo {
  position: fixed;
  top: 0;
  left:0;
  background-color: #CCC; 
  width: 100%;
}

media (min-width:768px) and (max-width:992px) {
  .scrolled-active #foo {
    background-color: #FCC;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="foo">Test</div>
<p>I like cheese</p>
<p>I like cheese</p>
<p>I like cheese</p>
<p>I like cheese</p>
<p>I like cheese</p>
<p>I like cheese</p>
<p>I like cheese</p>
<p>I like cheese</p>
<p>I like cheese</p>
<p>I like cheese</p>

If you decide to use JavaScript, I recommend utilizing window resize event to determine browser size instead of checking on every scroll event.

var isWidthValid;
$(window).on("resize load", function() {
    var width = $(window).width();
    isValidWidth = width>=768 && width<=991;
    $(window).trigger("scroll");
}).on("scroll", function(){
    if(!isValidWidth) return;
    /* Your code */
});

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

The `XMLHttpRequest.prototype.open` function does not capture every single HTTP request visible in the chrome-dev-tools

While utilizing a third-party embedded code that initiates HTTP requests with a request header origin different from my own, I encountered an issue. Despite attempting to intercept these HTTP requests using XMLHttpRequest, they do not get intercepted. This ...

Getting data from an API using a Bearer Token with React Hooks

I am currently developing a React application that is responsible for fetching data from an API. This API requires Bearer Token Authorization. To handle this, I have implemented useState() hooks for both the token and the requested object. Additionally, th ...

Utilizing CSS transitions to smoothly adjust the width of an element until it completely fills the container div in ReactJS

import React from 'react'; import PropTypes from 'prop-types'; import SearchIcon from '@material-ui/icons/Search'; import InputBase from '@material-ui/core/InputBase'; import { AccountCircle } from '@material-ui ...

Unable to generate a menu with bootstrap

Hey there, I've been experimenting with creating a responsive menu using Bootstrap, but I'm struggling with the implementation. My vision is to have a logo on the left side and a menu on the right side. Below is the concept for my menu design. ...

Tips for preventing an element from scrolling horizontally along with the page body

This is the structure of my HTML: <div class='header-wrapper'> <div class='title'>Title</div> </div> <div class='some-wide-content'> </div> Let's imagine a scenario where the br ...

Guide to incorporating Jquery-Comment into Angular versions 2 and beyond

I've incorporated the Jquery-Comment plugin into my Angular 2 project by adding the necessary script and css files to my Index.html page. However, when initializing the Comment TextBox id within a script tag, I encountered an error in the console. ...

When viewing HTML "Div" on smaller screens, the full height may not be displayed properly

My setup includes two monitors: one is 24" and the other is my laptop's 12.5" screen. I have a red box (div) in my web application that displays full height on the larger monitor, but only partially on the smaller one. I'm puzzled as to why it s ...

An error occurred while attempting to save a new entry using the New Entry Form in DataTable, stating that the variable "

I have encountered an issue with a table that includes a bootstrap modal containing a form. After filling out the form and saving the data or closing the modal, I want to refresh the table data. However, I am receiving the following error: TypeError: c i ...

What is the best way to search for a specific item in Express.js?

I recently got the Leaderboard API issue fixed, but now I'm encountering a new problem with express Querying. Specifically, I'm attempting to search for a specific Discord ID using quick.db as my database. I've included an excerpt of my expr ...

Encountering difficulty when trying to initiate a new project using the Nest CLI

Currently, I am using a tutorial from here to assist me in creating a Nest project. To start off, I have successfully installed the Nest CLI by executing this command: npm i -g @nestjs/cli https://i.stack.imgur.com/3aVd1.png To confirm the installation, ...

What could be causing a template value in my AngularJS/Ionic Framework code to not be replaced properly?

Recently, I've been exploring the world of Ionic Framework with Angular by my side. However, I've hit a bit of a roadblock. My goal is to set up tabs at the bottom of my application using a model definition. Here's what I've tried so ...

Exploring the Transition from React.js with Material UI to Next.js for Server-Side Rendering: A Comparison of Tailwind CSS, Material UI, and Chakra UI

Currently, I am in the process of moving my React.js application with Material UI components to Next.js for server-side rendering (SSR) while considering some UI changes. In my research, I have come across three UI frameworks: Material UI, Chakra UI, and T ...

Expanding Gridview Width within a Container in ASP.Net: A Step-by-Step Guide

https://i.stack.imgur.com/ZaJE7.jpg After viewing the image above, I am facing a challenge with stretching and fixing a gridview to contain the entire div where it is placed. The issue arises when the gridview adjusts automatically based on the content&ap ...

error in three.js occurs when attempting to load .obj files

I've been encountering issues with OBJ files that I've downloaded from the internet. All of these files render like this: View Obj File Pic I'm using the standard OBJLoader for rendering. var loader = new THREE.OBJLoader(); loader.load( ...

convert text on website using selected option from menu

A dropdown menu allows the user to choose from 3 language options: English, Spanish, and German. The intended functionality is that when a language is selected, the entire content of the site should switch to that language. Unfortunately, this feature is ...

Pass an array from JavaScript to PHP

I am attempting to send an array to the server using jQuery. Here is my code snippet for sending the array: jQuery(document).ready(function($){ $.ajax({ type: "POST", url: "file.php", datatype : "json", data : JSON.str ...

What is the best way to achieve a consistent style for two tables?

I would like to achieve uniform styling for each row. The first row, which contains 'het regent vandaag', has the following CSS rule: .attachments-table td { margin: 0 5px; padding: 10px 8px; line-height: 1.4; white-space: pre-wr ...

Implementing jQuery to add content within Redactor

I am working with a textarea field that has an ID of "description", however, it is being rendered by a WYSIWYG editor called Redactor. I am trying to use jQuery to input something in the textarea. So far, I have attempted: $('#description') ...

Using AJAX within the $.when function to extract the first character from the returned string

Currently, I am utilizing an AJAX call by using $.when to wait for the completion of that specific ajax request and then continue with processing the subsequent ajax request inside. The code block below demonstrates where the $.when method is being invoke ...

In which location can one find the compiled TypeScript files within an Angular 2 project?

As a newcomer to learning Angular 2, I've come across tutorials that mention all compiled files should go into the dist folder. These compiled files refer to typescript files transpiled into JavaScript. However, upon creating my project using Angular ...