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

Do function pointers require an asterisk to be valid?

Within the code snippet I am utilizing, there is the following line: typedef void ( udp_data_notify )(OS_FIFO * pfifo, WORD port); At first glance, it appears to be a function pointer declaration for udp_data_notify. However, the absence of an asterisk ...

A guide on extracting a URL from source tags using Cheerio/jQuery

I have been struggling to retrieve the first image with data-srcset attribute ("https://sample.img_1") using Cheerio. None of my previous attempts have been successful. My most recent attempt looks like this: $(".sample_picture [media='(max-width: 64 ...

Adjust the margin of FormHelperText within a FormControl specifically for a Select component in Material-UI

I'm currently facing a challenge where I need to add marginLeft of 8px to FormHelperText. However, I have not been successful in doing so within the MuiInput formControl rule or in MuiSelect. Here is the React code snippet: <FormControl error clas ...

Error in Angular Universal: KeyboardEvent is not defined

I have inserted the word "domino" into the server.ts file and updated the webpack.server.config.js as follows: module: { rules: [ { test: /\.(ts|js)$/, loader: 'regexp-replace-loader', options: { match: { pattern: '&bs ...

Anchor tags created using JQuery will remain on the same page without redirecting

Presented below is the code I have utilized to construct the anchor tag along with its content. $('div#right-slide').html("<a href=\"http://www.XXXXXXXXXXXX.info/limited-specials/\" ><h1 id=\"specials\">Click Here ...

Using database entries to generate dynamic routes in express.js without the need for a server restart

I have created a custom Express instance for my KeystoneJS v5 app that serves data stored in a Postgres database with the following model: CREATE TABLE "Link" ( id integer DEFAULT PRIMARY KEY, customer text, slug text ); I've set up dyna ...

Issue with background/hero video not adjusting its size

I've been experimenting with creating a page that features a video as the background, but no matter what I try, the video never seems to resize properly. The image below shows how it looks: image in question body { margin: 0; } .hero-se ...

Firefox Cookie Expiry Date Automatically Set to One Week in Default Settings

I recently encountered an issue while trying to create a cookie that would persist for a year. Interestingly, the code I used worked perfectly on Chrome, as I could verify by checking the "Storage" in the dev tools. However, when I tried the same code on F ...

Ensure chip component (div) dynamically resizes its width to accommodate varying lengths of child text elements

I have a main container with two child elements (a text span and an image svg) created using the Material UI component library. My objective is to dynamically adjust the width of the chip based on the length of the text content inside it, while ensuring a ...

Retrieve all documents from a Firebase User's collection

Recently, I created a Firebase cloud function where my goal is to access every user's internal collection named 'numbers' and examine each document within that collection for some comparisons. Do you have any insights on how I can achieve t ...

Foundation: the importance of source order (without using flex grid)

I have a 3-column grid, with content and a sidebar. On small and medium devices each takes up 12 columns. Take a look at the example here: cdpn.io/anon/pen/bqENqG. I am looking to have the sidebar appear after the articles on small and medium devices like ...

Removing a Request with specified parameters in MongoDB using NodeJS

Working with Angular 4 and MongoDB, I encountered an issue while attempting to send a delete request. My goal was to delete multiple items based on their IDs using the following setup: deleteData(id) { return this.http.delete(this.api, id) } In order ...

Show the price of the item with a click of a button

There are three buttons where I can select values and input them into the button. Once all three values are selected in the buttons, I would like the product of these values to be displayed in a fourth button. Here is my HTML code: <label>S *</l ...

Types of Content in Solr Responses

My journey with Solr has been enlightening, but I've hit a bump in the road. When querying Solr using: curl "http://localhost:8983/solr/myCollection/select?q=*:*&wt=json&rows=0" I receive a webpage displaying the JSON response. However, the ...

"Utilize Python's Selenium library to automate clicking the 'Get Data

Having trouble with clicking the GetData button to retrieve the output. Looking for assistance on how to achieve this. Update your code below:- from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.o ...

I have expanded the CSSStyleDeclaration prototype, how do I access the 'parent' property?

I have developed some custom methods for CSSStyleDeclaration and implement them like this: A_OBJECT.style.method() ; The code structure is quite simple: CSSStyleDeclaration.prototype.method = function () { x = this.left; ..... etc } Here's my que ...

Replicate a form input element as a jQuery object and showcase it within a wrapped div or list item

Whenever I attempt to wrap or add more HTML content to the jQuery selectors, I keep encountering [object Object] or [object HTMLInputElement]. My objective is to: Copy an input field Clear out any data (while preserving id, class, type etc...) - Firefox ...

Retrieve the highest location of a dialog in JQuery

I've been experimenting with the position option on JQuery dialog plugin. My goal is to extract only the "top" and "left" values from this position object, but I'm struggling to do so. Currently, my dialog is set up like this: <a href="#" onc ...

Ways to specify distinct css styles according to varying number of elements

I need the Button element to always take up 100% of the container, no matter how many elements are inside. Check out my Fiddle link here: Js Fiddle Link <div class="inputFieldBoolean buttonSeries" data-type="Boolean"><button class="true" data-va ...

CSS menu - Shifting bar: What's the issue?

I'm struggling to add a moving bar to my website's navigation and need some help. I tried following a tutorial at the following link: (http://css-tricks.com/jquery-magicline-navigation/) Here is what I ended up with: If anyone could take a look ...