when the window is scrolled a certain amount, use jQuery to scroll back in the opposite direction

Using jQuery for Background Image Position:

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

    if (scroll >= 50) {
        $(".class").addClass("bgposi");
        // $(".top").addClass("fixd");
        // $(".logo").addClass("maxwidth");
       if (scroll >= 50) {
        $(".class").addClass("bgposi");
        // $(".top").addClass("fixd");
        // $(".logo").addClass("maxwidth");
        }
    }

});

I'm utilizing jQuery to dynamically change the background image position by adding the class .bgposi when users scroll past 50px on the page. The initial if statement is functioning as expected, but I'm encountering difficulty with implementing a second if statement to reverse this effect when users scroll back up. Any suggestions or tips would be greatly appreciated!

Answer №1

Revise the following in your second if statement:

  • Avoid nesting it.
  • Switch the comparison operator >= to <=.
  • Utilize removeClass.

Modify:

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

    if (scroll >= 50) {
        $(".class").addClass("bgposi");
        // $(".top").addClass("fixd");
        // $(".logo").addClass("maxwidth");
       if (scroll >= 50) {
        $(".class").addClass("bgposi");
        // $(".top").addClass("fixd");
        // $(".logo").addClass("maxwidth");
        }
    }

});

To:

$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  if (scroll >= 50) {
    $(".class").addClass("bgposi");
    // $(".top").addClass("fixd");
    // $(".logo").addClass("maxwidth");
  } else if (scroll <= 50) {
    $(".class").removeClass("bgposi");
    // $(".top").removeClass("fixd");
    // $(".logo").removeClass("maxwidth");
  }
});

You can optimize by caching commonly used selectors (performing the lookup once), such as:

$(window).scroll(function() {
  var scroll = $(this).scrollTop();
  var $class = $(".class"),
    $top = $(".top"),
    $logo = $(".logo");

  if (scroll >= 50) {
    $class.addClass("bgposi");
    $top.addClass("fixd");
    $logo.addClass("maxwidth");
  } else if (scroll <= 50) {
    $class.removeClass("bgposi");
    $top.removeClass("fixd");
    $logo.removeClass("maxwidth");
  }
});

$(window).scroll(function() {
  var scroll = $(this).scrollTop();
  var $class = $(".class");

  if (scroll >= 50) {
    $class.addClass("bgposi");
  } else if (scroll <= 50) {
    $class.removeClass("bgposi");
  }
});
body {
  height: 200vh;
  background-color: peachpuff;
}
.class {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 20%;
  background-color: dodgerblue;
}
.class.bgposi {
  background-color: purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="class"></div>

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

Troubleshooting issue: `will_paginate` and jQuery integration not functioning properly due to non-responsive

I'm currently implementing a pagination feature in my application using jQuery, similar to how it's done on platforms like Facebook and Twitter. However, when I try to load "next" results, the entire HTML page is being loaded instead. It seems li ...

Adding borders to div elements for mobile display

Almost done with my website homepage, but I'm noticing some pesky borders/outlines on mobile devices. This issue doesn't seem to pop up on computers, so you'll need an iPhone, tablet, or smartphone to see what I'm talking about. Check o ...

Problem with Labels Overlapping and Blocking Text Fields

My issue is that when I interact with the text field, the label "Type your New Task here" moves up and gets covered by what looks like a white overlay. How can I fix this so that the label stays visible at all times? Prior to engagement: https://i.stack.i ...

Interactive navigation with jQuery

I am currently utilizing a jQuery menu script that enhances the navigation structure on my website: (function($) { $.fn.blowfish = function() { // concealing the original ul dom tree $(this).hide(); // constructing a container from top-l ...

Issue with displaying Semantic UI Popup

Attempting to utilize semantic as the front end and implementing popups, however, the pop up is not appearing HTML <div class="ui teal button" data-title="Using click events" data-content="Clicked popups will close if you click away, but not if you cl ...

Achieving dynamic text alignment within a Grid tile container using HTML and Angular

Here is the main section of my parent component. <div class="o-tile-container "> <div *ngFor="let country of Countrys"> <app-country [na ...

Retrieve key-value pairs from a database and store them as variables in PHP before transferring them into an array in JavaScript

My challenge lies in loading Chinese characters as keys and their English translations as values from a database into a PHP array, so that I can use them on the client side in JavaScript. The process involves fetching key:value pairs from PHP into a JavaSc ...

Utilizing AngularJS to dynamically inject HTML content into $scope

In my possession are the following files: index.html //includes instructions for passing arguments to the btnClick function in app.js <div ng-bind-html="currentDisplay"></div> app.js app.factory('oneFac', function ($http){ var htm ...

Choosing a dynamic dropdown option using jQuery and AJAX

I am facing an issue with a select box that is dynamically populated and should display information about a single option. The problem I am encountering is that the browser does not trigger a ':selected' event when I click on any of the options. ...

The toggling feature seems to be malfunctioning as the div section fails to display

I'm facing an issue with my Django project while working on a template. I want to toggle the visibility of a div element between hiding and showing, but the function I used isn't working for some reason. I borrowed the function from a different t ...

Design and execution of webpage structure

My website features a single-page layout with fixed navigation that allows users to easily navigate up and down the page using #. However, when the page loads I want it to display the second section of content instead of the top section. Is there a way to ...

AngularJS fails to prioritize the following element

Here is my HTML code: <div ng-app="app"> <form> <div class="form-group"> <label >Username</label> <input focus type="text" class="form-control" id="loginUserName" ng-model="userForm.crn" required/> ...

What's the Reason Behind the Ineffectiveness of Footer Background Color in HTML CSS3?

Having some trouble setting the background color for my footer to something other than white. I've been able to successfully change the background of other layout elements, but the footer is giving me issues. Check out the code below: <footer> ...

Encountering an issue with html2canvas: receiving an error message stating "object

To print the div using Javascript, I encountered an issue with the generated barcode not appearing in the printed page. This led me to use the html2canvas approach to 'render' the div before printing it out. Here is the code snippet: HTML: < ...

Cutting-edge framework for Single Page Applications

Can you assist me in identifying the most recent framework suitable for creating single page applications? Your help is greatly appreciated. Thank you. ...

AngularJS special feature: enhance controllers and views by adding notification capabilities

What is the most efficient method for integrating common notification features into necessary controllers in AngularJS? The objective is to establish local notifications that can be effortlessly included or removed from any controller. Key factors includ ...

The integration between PHP and Jquery seems to be malfunctioning

As a beginner in jQuery and ajax, I am encountering numerous issues. There is a function that isn't working as expected during testing. Can someone please help me understand what the problem might be? Thank you. HTML Page PHP Page ...

The variable "$" cannot be found within the current context - encountering TypeScript and jQuery within a module

Whenever I attempt to utilize jQuery within a class or module, I encounter an error: /// <reference path="../jquery.d.ts" /> element: jQuery; // all is good elementou: $; // all is fine class buggers{ private element: jQuery; // The nam ...

The TypeScript error states that the argument type 'string | undefined' cannot be assigned to the parameter type 'string'

Receiving TS error that says "Object is undefined" I am attempting to retrieve the "userid" from my headers. However, I keep encountering the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'str ...

Algorithm for detecting collisions in Javascript

I am looking to implement a collision detection function in JavaScript for canvas. Specifically, I have coin and piggy bank objects and want to create a function that triggers the disappearance of a coin object when it comes into contact with a piggy bank. ...