Issues arise with the onscroll functionality when it is responsible for executing numerous conditional statements

My JavaScript function triggers various conditional statements based on the user's scrolling behavior.

(Specifically, it adjusts the design of my navigation links as the window moves into different sections or rows.)

// list of variables
var pLink = document.getElementById('p-link');

var rLink = document.getElementById('r-link');

var bLink = document.getElementById('b-link');

var cLink = document.getElementById('c-link');

var pElement = document.getElementById('slide');

var row2 = document.getElementById('row-2')

var pHeader = document.getElementById('p-header');

//function implementation

window.onscroll = function() {scrollLink() };
function scrollLink() {

/* 
When the top of the window scrolls to a certain point (within 100):
the background color of row-2 and text elements revert back to their original styles 
*/

if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
} else {
        document.getElementById('row-2').style.backgroundColor = "#5e312b";
        document.getElementById('p-header').style.color = "#fff";
        pElement.style.color = "#fff";

/*
When the top of the window scrolls past 450:
execute slide() for text animation from left to center
*/

} if (document.body.scrollTop > 450 || document.documentElement.scrollTop > 450) {
        slide();

/* 
When the top of the window enters row-2 (past 692):
change nav link colors from pink to white and reduce opacity 
needed for visibility when bgChange1 turns background pink
when window scrolls back to row-1 (past 692 in opposite direction):
revert nav link colors and opacity
*/

} if (document.body.scrollTop > 692 || document.documentElement.scrollTop > 692) {
        pLink.style.color = "#fff";
        rLink.style.color = "#fff";
        bLink.style.color = "#fff";
        cLink.style.color = "#fff";
        rLink.style.opacity = ".6";
        bLink.style.opacity = ".6";
        cLink.style.opacity = ".6";
}   else {
        pLink.style.color = "#D07F8D";
        rLink.style.color = "#D07F8D";
        bLink.style.color = "#D07F8D";
        cLink.style.color = "#D07F8D";
        rLink.style.opacity = "1";
        bLink.style.opacity = "1";
        cLink.style.opacity = "1";
}
};

The current function is functioning correctly.

However, when I try to introduce an additional conditional statement below, the function starts malfunctioning. The new condition does not trigger, and it disrupts the previously working logic above.

/*
When the top of the window reaches row-3 (past 1800):
change nav link colors to pink for better visibility against background
when window returns to row-2 (past 1800 in reverse):
reset nav link colors and opacity to match row-2 style
*/

if (document.body.scrollTop > 1800 || document.documentElement.scrollTop > 1800) {
        pLink.style.color = "#D07F8D";
        rLink.style.color = "#D07F8D";
        bLink.style.color = "#D07F8D";
        cLink.style.color = "#D07F8D";
        pLink.style.opacity = ".5";
        bLink.style.opacity = ".5";
        cLink.style.opacity = ".5";
} else {
        pLink.style.color = "#fff";
        rLink.style.color = "#fff";
        bLink.style.color = "#fff";
        cLink.style.color = "#fff";
        pLink.style.opacity = "1";
        bLink.style.opacity = "1";
        cLink.style.opacity = "1";
} 

Answer â„–1

One of the reasons why your ifs are not working as expected is because they are all treated separately and not properly structured using else if. This means that every time the function runs, it will always hit the else statement of the last if block you added.

For instance, when

if (document.body.scrollTop > 1800 || document.documentElement.scrollTop > 1800) {
evaluates to false, which happens anytime it is not greater than 1800, it triggers the else statement resetting everything back to white and full opacity.

In simpler terms, each if block operates independently. Therefore, any previous style changes will be overridden each time the function executes since it will always enter one of these blocks.

if (document.body.scrollTop > 1800 || document.documentElement.scrollTop > 1800) {
        pLink.style.color = "#D07F8D";
        rLink.style.color = "#D07F8D";
        bLink.style.color = "#D07F8D";
        cLink.style.color = "#D07F8D";
        pLink.style.opacity = ".5";
        bLink.style.opacity = ".5";
        cLink.style.opacity = ".5";
} else {
        pLink.style.color = "#fff";
        rLink.style.color = "#fff";
        bLink.style.color = "#fff";
        cLink.style.color = "#fff";
        pLink.style.opacity = "1";
        bLink.style.opacity = "1";
        cLink.style.opacity = "1";
} 

To address this issue, consider adding return statements in each if block to prevent subsequent ifs from running once you have set the necessary styles.

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

What happens to PHP echos when you send a post request to a web page?

I have a question that may seem silly to some. As someone who is relatively new to PHP, I am attempting to view echo statements from a page that I am posting to but not actually navigating to. Directly accessing the page's URL without the necessary po ...

Difficoltà nel caricare un file CSS esterno su una pagina HTML

As a newcomer to the world of HTML and CSS, I am venturing into customizing the 404 error page on Altervista known as not_found.html. This page pulls in styles from an external file named Style.css located within a folder titled Sheets-Style while the page ...

Using Vue.js causes an issue with Array.from(Object).forEach

When using vue.js 2 CLI, I typically define object data like this within the data() function: data(){ return{ user: { user_mail: '', user_password: '', user_confirm_password : '' ...

Implementing Cross-Origin Resource Sharing (CORS) in play-framework version 2.5.x: A Step-by-Step Guide

My current challenge involves retrieving JSON data by sending a request to a Restful URL from localhost within an AngularJS-1 application. The error that I encounter is as follows: http://localhost:9000/mlm/user/all Failed to load resource: the server r ...

How can you protect your webhook from unauthorized access?

I am looking to create a webhook that will update the status of a document in my collection, triggering additional events in the process. Router.route('/mandrill/invitation_sent', { where: 'server' }) .post(function () { var resp ...

Uncertain on the Character Count for MailTo Links

I have been utilizing the mailto function in my application to launch email templates in Outlook. However, I have noticed that at times my text gets cut off. I am unable to determine the exact character limit and whether it includes the syntax part as well ...

Is there a way to perfectly center this image with the rest of my text content?

Seeking assistance in aligning this image to the right alongside other text content. Currently, when the code is executed, the image is pushed down and positioned below the text on the right side. Ideally, I would like the image to be aligned evenly with ...

Collecting numerous user-input data from dynamically generated fields

I am working on a simple form in Laravel where users can add multiple forms dynamically using AJAX. Here is the link to my code on jsfiddle: dynamic adding field by user Below is the HTML structure: <form id="paramsForms"> {{csrf_f ...

Pull in content or data from a separate page by leveraging AJAX

Hello, I'm just starting out in programming and I could really use some help with this issue. index.html <button id="press">Click here</button> <div id="show_image"> </div> <br> <div id="appended_area"></div&g ...

The background image will not repeat to completely cover the height

Click here to view my issue. I have set the background image to repeat the entire height, but it's not behaving as expected. Here is my CSS #wrapper { margin: 0px; padding: 0px; background: url(img02.jpg) repeat-x left top; } I attempt ...

Generate a Calendar Table using JavaScript in the Document Object Model (DOM

I have set up a table with 6 rows and 5 columns. The purpose of the table is to represent each month, which may have varying numbers of days. I want each column to display dates ranging from 1-30 or 1-31, depending on the specific month. Here's what ...

Is there a way to retrieve the number of notifications that have not been seen or read from the API?

Is there a way to retrieve the unread or unseen count in PHP without relying on a real-time notifications JavaScript library? Typically, using a JavaScript library would provide the following information: "data": { "deleted": "array of activities or ...

Why is it that injecting javascript within innerHTML seems to work in this case?

According to the discussion on this thread, it is generally believed that injecting javascript in innerHTML is not supposed to function as expected. However, there are instances where this unconventional method seems to work: <BR> Below is an examp ...

Are you looking to enhance your website with dynamic and

I am looking to display dynamic text in a label using HTML. This label should be populated with text from a Javascript function upon loading or reloading the page. How can I make this happen? <label id="MyLabel"></label> <script type="tex ...

Transferring data to and from Firebase

I am currently developing a photo app in Ionic, but I am facing some issues when trying to display the photos after uploading them. Here is my .ts file: interface FeaturedPhotoUrls { url1?: string; url2?: string; } @IonicPage( { name: 'A ...

Text Overflow Issue in iOS Mail Tables

Encountering an issue with iOS Mail where the text size increases, causing it to overflow outside the table cell. The table displays correctly on desktop Outlook/web mail but not on the Mail app. I've attempted to add word wrap without any impact. Is ...

AngularJS is designed to provide alternating colors specifically for the objects that are currently visible within the complete set

Within my angularjs application, I am working with the following JSON data: $scope.itemsList = { "busName": "ABC", "needsToHide": true, "num": 123 }, { "busName": "xyz", "needsToHide": false, "num": 567 ...

Using JQuery to monitor the loading of a newly selected image src attribute

As a newcomer to JavaScript and JQuery, I am facing a challenge that I couldn't find a solution for in other discussions: I have a function that retrieves the path to an image (/API/currentImage) using a GET request and needs to update the src attrib ...

Direction of Scrolling

Is it possible to have a div move in the opposite direction of mouse scroll, from the top right corner to the bottom left corner? Currently, it is moving from the bottom left to the top right. #block { position: absolute; top: 400px; left: 100px; < ...

I'm struggling to navigate the login process on a website to access the HTML code

Below is the HTML code for a button: <form id="loginbox_form" class="okform initialized" method="post" action="https://www.okcupid.com/login"> <div id="login_usernameContainer" class="inputcontainer input empty"> <input id="logi ...