Apply a specific class only when the user scrolls within the range of 200px to 300px

Is it possible to dynamically add a class to a div element based on the user's scrolling behavior? For example, I would like to add a class when the user scrolls 200px down the page, and then remove it when they scroll 300px down. Similarly, I want to add the class again when the user scrolls back up to 300px from the top, and remove it at 200px.

Despite trying multiple variations, I seem to be struggling with the approach. You can view my current progress on JSFiddle here: http://jsfiddle.net/v8my3sr1/

$(window).on('scroll',function() { 
  var scroll = $(window).scrollTop();
  if (scroll >= 200) {
    $(".trigger").addClass("wow");
  } else {
    $(".trigger").removeClass("wow");
  }
});

Answer №1

Your condition is not accurate. Make sure that the value of scroll falls between 200 and 300

$(window).on('scroll',function() { 
  var scroll = $(window).scrollTop();
  if (300 >= scroll && scroll >= 200) {
    $(".trigger").addClass("wow");
  } else {
    $(".trigger").removeClass("wow");
  }
});

$(window).on('scroll',function() { 
  var scroll = $(window).scrollTop();
  if (300 >= scroll && scroll >= 200) {
    $(".trigger").addClass("wow");
  } else {
    $(".trigger").removeClass("wow");
  }
});
.container {
  height: 2000px;
}
.trigger {
  margin-top: 300px;
  height: 400px;
}
.wow {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="trigger">
    <h1>Trigger container</h1>
  </div>
</div>

You can also simplify the code by using .toggleClass()

$(window).on('scroll',function() { 
  var scroll = $(window).scrollTop();
  $(".trigger").toggleClass("wow", 300 >= scroll && scroll >= 200);
});

Answer №2

Here is a possible solution:

$(window).scroll(function(){

  var position = $(window).scrollTop();

   $(".element").each(function(){
    if($(this).offset().top + $(this).height() > position){
      box.removeClass('animate');
      $(this).addClass('animate');
      return false;
    }
  })
})

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

Selection menu for hierarchical reporting information

Looking for assistance on how to display hierarchical data from two tables - reporting and employee_details. The reporting table includes supervisor_id and subordinate_id fields which correspond to emp_id in the employee_details table. This hierarchy spa ...

Tips for successfully uploading FormData files using Axios: Resolving the TypeError of "file.mv is not a function"

When transmitting a file from one server to another using Axios, I am facing an interesting scenario where one server is an app backend and the other is a blockchain server. The destination for the file transmission is set up as follows: router.post("/a ...

Obtain the IP address of a Node application running within a Docker container

I currently have a node express application set up in a Docker container, and I am attempting to record the IP address of each incoming request within the app. However, due to running behind a firewall, my current method "req.headers['x-forwarded-for& ...

"execute loop in a strange and peculiar manner using JavaScript

Implement a loop to place markers on the map: for (i = 0; i <= 6; i++) { _coord = prj_markers[i]; alert(i); instance.set_marker(instance, provider, i, _coord, divBlock); } This code displays "0" in an alert once and executes instance.set_m ...

Google Web Fonts: Exploring the World of Font Weight Variations

It's quite puzzling as to why the weight of my Google web font in the navigation menu keeps changing on different pages even though I have specifically set it to 700. The CSS for the menu is exactly the same across all pages. Can anyone shed some ligh ...

Is it possible to conceal an error message while another error message is being shown?

<form name="form"> <input type="password" placeholder="Password" ng-model="password" name="password" minlength="6" maxlength="15" ng-pattern="/^\S*$/" required> <span ng-show="form.password.$dirty && form.password.$in ...

Identify Safari browser and redirect visitors

Here is the script I am using to detect and redirect a page specifically when Safari is used: if(/safari/.test(navigator.userAgent.toLowerCase())) { window.location.href = "elsewhere.html" } Currently, it redirects in both Safari and Chrome. How can ...

Extracting Vertices, Edges, Faces, and Triangles from GLB Model Using ThreeJS GLTFLoader

I am looking to incorporate basic information about the model into my model viewer. Specifically, I need to obtain the vertex, edge, face, and triangle count of the object, or at the very least, the vertex count. My attempted approach involves using the f ...

Display subpages of WordPress site in a dropdown menu on the navigation bar

Currently in the process of converting an HTML website to Wordpress, I am encountering a challenge. The issue lies in my attempt to add a drop-down feature to the navigation list using the wp_list_pages tag. As it stands, when hovering over the "products" ...

Issues with displaying markers on Google Maps API using JSON and AJAX

I have successfully coded the section where I retrieve JSON markers and loop through them. However, despite this, the markers do not seem to be appearing on the map. Could someone please assist me in identifying the mistake? $.ajax({ url ...

The Ajax Get Request functions properly when called in a browser, but returns a 302 error when executed within an iframe. What might be causing this discrepancy?

I am currently developing a web application that initiates multiple ajax requests upon startup. The app functions perfectly when executed independently in the browser. However, when I run it within an iframe, one of the ajax requests unexpectedly returns ...

Modifying the Inactive Tab Color in Material UI

For my application, I have a specific requirement where the active tab needs to be styled in red and the inactive tab in blue. Here is how the styling is set up: newStyle: { backgroundColor: 'red', '&$selected': { b ...

casperjs timeout issue with an endless loop

Currently, I am utilizing casperjs to retrieve the content of a website that updates its values using websockets. Rather than attaching an event listener to each value, my goal is to scrape the entire website every 10 seconds. Here is the code snippet I a ...

Is it possible for the HTML (source code of a web page) to alter once the page is saved onto a local computer?

Upon opening a webpage at http://www.designova.net/rise/index-01.html, I decided to inspect its source code. Afterwards, I saved the page to my computer and opened it in an editor (sublime text 2). To my surprise, I noticed that the HTML content in the two ...

Sliding out the sidebar menu with Jquery

Hey there! I'm currently working on implementing a swipe feature for the side menu bar. I have already added a click method in my code, but now I also need to incorporate a swipe technique. When the side bar is opened, I want to remove the inside im ...

Altering data in a concealed dynamic HTML form

I have a hidden form on my webpage that gets populated dynamically when a button is clicked. I want to be able to change the values within this form dynamically. Initially, the form looks like this: <form id="zakeke-addtocart" method="pos ...

The website was designed to only allow scrolling on desktop devices, not on mobile devices

I noticed that the website is not scrolling properly on mobile devices, specifically when viewed on a Samsung Galaxy S4 Mini. Does anyone have suggestions on how to resolve this issue? ...

Why is my Javascript XMLHttpRequest onreadystatechanged event not triggering?

I am facing an issue with my html file and a .txt file stored in the same directory on a webserver. In the html file, I have the following code: <html> <head> <script> window.onload = function() { receiveMessage(); } function recei ...

In Production environment, v-model triggers a ReferenceError

My Vue View includes the following code: <script setup> import Overwrite from "../components/Overwrite.vue"; </script> <template> <div> ... <textarea v-model="text" cols="99" rows=&qu ...

What is the best way to restrict the creation of objects in a JavaScript list?

Experiencing a fun challenge with HTML coding! Take a look at my ordered list in HTML: <ol id="myList"> <li>Tea</li> <li>Milk</li> <li>Water</li> </ol> <button onclick="myFunction()">Try it</ ...