Paulo Paulo - 5 months ago 30
jQuery Question

How can I control when a class is added to an element on scroll in jQuery

I am using the following javascript in order to add and remove a class when scrolling the page:

(function($) {
$.fn.timeline = function() {
var selectors = {
id: $(this),
item: $(this).find(".timeline-item"),
activeClass: "timeline-item--active",
img: ".timeline__img"

var itemLength = selectors.item.length;

$(window).scroll(function() {
var max, min;
var pos = $(this).scrollTop();
selectors.item.each(function(i) {
min = $(this).offset().top;
max = ($(this).height() + $(this).offset().top);
if (i == itemLength - 2 && pos > min + $(this).height() / 2) {
} else if (pos <= max - 40 && pos >= min) {




I have put together the following jsfiddle: what I am trying to achieve here is to add a class as soon as each element on this timeline comes into view. The elements are blurred and when scrolling when they come into view the blur should disappear almost instantly but on the jsfiddle above the elements remain blurred for quite a long time when already in view. How could I make it so that they become visible, without blur almost as instantly as they come into the viewport when scrolling?

Answer Source

The problem lies within the positioning and the "else if" statement. The active class should be removed for each item individualy an not all the items at once. And I changed the positioning a little bit:

    } else if (pos <= max && pos >= min - window.innerHeight + $(this).height()/2) {
    } else{
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download