JQuery - Implementing class changes during vertical scrolling yields no results

I have been attempting to dynamically add and remove a class to the navbar based on vertical scroll, but for some reason, it's not having any effect.

The goal is to change the background color of the navbar as the page is scrolled, yet I can't seem to figure out why it's not working.

Even trying to apply CSS directly using $(element).css doesn't seem to be making a difference either.

Check out the code here: https://jsfiddle.net/r4Lxvqps/

Here's the HTML snippet:

<!DOCTYPE html>
<title>A</title>

    <body>
        <div class="container">
            <header class="header">
                <nav class="nav">
                    <ul>
                        <li>
                            <a href="#">Home</a>
                        </li>
                        <li>
                            <a href="#">About Me</a>
                        </li>
                        <li id="logo">
                            <a href="#">Arshdeep</a>
                        </li>
                        <li>
                            <a href="#">Portfolio</a>
                        </li>
                        <li>
                            <a href="#">Contact</a>
                        </li>
                    </ul>
                </nav>
            </header>

            <div class="home">
                <div class="container">
                    <section>

                    </section>
                    <aside>
                        <img src="assets/images/imac.png" alt=""/>
                    </aside>
                </div>
            </div>

            <div class="about">
                <div class="container">

                </div>
            </div>

            <div class="portfolio">
                <div class="container">

                </div>
            </div>

            <div class="contact">
                <div class="container">

                </div>
            </div>
        </div>

    </body>

And the accompanying CSS:

* {
                padding: 0px;
                margin:0 auto;
                -webkit-transition: all .2s ease-in-out;
            }

            html, body {
                height: 100%;
                font-family: 'TitilliumWeb-Regular', 'sans-serif';
            }

            body {
                min-height: 100% !important;
            }

            h1 {
                padding: 0px;
                margin:0px;
            }
            .container {
                position:relative;
                height: 100%;
            }

            nav {
                padding: 5px 0px;
                position:fixed;
                width: 100%;
                top:0;
                z-index: 9999;
                color:black;
            }

            nav > ul {
                text-align: center;
                padding: 5px 0px;
            }

            nav > ul > li {
                display: inline-block;
                vertical-align: middle;
                margin:0 15px;
            }

            nav a {
                text-decoration: none;
                color:white;
                display: block; 
            }

            nav li a:not(#logo) {
                padding: 10px 18px;
            }

            ...

            /** About Me **/

This jQuery script checks if the offset is greater than 50 and then applies the CSS (color: black).JQuery:

$(document).ready(function() {
  $(window).scroll(function() {
    var scroll_offset = $(window).scrollTop;
    if (scroll_offset > 50) {
      $(".nav").css("color", "black");
    }
  });
});

Answer №1

const scroll_position = $(window).scrollTop();

$.fn.scrollTop() should be called as a function. Don't forget to invoke it.

Answer №2

Give this a shot too:

$(window).scroll(function() {
  if ($(window).scrollTop() >= 50) {
$(".nav ul li a").css("color", "black");
  } else {
  $(".nav ul li a").css("color", "white");
  }
});

Check out JSFiddle here!

Answer №3

  1. Utilize the scrollTop method (scrollTop())
  2. Correct the selector: nav a instead of .nav
  3. Include an else statement to revert back to original color

View the jsFiddle demo here

$(document).ready(function() {
  $(window).scroll(function() {
    var scroll_offset = $(window).scrollTop();
    //alert(scroll_offset);
    if (scroll_offset > 50) {
      $("nav a").css("color", "black");
    } else {
      $("nav a").css("color", "white");
    }
  });
});
* {
  padding: 0px;
  margin: 0 auto;
  -webkit-transition: all .2s ease-in-out;
}

html,
body {
  height: 100%;
  font-family: 'TitilliumWeb-Regular', 'sans-serif';
}

body {
  min-height: 100% !important;
}

h1 {
  padding: 0px;
  margin: 0px;
}

.container {
  position: relative;
  height: 100%;
}

nav {
  padding: 5px 0px;
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 9999;
  color: black;
}

nav > ul {
  text-align: center;
  padding: 5px 0px;
}

nav > ul > li {
  display: inline-block;
  vertical-align: middle;
  margin: 0 15px;
}

nav a {
  text-decoration: none;
  color: white;
  display: block;
}

nav li a:not(#logo) {
  padding: 10px 18px;
}

nav li:not(#logo) a {
  opacity: .7;
}

nav li:not(#logo) a:hover {
  opacity: 1;
}

#logo a {
  font-size: 30px;
}

.scrolled {
  background-color: white;
  color: black !important;
}


/** Home Page **/

.home {
  vertical-align: top;
  background-color: #38A5DB;
  color: black;
  min-height: 100%;
  position: relative;
}

.home > .container {
  top: 85px;
  padding: 50px 0px;
  float: left;
  width: 100%;
  color: white;
}

.about,
.contact,
.portfolio {
  min-height: 100%;
}

section {
  float: left;
  width: 48%;
  position: relative;
  text-align: center;
}

aside {
  float: right;
  width: 50%;
}

aside > img {
  width: 80%;
}


/** About Me **/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
    <header class="header">
      <nav class="nav">
        <ul>
          <li>
            <a href="#">Home</a>
          </li>
          <li>
            <a href="#">About Me</a>
          </li>
          <li id="logo">
            <a href="#">Arshdeep</a>
          </li>
          <li>
            <a href="#">Portfolio</a>
          </li>
          <li>
            <a href="#">Contact</a>
          </li>
        </ul>
      </nav>
    </header>

    <div class="home">
      <div class="container">
        <section>

        </section>
        <aside>
          <img src="assets/images/imac.png" alt="" />
        </aside>
      </div>
    </div>

    <div class="about">
      <div class="container">

      </div>
    </div>

    <div class="portfolio">
      <div class="container">

      </div>
    </div>

    <div class="contact">
      <div class="container">

      </div>
    </div>
  </div>

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 is the equivalent command in MongoDB?

Just starting out with MongoDB and I'm curious about the equivalent of this SQL statement: SELECT * FROM users WHERE CONCAT(firstName, ' ', lastName) LIKE CONCAT('Walter Whi', '%') ...

implementing a new class for event handling that includes the toggleClass function

I'm not a full-time jQuery or JavaScript developer, so please forgive me if this is a silly question. I believe I require something similar to the live function for swapping classes in order to handle the values associated with a selector. This is th ...

Working with data filtering in React.js

Imagine having a list of records that you want to filter based on the user's selection from a select box. You can find all the details in this JSFiddle. http://jsfiddle.net/reactjs/69z2wepo/ For instance, if the user chooses 1-10, only numbers betwe ...

How can I modify the material and color of the result in Three.js CSG?

Upon creating a union of two meshes, I want to apply MeshLambertMaterial specifically on the object named 'result': var lathe = new THREE.Mesh(latheGeometry); var cube_bsp = new ThreeBSP( lathe ); var box = new THREE.BoxGeometry( 2,30,3); var ...

What is the method for generating ocean waves using three.js?

I attempted to create ocean waves using three.js, but when I tried running it on a web browser, all I saw was a blank white screen. https://i.sstatic.net/dhEsY.png The code snippet I utilized for generating the ocean waves is: <!DOCTYPE html> <h ...

The JavaScript function getSelection is malfunctioning, whereas getElementById is functioning perfectly

I am encountering a peculiar situation while trying to input text into a textbox using a JavaScript command. The CSS locator does not seem to update the text, whereas the ID locator is able to do so. URL: Below are screenshots of the browser console disp ...

Drupal's Custom Status Update Box with Facebook Like Feature

Currently developing a Drupal site and looking to incorporate a Facebook-like box that generates content, specifically quotations from my Facebook account. Is there a way to accomplish this within the Drupal platform? Additionally, I intend to showcase o ...

Properly maintaining child processes created with child_process.spawn() in node.js

Check out this example code: #!/usr/bin/env node "use strict"; var child_process = require('child_process'); var x = child_process.spawn('sleep', [100],); throw new Error("failure"); This code spawns a child process and immediately ...

The initial dropdown menu in PHP coupled with Javascript fails to retain my chosen option

As a novice PHP programmer, I successfully created a double drop-down list from a MySQL database. The idea is to choose a claims hub in the first box and then select an attorney associated with that specific hub in the second box. However, I am facing an ...

Sending an ajax request to an external service along with the necessary request headers

When it comes to handling contact forms on my website, I have opted to use an external service called emailmeform.com. The only drawback I've encountered with this service is the absence of a public API for making server requests using AJAX. As a resu ...

Off-center map display on Google Maps result

I am utilizing a listener that triggers the display of a div each time a marker is clicked: google.maps.event.addListener(marker, 'click', function() { var boxText = document.createElement("div"); boxText.style.cssText = "margin-top: 8px ...

Slow loading time when switching between items in the drop-down menu from the Main Menu

Visiting my website at europebathroom.com, you will notice a horizontal main menu with dropdown functionality. When hovering over a menu item, the corresponding dropdown appears seamlessly. Yet, sometimes quickly touching another menu item unintentionally ...

Is it possible to transform a class file into a function using hooks?

I have this React class that I want to convert into React hooks. I attempted to do so but ran into some issues. Here are the original and updated codes: class Parent extends React.Component { constructor(props) { super(props); this.state = { nam ...

showing text style that is only specified on the server, not by the client

I am in the process of creating a new website that offers SMS services through clickatell. This website includes various font families that may not be defined on the client's computer. For instance, if the site is accessed from a different computer, t ...

Height of a React Component

I have developed a React component for the homepage of my React application. Utilizing React Router, I am able to navigate through different components on the site. The issue I'm facing is that the homepage component does not occupy the entire page ex ...

Using jQuery/AJAX for conducting multiple searches in MySQL

I have created a form where users can input their Name, region, age, and language. I've written a PHP script to retrieve this data but encountered an issue - if a field is left empty or the user starts typing a name and deletes it, the database return ...

Using Vue to create a single submit() method that works with multiple forms

Having multiple forms with the same logic for validation and submission, I want to streamline my code by creating a single method to handle form actions. Currently, there is redundancy in my code as each .vue file contains the same onSubmit() method. Here ...

Having difficulty in choosing the desired option from the dropdown menu

I seem to be facing a challenge with a dropdown list while trying to select the birth month. Despite my experience working on other websites, I have been unable to resolve this issue. I have attempted: Clicking using different locators. Using Action cla ...

How can numbers be translated into letters?

I have a new security feature for my system where users are required to enter obscure user IDs on their phones. To achieve this, I want to encode the IDs in such a way that guessing them becomes challenging. My plan is to convert the IDs into base-23 numbe ...

Retrieving objects from Firebase in a loop using promises

Seeking guidance on handling promises in AngularJS as a newcomer. Struggling with merging data from two asynchronous arrays into a single array within a for-loop. Encountering a bug where the same picture is displayed for all entries despite different user ...