When scrolling, apply a CSS class to a div element once it becomes visible on the

I'm in the process of developing a timeline feature for my website, and I am facing an issue where the addClass function is being applied to all sections, even those that are not currently visible on the screen during scrolling.

If you would like to test it out, feel free to visit my JSFiddle page.

Here is the jQuery code snippet I am using:

$(window).on('load scroll', function() {
    var $elem = $('#timeline .section');
    var $window = $(window);

    var docViewTop = $window.scrollTop();
    var docViewBottom = docViewTop + 20 + $window.height();
    var elemTop = $elem.offset().top;
    var elemBottom = elemTop + $elem.height();
    if (elemTop < docViewBottom) {
        $("#timeline .section").each(function(i) {
            $(this).delay(300 * i).addClass("active");
        });

    }
});

Answer №1

$(window).on('load scroll', function() {
    var $elements = $('#timeline .section');
    $elements.removeClass("active")
    $elements.each(function(idx){

    var $win = $(window);

    var docTop = $win.scrollTop();
    var docBottom = docTop + 20 + $win.height();
    var elemTop = $elements.eq(idx).offset().top;
    var elemBottom = elemTop + $elements.eq(idx).height();
    if (elemTop > docTop && elemBottom < docBottom){
$elements.eq(idx).addClass("active");
  }
  });
});
#timeline{
    max-width: 620px;
    margin: 40px auto 20px;
}

#timeline .section{
    position: relative;
}

#timeline .section .year{
    text-align: center;
    padding: 30px 0 10px 0;
    font-size: 18px;
    font-weight: 300;
    transition: 1s ease-in-out;
}

#timeline .section .year:after{
    content: "";
    opacity: 0;
    width: 9px;
    height: 9px;
    background: #006699;
    border-radius: 100%;
    position: absolute;
    margin: auto;
    bottom: 0;
    left: 0;
    right: 0;
    transition:1s ease-in-out;
}

#timeline .section .text-sec{
    position: absolute;
    font-weight: 100;
    line-height: 24px;
    right: 0;
    bottom: 40px;
    transition: 1s ease-in-out;
}

#timeline .section .sec-left{
    max-width: 275px;
    text-align: right;
    float: left;
    position: absolute;
    left: 0;
    top: 100px;
    padding: 0 0 0 0;
}

#timeline .section .line{
    background: #dedede;
    width: 1px;
    height:200px;
    position: relative;
    margin: 0 auto;
    transition: 1s ease-in-out;
}

#timeline .section .sec-right{
    max-width: 265px;
    float: right;
}

#timeline .section.active .year{
    color: #333333;
}

#timeline .section.active .year:after{
    opacity: 1;
}

#timeline .section.active .text-sec{
    color: #333333;
}

#timeline .section.active .sec-left{}

#timeline .section.active .line{
    background: #006699;
}

#timeline .section.active .sec-right{}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="timeline">
<div class="section">
    <div class="year">2014</div>
    <div class="text-sec sec-left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc a porta erat. Vestibulum commodo neque in iaculis lobortis. Nullam sit amet placerat sapien. </div>
    <div class="line"></div>
    <div class="text-sec sec-right">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc a porta erat. Vestibulum commodo neque in iaculis lobortis. Nullam sit amet placerat sapien. Pellentesque sollicitudin, nulla quis efficitur feugiat, augue tortor scelerisque urna, sit amet ultricies lectus</div>
</div>

<div class="section">
    <div class="year">2015</div>
    <div class="text-sec sec-left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc a porta erat. Vestibulum commodo neque in iaculis lobortis. Nullam sit amet placerat sapien. Pellentesque sollicitudin, nulla quis </div>
    <div class="line"></div>
    <div class="text-sec sec-right">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc a porta erat. Vestibulum commodo neque in iaculis lobortis.</div>
</div>

<div class="section">
    <div class="text-sec sec-left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc a porta erat. Vestibulum commodo neque in iaculis lobortis. Nullam sit amet placerat sapien. Pellentesque sollicitudin, nulla quis efficitur feugiat, augue torto</div>
    <div class="line"></div>
    <div class="text-sec sec-right">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc a porta erat. Vestibulum commodo neque in iaculis lobortis. Nullam sit amet placerat sapien. Pellentesque sollicitudin, nulla quis.</div>
</div>

<div class="section">
    <div class="year">2016</div>
    <div class="text-sec sec-left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc a porta erat. Vestibulum commodo neque in iaculis lobortis. Nullam sit amet placerat sapien. Pellentesque sollicitudin, nulla quis efficitur feugiat, augue</div>
    <div class="line"></div>
    <div class="text-sec sec-right">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc a porta erat. Vestibulum commodo neque in iaculis lobortis. Nullam sit amet placerat sapien. Pellentesque</div>
</div>

<div class="section">
    <div class="text-sec sec-left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc a porta erat. Vestibulum commodo neque in iaculis lobortis. Nullam sit amet placerat sapien. Pellentesque sollicitudin, nulla quis efficitur feugiat</div>
    <div class="line"></div>
    <div class="text-sec sec-right">Lorem ipsum dolor sit amet, consectetur adipiscing elit..</div>
    <div class="year">Now</div>
</div>
</div>

You need to iterate through each div with section class.

$(window).on('load scroll', function() {
var $elements = $('#timeline .section');
$elements.removeClass("active")
console.log($elements)
$elements.each(function(idx){

        var $win = $(window);

var docTop = $win.scrollTop();
var docBottom = docTop + 20 + $win.height();
var elemTop = $elements.eq(idx).offset().top;
var elemBottom = elemTop + $elements.eq(idx).height();
if (elemTop > docTop && elemBottom < docBottom){
        $elements.eq(idx).addClass("active");
  }
  });
});

jsfiddle

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

Create a duplicate of a React component that utilizes the forwardRef method

Imagine you have a foundational component that utilizes forwardRef in this manner: const BaseMessage = React.forwardRef((props, ref) => ( <div ref={ref}> {props.icon} <h2>{props.title}</h2> <p>{props.message ...

Stopping the interval in Vue before the component is destroyed

I am currently facing an issue with a countdown timer implemented on a component. The timer functions properly, however, I want it to stop counting down once the user navigates away from the page where the component is located. I have attempted to use cl ...

The browser does not support the display of Spanish special characters

I am working on a website and need to incorporate support for the Spanish language. I have prepared an XML file with both English and Spanish text. The XML file is being read based on the user's selection of language from a dropdown menu. Everything s ...

Automatically transferring CSS class attributes to a newly created class

The Issue I've encountered a problem while developing a small app for a website. The form in the app requires validation, but conflicts with existing jQuery scripts have been causing errors. These conflicting styles are essential to maintain the desi ...

Learn how to collapse a list by clicking outside of it on the document with the following code: $(document).on("click"

I want to create a collapsible/expandable menu for my website. I had a version where hovering over a category would expand the subcategory, but what I really need is for the subcategories to expand when I click on a category and remain expanded until I cli ...

Is there a specific measurement or scale for the dragging feature in jQuery UI draggables?

I'm interested in adjusting the position of my draggable element based on the distance moved by the mouse. For instance, if the scale is 1:2 and the cursor is moved 10px to the right, then the draggable should move 20px. I already have my draggable ...

Step-by-step guide to positioning an iframe with 'transform:scale' on the left side

Recently, I encountered an issue with an iframe in my project. Initially, without any 'transform:scale' css applied, it displayed on the top-left side of the div as expected. However, after adding -webkit-transform:scale(0.6,1); margin-left:0.0e ...

Tracking the progress of jQuery ajax requests

I'm currently using jQuery $.ajax to send files over the internet. Is there a way for me to receive updates on the progress of the file transfer, and then adjust the settings accordingly? Below is my current implementation of $.ajax : $.ajax({ ...

The initial value for the `useState` is not defined at the

Here's a simplified version of my requirement that demonstrates the issue. The ColorBox component receives a prop called "isVisible" from the ShowColorComponent component, which is used to initially set the state of the ColorBox.visible variable. impo ...

Use JavaScript to gather various data forms and convert them into JSON format before transmitting them to PHP through AJAX

My understanding of JSON might be a bit off because I haven't come across many resources that discuss posting form data via JSON/AJAX to PHP. I often see jQuery being used in examples, but I have yet to delve into it as I've been advised to firs ...

Retrieve an integer value from an HTML form

I need to extract an integer value from an HTML form using Python. Here is the code I tried: form = cgi.FieldStorage() if not form.has_key("id"): error_pop("There is no id in this form","The format of the request is not correct") id = ...

The Element Datepicker incorrectly displays "yesterday" as an active option instead of disabled when the timezone is set to +14

After adjusting my timezone to +14 using a chrome plugin, I noticed that the calendar app is displaying incorrect disabled dates. You can view the issue here. This is the formula I'm currently utilizing to disable dates: disabledDate(time) { re ...

When the component is initialized, the computed property is not being evaluated

My maps component initializes a Google map, adds markers based on props passed from the parent, and sets the correct bounds of the map. However, the markers are added through a computed property to make it reactive. Everything seems to be working fine, exc ...

What is the best way to populate dropdown menus using JavaScript?

I'm facing an issue with my ajax request where I am unable to populate the options of a select tag. This problem is occurring in multiple blocks where the select tag serves the purpose of choosing a type of product. Here is how my select tag looks li ...

Is the menu not appearing in the header section of the HTML/CSS?

Hey there, I'm a new student diving into the world of HTML/CSS. I've been working on creating a page layout, but for some reason my menu links are appearing under the header section instead of within it. I'm a bit confused and could really u ...

Issue: jQuery 1.9 causing freezing in Internet Explorer 9 following initial $ajax request

When creating a dynamic webpage, I encountered an issue with Internet Explorer hanging after the first request when using Ajax Long Polling with jQuery 1.9. The script code I implemented is based on this article: Simple Long Polling Example with JavaScrip ...

Tips for using the identical function on matched elements

I am working on a code where I want each textbox input to change its corresponding image. The function is the same for all partners in the list (txt & img). I have looked around and found some similar posts, but I am struggling to make the function wor ...

Having trouble generating a dynamic ref in Vue.js

I am currently working on rendering a list with a sublist nested within it. My goal is to establish a reference to the inner list using a naming convention such as list-{id}. However, I'm encountering difficulties in achieving this desired outcome. B ...

`json object allows for category selection in options`

Hello (please excuse my English), I have the following script: <script type="text/javascript"> $(document).ready(function() { var idPlato = decodeURI(getUrlVars()["idPl"]); var url = "http://localhost/plato-datos.php?idPla="+idPl ...

What is the reason for the error that is being caused by using arrow functions in my code

I'm currently working on a React application, but I keep running into errors that are causing issues. Here is the code snippet in question: import React from 'react'; import { Link } from 'react-router-dom'; const LINKS = [ { to ...