Put the code inside a function. I'm new to this

My goal is to encapsulate this code:

if($(window).width() > 980) {
   $(window).on("scroll", function() {
      if($(window).scrollTop() > 20) {
        //add black background
        $(".x-navbar").addClass("active");
        $(".x-navbar .desktop .x-nav li a").addClass("small-bar");
      } 
      else {
        //remove background
        $(".x-navbar").removeClass("active");
        $(".x-navbar .desktop .x-nav li a").removeClass("small-bar");
      }
   });
}

into a function, making it possible to deactivate it when the width is under 980px.

The desired outcome consists of the following steps:

Create a function like this:

navBar = function () {
     // entire code block goes here.
}

and later "disable" it on mobile devices with a width below 980px as follows:

if($(window).width() < 980) {
    // DO NOT execute the function named "navBar".
}

The issue I am facing is that upon resizing the window to a width less than 980px, the code does not respond to the resize event and continues to run regardless.

Answer №1

as previously stated in the comment

$(window).on("scroll resize", function() {
     if($(window).width() > 980) {
      if($(window).scrollTop() > 20) {
        //apply black background
        $(".x-navbar").addClass("active");
        $(".x-navbar .desktop .x-nav li  a").addClass("small-bar");
      } 
      else {
        //remove background
        $(".x-navbar").removeClass("active");
        $(".x-navbar .desktop .x-nav li a").removeClass("small-bar");
      }
     }else{
         // if window width < 980
         //remove background
        $(".x-navbar").removeClass("active");
        $(".x-navbar .desktop .x-nav li a").removeClass("small-bar");
     }
   });

Answer №2

If you want to take action when the window is resized, you can create a function and register it with the window.resize event.

$(window).resize(function () {
    //Add your code to check the width here
});

I hope this information proves useful to you.

Answer №3

The reason for this behavior is that a listener remains active until explicitly removed after instantiation. For removing a listener, refer to jQuery's off function. By utilizing off() and on(), you can control the event based on the window size.

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

Vue does not consistently update HTML when the reference value changes

I am trying to showcase the readyState of a WebSocket connection by utilizing a Ref<number> property within an object and displaying the Ref in a template. The value of the Ref is modified during WebSocket open and close events. However, I am encount ...

Implementing ESM in your next.config.js file is critical for optimizing

Currently, I am in the process of optimizing a Next.js project and came across the requirement to include type: 'module' in thepackage.json file. However, this led to an error being thrown: Error [ERR_REQUIRE_ESM]: Must use import to load ES Mo ...

Execute React program within VM Azure

After setting up my React application on Azure's virtual machine, I encountered an issue. When trying to access the public URL (DNS) of the VM, I received a "site can't be reached" message. This is the process I followed to launch my project on ...

Automating Web Form Completion with VBA and Selenium

I am experiencing an issue with filling out a form. I have attempted the following methods: driver.FindElementByXPath("//div[@id='s_dane_dokumentu-section?grid-1-grid?c_nr_lrn_komunikatu-control?xforms-input-1']").sendkeys "2112345 ...

What is the best method for extracting data from a node?

Issue: Upon sending a get request to node using the fetch API, an error is encountered. Refer to comment in code for details server.js const express = require('express'); const app = express(); const bodyParser = require('body-parser&apo ...

Generating React components dynamically can bring flexibility and efficiency to the

Looking for a solution to dynamically render different components based on the arguments passed with data. While using regular or React.createElement(Item) works fine, all other options seem to fail. http://jsfiddle.net/zeen/fmhhtk5o/1/ var React = windo ...

Utilizing Vue refs to set focus on a specific element target

Clicking on "span class="before-click" should hide it, and display input class="after-click" instead. The displayed input must be in focus! However, when trying to use $refs.afterClick to access the DOM and apply .focus(), an unexpected error stati ...

String includes another String not refreshing automatically

How come myCtrl.greeting doesn't automatically update when I change myCtrl.name? angular.module('MyApp', []) .controller('MainController', [function(){ var mCtrl = this; mCtrl.name = ''; mCt ...

Unable to function in simplistic html/php code, 'Require' fails to operate as intended

I am facing an issue while attempting to import a header.php file into my index.php file. For some reason, it is not working as expected. header.php: <!DOCTYPE html> <html> <head></head> <body> <header> & ...

Challenges I'm Facing with my Vue.js API Integration using axios

I am currently working on a bookstore application using Vue.js. The book data is stored in this API . However, I am encountering issues displaying the information on my HTML page with the provided function and I am struggling to identify the root cause: ...

Utilizing v-model for dynamic binding within a v-for iteration

I'm currently working on binding v-model dynamically to an object property within an array of objects. I am unsure about how to accomplish this task. The objective is to choose a user using the Select HTML tag and then display the list of that user&ap ...

Exploring the Features of Bottom and Right in jQuery

Here is a snippet of jQuery code that I included in a sample program: $('#left').click(function(){ $('.box').animate({ left: "-=40px", }, function(){/* End of Animation*/}); }); $('#right ...

Issues with Adding Variable Products to Cart in Woocommerce

Hey there! I've been working on my woocommerce website and have added a variety of products, some single and some variable. The singles are all good to go, but I've run into an issue with the variable ones. Every time I try to add a variable prod ...

Exploring ways to store session data in Next.js 13 with Supabase for seamless persistence

Encountering an issue with next-auth. Upon logging in, the result shows ({error: 'SessionRequired', status: 200, ok: true, url: null}), despite having an active session. The console also displays this error message, which I believe may be related ...

Why isn't $.post functioning properly in any instance?

I've been experiencing issues with my $.post calls throughout my code. Despite not sending requests to different domains, everything is localhosted. My Mac OS X 10.8 automatically defined my localhost alias as ramon.local, and I'm trying to make ...

Tips for dynamically updating the id value while iterating through a class

Here's the HTML snippet I am working with: <div class="info"> <div class="form-group"> <label class="control-label col-sm-2">Title</label> <div class="col-xs-10 col-sm-8"> <inpu ...

Using JQuery to toggle a fixed div at the bottom causes all other divs to shift upwards

I'm currently working on a chat feature using node JS, and while the functionality is perfect, I've run into an issue with the CSS aspect of it. The problem arises when we have multiple tabs and clicking on just one causes all the tabs to move u ...

Having difficulty accessing any of the links on the webpage

I'm currently utilizing the selenium webdriver to automate a specific webpage. However, I am encountering an issue where my selenium code is unable to identify a certain link, resulting in the following error message. Exception in thread "main" org ...

Invoke a function or variable based on a string parameter within a JavaScript/React function dynamically

I am currently exploring ways to dynamically call a function based on a string or reference a variable using a string. For example: import React, {useState} from 'react' const array = [ { text: 'count1', setFunctionName: &apo ...

Ways to obtain the coordinates that surround a particular x, y location

I am trying to figure out how to generate an array of coordinates around a specific x, y point. For instance: xxxxx xxoxx xxxxx In this case, "o" is located at coordinates 3, 2. Now I aim to produce: xxx xox xxx as the set of coordinates surrounding "o ...