Home > front end >  How can I make text change when a page is scrolled to a certain point using jQuery?
How can I make text change when a page is scrolled to a certain point using jQuery?

Time:06-30

I am trying to make the content of a div change when the page is scrolled to a certain point using jQuery. Currently, I am trying to accomplish this by adding a class when the page is scrolled past 800 and removing it and adding a different class when the page is above 800. Here is my current code on jsfiddle: https://jsfiddle.net/shgfrdm8/

Here is the jQuery code:

$(window).scroll(function() {
            let windowTop = $(window).scrollTop();
            if (windowTop < 800) {
                $('image-content').addClass('scrolledDown');
                $('image-content').removeClass('scrolledUp');
            } else {
                $('image-content').addClass('scrolledUp');
                $('image-content').removeClass('scrolledDown')
            }
        })

The CSS ids/classes:

.main {
    width: 100%;
    height: 700px;
    overflow: hidden;
    position: relative;
}

.main-image {
    width: 100%;
    position: fixed;
    left: 50%;
    transform: translate(-50%) scale(500%);
}

.filler {
    height: 400vh;
}

.main-text {
    left: -14px;
    width: 99.3vw;
    height: 4000px;
    text-align: center;
    background-color: red;
    position: relative;
}

#image-content::before {
    white-space: pre;
    position: absolute;
    bottom: 20px;
    left: 20px;
    font-family: Impact;
    font-size: 55px;
    font-weight: 550;
    color: white;
    z-index: 4;
    opacity: 1;
    position: fixed;
}

#image-content.scrolledDown::before {
    opacity: 1;
    content: 'ABC';
}

#image-content.scrolledUp::before {
    opacity: 1;
    content: "DEF";
}

The HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="zoom.css">
</head>
<body>

    <div >
        <div >
            <img src="images/sourcecode.jpg" >
        </div>

        <div id="content-anchor"></div>
        <div id="image-content"></div>
    </div>

    <div >

    </div>

    <div >

    </div>

I am wondering how I can make this work because I far as I can tell the classes either not being added or the classes are not working.

CodePudding user response:

Suggesting the following changes:

$(window).scroll(function() {
  var windowTop = $(window).scrollTop();
  if (windowTop < 800) {
    $('.image-content').addClass('scrolledDown');
    $('.image-content').removeClass('scrolledUp');
  } else {
    $('.image-content').addClass('scrolledUp');
    $('.image-content').removeClass('scrolledDown')
  }
});

This ensures you have the correct Class selector.

  • Related