Alter the border line's color based on the specific section or div it overlays

I am attempting to utilize jQuery in order to change the color of my border line depending on its position within the divs. I have set the position to absolute and it is positioned on both divs. My goal is to make the line on the top div appear as grey, while the line on the bottom div should be white. This color change should occur dynamically based on which section the line is over.

Link to CodePen: https://codepen.io/asreenz/pen/MWpGMQO

var top1height = $(".top-box" ).height();
var bottom1height = $(".bottom-box" ).height(); 
 var linePosition = $(this).offset();
if(linePosition > top1height){
   $(".line").addClass(".line-grey"); 
   } 
else {
   $(".line").removeClass("line-grey"); 
   }
if(linePosition > bottom1height){
   $(".line").addClass(".line-white"); 
   } 
else {
   $(".line").removeClass("line-white"); 
   }
.line{
  width:0px;
  height: 100px;
  border: 1px solid black;
  position:absolute;
  left: 50%;
  bottom: -225px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
.top-box{
  width:100vw;
  height:500px;
  background-color: pink;
}
.bottom-box{
  width:100vw;
  height:500px;
  background-color: yellow;
}
.line-grey{
  color:#8a96a3;
}
.line-white{
  color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <div class="line">
    </div>
  <div class="top-box"></div>
  <div class="bottom-box"></div>
</div>

Answer №1

I'm not sure if the jQuery code you provided will function correctly, but one thing I can suggest is to utilize the "border-color" property instead of "color". Consider implementing it in this manner:

.line-grey {
    border-color: #8a96a3;
}

.line-white {
    border-color: white;
}

Answer №2

If you are looking for a way to dynamically change the color of a line as you scroll between boxes, I have a solution for you. Check out this unique pen I created just for this purpose: https://codepen.io/uniqueusername/pen/XyZabcde

This method is even simpler and can handle an unlimited number of boxes. All you need to do is replace the data attribute with your desired line color for each box.

Additionally, in this version, I modified the positioning of the line element to fixed, making it easier for you to observe the color transition.

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
   <div class="line"></div>
   <div class="box" data-line-color="rgba(255,255,255,1)"></div>
   <div class="box" data-line-color="rgba(0,120,255,1)"></div>
   <div class="box" data-line-color="rgba(255,255,255,1)"></div>
   <div class="box" data-line-color="rgba(0,120,255,1)"></div>
</div>

CSS

.line{
  width:0px;
  height: 60px;
  border: 1px solid rgba(255,255,255,1);
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  margin: 0 auto;
  transition: .3s all;
}
.box{
  width: 100vw;
  height: 500px;
  background-color: rgba(0,0,0,1);
  border: 5px solid white;
}

jQuery Code

(function ($) {
$(window).scroll(function() {    
    var scrollTop = $(this).scrollTop() + $(this).height() / 2; 
    $('.box').each(function() {
      if (scrollTop > $(this).offset().top) {
          $('.line').attr('style','border-color: ' + $(this).data('line-color')); }
       });
  });
})(jQuery);  

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

Creating dynamic bar chart visuals using Morris.js with JSON responses

Utilizing the morris.js library, I am extracting and plotting bar charts from data retrieved through a webservice. Issue: The format of my webservice URL is as follows: http://localhost:9999/hellowebservice/search?select=* I populate the select query ...

Height Miscalculation: Chrome and FF encounter window dimension

There is a large application with numerous pages. When I use the console to execute console.log($(window).height()) on any page within the application, it returns the expected result: the height of the window, not the document. For instance: $(window).he ...

Tips for displaying identical tab content across various tabs using jquery or javascript

For instance, if we have tabs labeled as 1, 2, 3, 4, and 5, and a user has selected tabs 2, 3, and 4, how can we display the same content for those tabs while showing different content for the remaining ones? ...

Tips for closing process.stdin.on and then reopening it later

I've been facing a challenge with an exercise. In this exercise, the client will input a specific integer x, followed by x other y values separated by spaces. The output should be the sum of each y value, also separated by spaces. For example: Input: ...

Why is it that GetElements does not provide immediate results upon execution?

Just diving into the world of Javascript for the first time and experimenting with it on Chrome, but running into unexpected results. When I try: document.getElementsByTagName("h1") I anticipate seeing: <h1>tester h1 in body</h1> Instead, wh ...

Strong tags are not functioning properly within paragraph tags in Firefox

It has come to my attention that when I insert <strong> into a <p>, the text does not appear bold. This issue seems to only occur in Firefox, as Chrome and Safari display it correctly. However, when I place <strong> inside a <li>, e ...

The most effective method for incorporating a header and footer into an HTML page utilizing a variety of client-side frameworks

Looking for a solution for my HTML project where I want to incorporate a header and footer to minimize rework. Any suggestions on a good approach? I have experimented with AngularJS using ng-include, and here is the code snippet: var app = angular.module ...

Using JavaScript to disable and re-enable an ASP.NET Timer control

I currently have a webpage built with ASP.Net that includes an ASP:Timer control <asp:Timer ID="TimerRefresh" runat="server" Interval="5000" Enabled="true" OnTick="TimerRefresh_Tick"> </asp:Timer> It is connected to an asp:UpdatePanel on the ...

Exploring the connections between PHP, JavaScript, JSON, and AJAX

While this question may lean more towards conceptual understanding rather than pure programming, it is essential for me to grasp how these mechanisms interact in order to code effectively. My current knowledge includes: 1) PHP as a programming language ...

Tips for Including a Parallax Image Within a Parallax Section

Currently, I am working on implementing a parallax effect that involves having one image nested inside another, both of which will move at different speeds. My progress has been somewhat successful, however, the effect seems to only work on screens narrowe ...

ways to disrupt a timeout

I am attempting to incorporate a functionality similar to this example: https://www.w3schools.com/jsref/met_win_cleartimeout.asp On my personal website: If you enter certain characters in the input field, select one of them, and then pause for 5 seconds, ...

There is an issue as headers cannot be changed after being set for the client

I am in the process of developing an employee leave management system. Everything runs smoothly until an issue arises when attempting to update the leave status as an admin, and the logged-in account or user does not have admin privileges. There is a midd ...

What sets response.setHeader apart from response.writeHead?

When it comes to sending a JSON response from my Nodejs server in my application, I have discovered two different methods. However, I am unsure about the distinctions between them. The first method involves var json = JSON.stringify(result.rows); respons ...

Leveraging parameters within a sequence of object properties

Within the realm of Angular, I am dealing with interfaces that take on a structure similar to this (please note that this code is not my own): export interface Vehicles { id: number; cars: Car; trucks: Truck; } Export interface Car { make: ...

Customizing React components based on API data

const LinkList = () => { const [links, setLinks] = useState([]); const url = 'http://localhost:5000/xyz'; const hook = () => { console.log('effect'); axios .get(url) .then(respo ...

Arrangement of cards in a column

As someone who is new to working with CSS, Wordpress, and similar technologies, I am seeking assistance. I am struggling with creating card layouts. My goal is to achieve a layout similar to this, where the cards are displayed in two columns instead of ju ...

Endless Loading in Node.js on Google App Engine

I have deployed a standard nodejs app (free tier) using cloud shell, but when I try to access https://[ID].du.r.appspot.com/ , it keeps loading indefinitely. app.js: const express = require('express'); const path = require('path'); co ...

jQuery can be used to obtain the label for a checkbox with a particular value

Currently, I am facing an issue with retrieving the label for a checkbox using jQuery. Let me provide you with the relevant HTML code: <div class="checkbox"> <label><input type="checkbox" name="cb_type[]" value="sold" >Sold</label ...

Issue with the execution of Javascript code. Edit required

After creating a registration form that allows users to input their information for registration, I encountered an issue where if certain fields were left empty or if the user name was unavailable or the email address was already registered, a warning mess ...

Error: The Node Express Server is unable to locate the requested resource at "/

const http = require("http"); const myApp= require('./myApp'); const portNumber = 8080; const myServer = http.createServer(myApp); myServer.listen(portNumber) ...