Adjusting CSS using JQuery based on scroll position

I am attempting to dynamically change a CSS style depending on the viewer's position on the page. Despite researching numerous similar threads online, I have not been able to get this code to work as intended. Any assistance would be greatly appreciated. Thank you.

The script I was editing can be found here: http://jsfiddle.net/BKnzr/151/

Here is my testing page (which is not functioning properly):

Below is the jQuery code that I am trying to implement:

// cache the elements
var $container = $('#container');
var $nav = $('#a.nav');
var $home = $('#home');
var $about = $('#about');
var $work = $('#work');
var $contact = $('#contact');

// get the view area of #container
var top=$(window).scrollTop();
var bottom = top + $container.height();

// execute code when #container is scrolled
$container.scroll(function() {
if ($home.offset().top < bottom) {
    $nav.css({"color":"green","font-size":"20px"});
} else if ($about.offset().top < bottom) {
    $nav.css({"color":"green","font-size":"20px"});
} else if ($work.offset().top < bottom) {
    $nav.css({"color":"green","font-size":"20px"});
} else {
    $nav.css({"color":"green","font-size":"20px"});
}
});

Answer №1

I found a solution that worked well for my issue, even though I'm not sure if it's the most semantically correct.

$(document).ready(function(){

var container = $('#container');
var nav = $('a.nav');
var home = $('#home');
var about = $('#about');
var work = $('#work');
var contact = $('#contact');

$(window).scroll(function(){
  if ($(window).scrollTop() <= $('#about').offset().top - 360)
  {
$('a.nav-home').css({
  'color': '#2dc9b2',
});
$('a.nav-about').css({
  'color': '#fff',
});
$('a.nav-work').css({
  'color': '#fff',
});
$('a.nav-contact').css({
  'color': '#fff',
});
$("a.nav").removeClass("about-hover");
$("a.nav").addClass("home-hover");
$("a.nav").removeClass("work-hover");
$("a.nav").removeClass("contact-hover");
  }

  else if ($(window).scrollTop() <= $('#about').offset().top * 2 - 360)  {
$('a.nav-home').css({
  'color': '#fff',
});
$('a.nav-about').css({
  'color': '#e7ad4a',
});
$('a.nav-work').css({
  'color': '#fff',
});
$('a.nav-contact').css({
  'color': '#fff',
});
$("a.nav").addClass("about-hover");
$("a.nav").removeClass("home-hover");
$("a.nav").removeClass("work-hover");
$("a.nav").removeClass("contact-hover");
  }

  else if ($(window).scrollTop() <= $('#about').offset().top * 2.9999 - 360) {
$('a.nav-home').css({
  'color': '#fff',
});
$('a.nav-about').css({
  'color': '#fff',
});
$('a.nav-work').css({
  'color': '#a22330',
});
$('a.nav-contact').css({
  'color': '#fff',
});
$("a.nav").removeClass("about-hover");
$("a.nav").removeClass("home-hover");
$("a.nav").addClass("work-hover");
$("a.nav").removeClass("contact-hover");
  }

  else  {

$('a.nav-home').css({
  'color': '#fff',
});
$('a.nav-about').css({
  'color': '#fff',
});
$('a.nav-work').css({
  'color': '#fff',
});
$('a.nav-contact').css({
  'color': '#374ad3',
});
$("a.nav").removeClass("about-hover");
$("a.nav").removeClass("home-hover");
$("a.nav").removeClass("work-hover");
$("a.nav").addClass("contact-hover");
  }
});
});

Answer №2

To correct the code snippet var $nav = $('#a.nav');, remove the "#" symbol as "a" is referencing a tag, not an id.

Alternatively, you can use the following code to ensure only links within the navigation are colorized:

$nav = $('#textlinks-container a.nav')

Answer №3

To achieve the desired outcome of changing the color of the anchor tag text through the plugin that applies the 'current' class to the li tag, you will need to address a CSS specificity issue. The existing code on line 81 of your stylesheet, li.current {color:red}, may not be overriding the previously set style for a.nav {color:#fff;}. To resolve this, consider using a more specific selector like li.current a {color:red;}.

By adjusting the specificity of the CSS selector, you can successfully modify the color of the anchor tag text as intended. I hope this explanation clarifies the issue for you.

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 best way to customize the appearance of an XML snippet using Greasemonkey?

I am attempting to customize an XML fragment retrieved from a server response using a Greasemonkey script. Take a look at this sample XML fragment from w3schools.com: <note> <to> Tove</to> <from>Jani</from> <heading ...

Exploring the world of third-party widgets: Comparing Angular, jQuery, and traditional JavaScript

I have a plan to develop a simple embeddable widget similar to Google ads or Facebook like box. Users will be able to easily add the widget to their website and I will extract some parameters to fetch data from my servers. Previously, I relied on jQuery f ...

how to change the padding in bootstrap container

I'm working with a div that has the container bootstrap class applied to it. This class adds a 15px padding on the left and right sides. I want to maintain this padding for all the children elements within the container, but I also want one specific d ...

How to integrate a jQuery plug-in into your Meteor 1.7.0.3 project

Recently, I delved into using Meteor for the first time, and it has been about a week since I started exploring its functionalities. However, I encountered an issue with integrating jQuery plugins that were installed via npm. After running: meteor npm i ...

JavaScript causing attribute() variable to malfunction in CSS animation

I am attempting to implement a CSS animation using three files. Below is the HTML file: <html lang="en"> <head> <link rel="stylesheet" type="text/css" class = "tag" href="../css/style.css" ...

Troubleshooting problem with jwPlayer resizing in Firefox and Opera browsers

<script type="text/javascript" src="js/jwplayer/jwplayer.js"></script> <div id="myElement"">Loading the player...</div> <script type="text/javascript"> jwplayer("myElement").setup({ file: "video/mosk.mp4", ...

What is the best way to connect the imagemap shape with the checkbox?

I need assistance with synchronizing an imagemap collection of shapes and checkboxes. How can I ensure that clicking on a shape selects the corresponding checkbox, and vice versa? Imagemap: <div class="map_container"> <%= image_tag("maps/main ...

positioning a div based on the location of another div

I am currently working on aligning a div that sits at the bottom of all other divs. The last div is set to float and aligned at the top using CSS. I am unsure how to align it from the left side without any issues when the screen resolution changes. Is th ...

Do we really need to use the eval function in this situation?

Just wondering, is it reasonable to exclude the eval() function from this code? Specifically how <script> ... ... function addGeoJson (geoJsonPath, iconPath = "leaflet-2/images/marker-icon.png", iconSize = [30,50], popUpContent, ...

Sending information from a Java class to an HTML WebView

I have a webpage loaded in my webView that includes the following HTML code: Now I need to automatically populate and submit the textbox within this HTML content from a variable in my Java class, but I'm unsure of how to achieve this. Any assistance ...

Implementing dynamic comment loading with Django and jQuery AJAX

Is there a way to load all the comments of a specific article when the user clicks on the comments link, using Jquery Ajax without refreshing the page? I've outlined my approach here, but if there's a better method, please share your suggestions. ...

A guide to retrieving all image URLs when a checkbox is selected using Javascript

My goal is to extract only image URLs from the concatenated values of price and picture URL. However, when I check different images using checkboxes, it always displays the URL of the first selected image. When I try to split the value, all the prices and ...

Picture not adapting correctly to various screen sizes

I'm looking to adjust the size of an image based on the user's browser window. Here is the code I have so far: .image { max-height: 15%; width: auto; } The image class is used in this section of my code: <ul> <li> <img c ...

Customize Material-UI Icons styles in React app

I'm working on a React.js app with Typescript and I need to remove the default visited Material Icons coloring from an anchor tag. Here's the stylesheet I tried: const useStyles = makeStyles((theme: Theme) => createStyles( myAnchor: ...

What is the best way to center align an element while having another element situated directly below it?

I want to create a grid of "clock" elements, with five clocks in each row. Below each clock, I'd like to display the DAY and DATE centered with the clock (day on top line, date below). Since I'm new to html/css, I appreciate your patience. Here&a ...

Can an enterprise level web application be effectively built using [HTML5 + jQuery] (without ASP.NET) + WCF?

We have been utilizing ASP.NET web forms for a long time to get some perspective. While we understand the advantages of MVC over web forms, there's now a suggestion on the table to skip all abstraction layers and move directly from a pure .HTML page ...

Transmit the JSON Data file through an AJAX request

I am encountering an issue where the HttpPostedFileBase is null when trying to send an image file to a Controller. I have attempted entering image: image outside of JSON.stringify({}), but it did not work. Additionally, I tried changing the contentType f ...

Using the parent id in knockoutJs to create a nested menu

I'm currently attempting to create a nested menu using the JSON data provided by the client. Here is the data: var serverData = [ { Id: "menuColorSearch", Text: "Color search" }, { Id: "menuAncillaryProductM ...

Generate an array using hyperlinks within a list item created by the user

In the process of developing a program, I have included a feature where users can drag and drop .wav files into a playlist-container. These files are then played in the order they are arranged within the playlist-container. Currently, I am working on imple ...

What is the Best Method to Retrieve the Desired Data from a YQL Query using a Callback Function?

I successfully implemented a callback function that retrieves titles related to a user-submitted string in a text input box. However, I am struggling with how to extract only the titles from the returned callback function after submitting a search term. C ...