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

Steps to update XmlHttpRequest URL during image upload

I am currently facing an issue with updating images on my website. When I try to update an image, it redirects to the wrong URL instead of the intended one. The form is set to post data to this URL: POST http://127.0.0.1/mgt/upload/processImage/foodImage ...

Struggling to integrate an audio player specifically for mp3 files and feeling quite perplexed by the process

I'm struggling with implementing an audio player for a file sharing platform, specifically only for .mp3 files. I have successfully implemented a function for images (.jpeg and others), but I am unsure how to do the same for mp3 files. function is_au ...

What types of numerical values is the Number data type capable of storing?

Is it true that a JavaScript number has the ability to store both a 64-bit number and a 64-bit Integer? I'm still unsure about this concept. ...

What is the reason that em takes precedence over p for font-family?

Take a look at this CSS snippet: * { font-family: Gill Sans, Verdana, Arial, Helvetica, Sans-Serif} p { font-family: Courier; } Now let's consider this HTML markup: <p>Hi there. So <em>very</em> pleased to make your acquaintance. ...

Achieve the same functionality as the nextjs getStaticProps() function across all pages without the need to duplicate the code on each page

Is there a way to implement the functionality of the nextjs getStaticProps() function for all pages without duplicating the code on each page? I have multiple pages and a layout component. I am looking to include a global function on all pages. Is it poss ...

Skipping validation while navigating back on SmartWizardIf you need to bypass validation during backward

Looking for assistance with Jquery smartwizard? Check out the link. I want to disable validation when a user clicks on the "Previous" button in any step, except for the first step where the Previous button is disabled by default. Below is my JavaScript co ...

Animating Text Changes with JavaScript and jQuery

In my HTML, I have an input type="text" element and I want to attach an event handler that triggers when the text is changed. The issue arises because this input's value is dynamically updated by another JavaScript function, causing the event handler ...

Having difficulty executing the playwright tests

Trying to execute the playwright test from the specified location results in a message prompting to run npm install -D @playwright/test before running the test. Despite having already installed playwright as a dev dependency, the test is still not being ex ...

Changing the background color of a PHP input based on the webpage being viewed - here's how!

I'm in the process of creating a website where each page will have its own unique background color. Additionally, I am using a PHP input for both the header and footer sections, which need to change their background colors based on the specific webpa ...

Receiving a blank request payload despite implementing a body parsing middleware

I am currently working on setting up a login system, and I have a form that sends a post request to my webpack dev server. This server then proxies the request to my actual server. Here is the function responsible for handling the form submission and send ...

Error: pos variable is not defined

I encountered a TypeError: pos is undefined while running the code below. $(document).ready(function() { var s = $("#col-scroll"); var pos = s.position(); $(window).scroll(function() { var windowpos = $(window).scrol ...

Building a dynamic webpage using AJAX, MVC, and web APIs to generate a div element filled

I'm currently working with a restful API, MVC, and ajax. My goal is to retrieve data from the backend and then display images within certain div elements. The expected outcome should resemble this example: https://i.stack.imgur.com/BFqWL.png This sni ...

Dealing with mistakes in a contact form - Finding the correct function

I developed a form using material-ui in React. I am facing some issues with my submit function. I am using a snackbar to notify the user about the successful submission, as well as a snackbar to alert them about missing required fields. The problem arise ...

React js code to create a position ranking table

Currently, I am in the process of developing a web application using Reactjs with a ranking table managed by Firebase. However, I have encountered a question: Is it possible to dynamically change the position numbers after sorting the table based on the am ...

Adding app stylesheet in Django

I'm a bit unsure about how to incorporate CSS into my HTML. I have an app within my project that has its own template folder, and I would like to include the sample.css file in my HTML. I think it should be something like this: <link rel="styleshe ...

The items are misaligned in a horizontal position

The 4 divs are styled with a width of 23% and displayed using inline-block. They have a fixed height of 220px and no margin applied. However, the issue arises as they are not aligning horizontally Despite attempting to adjust the height and width paramete ...

Conflict arising from duplicated directive names in AngularJS

Hey there, I've got a question for the experts. How can I prevent conflicts with directive names when using external modules? Right now, I'm utilizing the angular bootstrap module, but I also downloaded another module specifically for its carouse ...

The function does not provide an output of an Object

I have two JavaScript classes, Controller.js and Events.js. I am calling a XML Parser from Events.js in Controller.js. The Parser is functioning but not returning anything: SceneEvent.prototype.handleKeyDown = function (keyCode) { switch (keyCode) { ...

Creating a hierarchical JSON format for a nested commenting system

I have a JSON data representing a multi-level comment system as shown below: [{ "thread_id": 2710, "parent_id": "", "username": "string", "comment": "string", "postdate": "2017-06-09T07:12:32.000Z", "id": 1 }, { "thread_id": 2710, "parent_ ...

The HTML button with Google's material-icons appears noticeably small when displayed on mobile devices

Looking to design a basic HTML page with a button placed in the lower right corner? Check out the code below: <!DOCTYPE html> <html> <head> <title>Sample Page</title> <style> /* Styles for the container * ...