Is it possible to dynamically change the color of text based on its position using CSS, JS, or JQuery?

I am currently working on a corporate website and have been tasked with creating a unique design for a specific page. The design includes the following elements:

A body background gradient that transitions from their primary color to white in a top-to-bottom static manner.

All headers (h1, h2, h3, etc.) must be displayed in white text.

My challenge now is finding a way to ensure that header colors complement the overall design, even when they are not positioned at the very top of the page. This is especially important for sub-headers and section titles.

Is there anyone out there who knows a CSS, Javascript, or jQuery solution that would dynamically change the text color of headers based on their position on the page? For instance, having headers display in white at the top of the page to contrast the primary color of the body gradient, but switch to the primary color further down the page to contrast the white background?

Answer №1

If you're feeling adventurous, you might want to experiment with the css3 filter "invert." While the results may not be perfect at this time, exploring its potential could be interesting.

$(document).ready(function() {
  $("h2").each(function() {
    var offset = $(window).scrollTop() - $(this).position().top;
    var height = $(document).height();
    var percent = (-offset * 100) / height;
    $(this).css({
      'filter': 'invert(' + percent + '%)'
    })
  });
});
body {
  background: #7cf1ff;
  background: -moz-linear-gradient(top, #7cf1ff 0%, #96a0e7 100%);
  background: -webkit-linear-gradient(top, #7cf1ff 0%, #96a0e7 100%);
  background: linear-gradient(to bottom, #7cf1ff 0%, #96a0e7 100%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#7cf1ff', endColorstr='#96a0e7', GradientType=0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>Headline</h2>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
  sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
  Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
<!-- Repeated headline and paragraph elements for demonstration purposes -->

Answer №2

CSS mix-blend-mode offers a similar functionality to what you are looking for, but it may not be well-supported in all browsers particularly IE/Edge.

html,
body {
  margin: 0;
  padding: 0;
  background: linear-gradient(180deg, yellow 0%, green 100%);
  font-size: 0;
  height: 200%;
}
.outer {
  display: inline-block;
  width: 200px;
  height: 200px;
  font-family: sans-serif;
  font-size: 40px;
  line-height: 200px;
  text-align: center;
  font-weight: bold;
}
.inner {
  color: white;
  mix-blend-mode: difference;
}
.solid {
  background-color: navy;
}
.gradient-bw {
  background: linear-gradient(180deg, black 0%, white 100%);
}
.gradient-color {
  background: linear-gradient(180deg, navy 0%, orange 100%);
}
.fixed {
  position: fixed;
  padding: 20px;
  right: 0;
  bottom: 0;
  color: white;
  font-size: 40px;
  z-index: 2;
  mix-blend-mode: difference;
}
<div class="outer solid">
  <div class="inner">
    Text!
  </div>
</div>
<div class="outer gradient-bw">
  <div class="inner">
    Text!
  </div>
</div>
<div class="outer gradient-color">
  <div class="inner">
    Text!
  </div>
</div>
<div class="fixed">
  Text!
</div>

Answer №3

Is this the solution you've been searching for?

$(window).on("scroll", function() {
    if($(window).scrollTop() > 150) {
        $(".header").addClass("activeOne");
    }        
    else {
       $(".header").removeClass("activeOne");
    }
});

http://jsfiddle.net/jdcutter/634d6vgq/129/

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 indicator that signals a change in the value of a React ref.current?

Typically, when using props, we would write componentDidUpdate(oldProps) { if (oldProps.foo !== this.props.foo) { console.log('foo prop changed') } } to identify any changes in props. However, if we utilize React.createRef(), how can w ...

Utilizing JavaScript for Formatting and Comparing Dates

Here, I would like to compare the current date with a user-inputted date. <script type="text/javascript"> $(document).ready(function(){ $("#date").change(function(){ var realDate = new Date(); var startDate = new ...

Using JQuery to locate radio buttons that have been selected based on a variable

In my JavaScript code, I have created a variable called "thisRadio" to represent a dynamically generated div containing multiple radio buttons. Currently, one of these radio buttons may be checked and my goal is to find the checked radio button within this ...

Align text vertically within a link box by overriding inherited CSS styles

Fiddle: http://jsfiddle.net/jgallaway81/ax9wh/ <a href="lcars.jfx.php" class="leftbuttons buttonlinks antibutton"> LCARS Locomotive O.S. </a> My issue pertains to the alignment of text within a graphic. I am utilizing this particular button ...

What is the procedure for passing arguments to Google signIn in a NextJS backend?

I am currently working on implementing a role-based Google sign-in feature in a Next.js 13 app using next-auth. This setup involves calling two different tables to create users based on their assigned roles. For the database, I am utilizing mongodb/mongoo ...

Website layout looking unique due to pixel width adaptation from standard width

I'm currently working on a website with full width design. On my computer, the website displays as full width, but on other computers it shows extra space on the sides. How can I ensure that this website is truly full width? .wrapper_boxed { wid ...

Changing the value of an ASP HiddenField within an MVC 4 controller

I have created a simple asp:HiddenField in my view: <asp:HiddenField ID="hdnUserRole" runat="server" /> Now, I am utilizing RedirectToAction in the following manner: if (Something) { return RedirectToAction("Index", "AdminView" ...

Embedding Custom CSS Within a Parent CSS Element

After implementing a Wordpress Theme, I encountered the need to customize the styles of one of its elements. (This particular element displays our tours automatically) Currently, the style is as follows: .tourmaster-tour-grid .tourmaster-tour-content-wrap ...

Tips on preventing a nested loop's inner ng-repeat from updating when the array undergoes changes

My current challenge involves working with an array of events, each event has teams participating in it. Although these objects are related, they are not properties of each other. I am attempting to loop through every event and display the teams participa ...

Utilizing the '::marker' pseudo-element for generating Markdown-inspired headers

This code snippet is functioning correctly, however, I have a suggestion to make it more appropriate. Instead of using '::before', why not try using '::marker'? I attempted this adjustment but encountered an issue. Can anyone explain wh ...

Loading modules conditionally in Nuxt.js

In my Nuxt.js configuration, I have included a module for Google Tag Manager like this: modules: [ [ '@nuxtjs/google-tag-manager', { id: 'GTM-XXXXXXX' } ] ] Everything is functioning properly, but I am curious ab ...

Step-by-step guide on fetching blog posts from a Ghost blog by utilizing the API in a Vue cli project

I'm currently working on my Vue cli project and I am trying to showcase all the posts from a Ghost blog using the API. Unfortunately, the example provided on the page is for a nuxt project. Once we have called the dependencies and authenticated with ...

Encountering [object, Object] while attempting to display JSON object retrieved from req.body in the console

While attempting to insert a product's details into my API's PostgreSQL database using Postman, I encountered an issue where the values of the specs key were displayed as [object Object] instead of showing the complete data. As a result, even in ...

React forms are experiencing issues with characters overlapping

Having trouble with overlapping label and input letters in my React form. Looking for: The appearance shown in the top image Experiencing: What is displayed in the bottom image Any solutions on how to resolve this issue? https://i.sstatic.net/Y3W2m.png ...

Using JQuery Ajax to post an array

I have searched extensively for solutions, but none seem to fit my situation. Currently, I am utilizing the Jquery-Plugin DataTable with multiple tables within a form. The exact number of tables is unknown. The challenge lies in retrieving form data from ...

To ensure secure access to a file, restrict it to only be accessed through Jquery Ajax requests

Hey guys, I've run into a little problem... I just finished creating two PHP files. CreateAdmin.php ----------> Contains a Form to Fill Out Save.php ----------------> Called using jQuery Ajax to insert data into the database. Everything seem ...

Is there a way to modify my code to eliminate the need for a script for each individual record?

Whenever I need to create a code with the ID by browsing through my records, is there a way to make just one function for all the records? $tbody .= '<script> $(document).ready(function(){ $("#img'.$idImage .'").click(functi ...

Transform a PDF document into a Google Doc utilizing the capabilities of the Google Drive API version 3

I successfully uploaded a PDF file to Google Drive using a node server. However, I am struggling to find a way to convert it to a Google Doc format so that it can be downloaded later as a DOCX document. Here is the code snippet I've been working with ...

Best practices for executing an asynchronous forEachOf function within a waterfall function

I've been working with the async library in express js and I'm encountering an issue when using two of the methods alongside callbacks. The variable result3 prints perfectly at the end of the waterfall within its scope. However, when attempting t ...

The tooltips in the WordPress-Gulp-Starter-Kit running on Bootstrap 5 do not seem to be functioning properly

I'm having trouble with tooltips not working properly. The codebase I'm using is from this repository https://github.com/oguilleux/webpack-gulp-wordpress-starter-theme If you need more details, feel free to reach out. Here is my main.js file: ...