How can you prevent an element from overflowing when employing window.pageYOffset and using a switch case to alter the background color at specified pixel thresholds?

I want the <body> element's background-color to change every 500px as I scroll down.

I've scoured the web for answers, but still can't figure out what's going wrong. Please review the code. However, Firefox Browser indicates that an element is causing overflow in the body tag

https://i.stack.imgur.com/IbbZk.png

I attempted using overflow: hidden with CSS on both the body and html tags, but it just made the scroll bar disappear.

I'm a beginner at coding. It should be correct since it's from a learning module by my teacher. Thank you for your assistance. UPDATE: My mistake was in transcribing the code.

All the responses provided solutions to resolve this problem. Thanks to everyone who helped.

<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="UTF-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>CHALLENGES</title>
        <style>

            body {
                height: 3000px;
            };

            .one {
                background-color: beige;
                transition: all 3s;
            };

            .two {
                background-color: blueviolet;
                transition: all 3s;
            };

            .three {
                background-color: coral;
                transition: all 3s;
            };

            .four {
                background-color: cornflowerblue;
                transition: all 3s;
            };

            .five {
                background-color: darkgoldenrod;
                transition: all 3s;
            };
        </style>
    </head>
    <body class="one">

        <h1>Javascript Event Challenges: Challenge 29</h1>
        <p>Scroll Down!</p>

        <script>

            var pageTop;
            var bodyTag = document.querySelector("body");

            window.addEventListener("scroll", function(){

                pageTop = window.pageYOffSet;

                switch(true) {
                    case pageTop < 500: bodyTag.className = "one"; break;
                    case pageTop < 1000: bodyTag.className = "two"; break;
                    case pageTop < 1500: bodyTag.className = "three"; break;
                    case pageTop < 2000: bodyTag.className = "four"; break;
                    default: bodyTag.className = "five";
                }
            });

        </script>
    </body>
</html>

Answer №1

This particular line isn't functioning as expected due to a typo in the 'Offset' :

pageTop = window.pageYOffSet;

The correct version should read:

pageTop = window.pageYOffset;

Currently, it's only returning 'undefined'. You can alternatively utilize 'scrollY' which is another term for 'pageYOffSet':

 pageTop = window.scrollY;

The issue with the colors arises from using a ";" at the conclusion of each CSS query. Removing those will rectify this problem.

Answer №2

  1. The correct spelling is window.pageYOffset, not window.pageYOffSet.

  2. Make sure to remove all semicolons after CSS classes in the <style> element as they are not valid syntax.

Answer №3

Take a look at the link provided

If you try adding pageTop = window.scrollY; it may work

Make sure to delete the semicolon from the css code as well

let pageTop;
let bodyTag = document.querySelector("body");
window.addEventListener("scroll", function(e){
    pageTop = window.scrollY;
    switch(true) {
        case pageTop < 500: bodyTag.className = "one"; break;
        case pageTop < 1000: bodyTag.className = "two"; break;
        case pageTop < 1500: bodyTag.className = "three"; break;
        case pageTop < 2000: bodyTag.className = "four"; break;
        default: bodyTag.className = "five";
    }
});
body {
    height: 3000px;
    display:block;
}

.one {
    background-color: beige;
    transition: all 3s;
}

.two {
    background-color: blueviolet;
    transition: all 3s;
}

.three {
    background-color: coral;
    transition: all 3s;
}

.four {
    background-color: cornflowerblue;
    transition: all 3s;
}

.five {
    background-color: darkgoldenrod;
    transition: all 3s;
}
<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="UTF-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>CHALLENGES</title>
    </head>
    <body class="one">
        
        <h1>Javascript Event Challenges: Challenge 29</h1>
        <p>Keep scrolling!</p>
    </body>
</html>

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

Registering a function for chart.js plugins that manipulates external data

Is there a way to pass external data to the chart.plugins.register function? I'm struggling because I can't access the necessary context: Chart.plugins.register( { beforeDraw: function (chart) { //implementation } }); I attempted using ...

An uncomplicated broadcasting and receiving method utilizing an event emitter

This code is from chapter 3, example 11 of the book Node.JS in Action, found on page 52. var events = require('events'); var net = require('net'); var channel = new events.EventEmitter(); channel.clients = {}; channel.subscriptions = ...

Attempting to utilize express-load in conjunction with express 4

As a beginner in NodeJS, I encountered a problem with my code. Let me show you the issue. I am trying to load the application in the MVC pattern using express-load, but I am facing an error when defining the load order. Here is the important part of app. ...

Implementing a feature that loads older posts on a webpage as users scroll down

Spent hours trying to get my site to automatically load older posts on scroll down with no luck. Any assistance is greatly appreciated :) After researching, [this tutorial][1] seemed like the best solution so I followed it step by step and integrated ever ...

Expanding Module Scope to Just the Request (employing Require, Node.js)

Original Query The project I am currently working on is using Express to manage HTTP requests. The structure of the project is quite intricate, with multiple embedded require statements. Our main challenge lies in maintaining access to the request and re ...

Rings that react to both width as well as height

Below is a popular CSS markup for creating responsive circles. http://jsfiddle.net/WTWrB/355/ <div class="circle"></div> .circle { width: 25%; height:0; padding-bottom: 25%; -moz-border-radius: 50%; -webkit-border-radius: ...

Can VueJS 1 and 2 be integrated within the same package.json configuration?

At the moment, my JavaScript files are using VueJS 1. However, I am preparing to work on a new section of the system and want to switch to VueJS 2. ...

Looking to extract a Twitter handle using Python's BeautifulSoup module?

I'm struggling to extract the Twitter profile name from a given profile URL using Beautiful Soup in Python. No matter what HTML tags I try, I can't seem to retrieve the name. What specific HTML tags should I be using to successfully grab the prof ...

How to prevent selecting future dates in Material UI date picker

Is there a way to prevent selecting future dates in the material UI datepicker? I noticed that it doesn't seem to have any prop options like disableFuture or past. For those interested, here's the link to the github repository sandboxlink ...

Finding a jQuery DOM element without using a loop

Can the element in variable d be identified directly instead of looping through each function? Take a look at the DOM below: <!DOCTYPE html> <html lang="en"> <head> <title></title> <script src="../jquery-ui ...

Is Moment.js displaying time incorrectly?

When using moment.tz to convert a specific date and time to UTC while considering the Europe/London timezone, there seems to be an issue. For example: moment.tz('2017-03-26T01:00:00', 'Europe/London').utc().format('YYYY-MM-DD[T]HH: ...

Leveraging the power of the Twitter API to integrate real-time tweets into custom code

Looking for an API that can transform a tweet from Twitter into a string format suitable for integration into a program or website. Any recommendations? ...

Splitting data in NodeJS sockets

Whenever I encounter the need to divide data, my standard practice involves converting it into a string format. Here's an example of how I handle data in my function: socket.on('data', function (data) { var str = data.toString().spl ...

What is the best way to automatically insert data into a database at regular intervals, while ensuring that users are unable to manipulate the timing through inspect

Is there a secure way to insert 1 point into the database every x seconds without allowing users to manipulate the interval time through inspect element? var time = 1; var interval = setInterval(function() { if (time != time + 1) { ...

Help needed with debugging CSS for IE6 >_<

I have been working on the following website: www.darksnippets.com While the design looks good on Firefox and Chrome, it appears terrible on IE6. For example, on the home page and other pages like , the width is too wide in IE6. I've been unable to ...

Styling material-ui textfield: Tips and tricks

I've been grappling with figuring out how to customize a material-ui TextField component. <TextField id="email" label="Email" className={classes.textField} value={this.state.form_email} onChange={this.handle_change('form_e ...

Looking to incorporate jQuery Form Wizard with mandatory radio button groups?

Currently, I am utilizing the jQuery Form Wizard plugin from The Code Mine website to transform a form into a wizard format. Myform consists of five pages, each containing approximately four radio buttons. It is crucial that at least one radio button on ea ...

Using Aurelia to create a schema form

In my project, I am utilizing Aurelia to create a dynamic form based on a JSON data. The form is being generated from a JSON structure similar to the one shown below: Schema = [{ 'key': 'Name', 'display': 'Name&a ...

sending information from a PHP form to a JavaScript window

Currently, I am in the process of developing a game using javascript and jquery. In this game, when a player interacts with another character, it triggers the opening of text from an external file using the window.open('') function. At the start ...

Troubleshooting issue: AngularJS NVD3 line chart directive does not refresh after data update (not updating in real time)

I am currently facing an issue with the nvd3-line-chart directive in my AngularJS application. The chart does not redraw when I change the underlying model... As a newcomer to AngularJS, there may be something obvious that experienced programmers will not ...