Dynamically Change Font Color Based On Background – Contrast.js

Category: Color , Javascript | July 30, 2020
Author:MishaPetrov
Views Total:4,067 views
Official Page:Go to website
Last Update:July 30, 2020
License:MIT

Preview:

Dynamically Change Font Color Based On Background – Contrast.js

Description:

Contrast.js is pure JavaScript color manipulation library that makes it possible to dynamically change the font color based on the page or element background – including responsive background image.

You can also set bw value to true like invertColor(hex, true) and in this case the font color will switch between black/white or any color pair you set based on the background behind the target element.

See Also:

How to use it:

1. Install & Import.

# NPM
$ npm i contrast-js --save
const Contrast = require('contrast-js');

2. Or download the package and insert the Contrast.js script into the document.

<script src="./contrast.min.js"></script>

3. Add the contrast-el class to the text element.

<h1 class="contrast-el">Element</h1>

4. Add the contrast-bg class to the parent container.

<section class="contrast-bg">
  <h1 class="contrast-el">Element</h1>
</section>

5. Initialize the Contrast.js and done.

let contrast = new Contrast();
contrast.launch();

6. All default options.

let contrast = new Contrast({

  // Set to true if you want to prebuild light/dark colors
  isCustomColors: false,

  // dark color HEX if isCustomColors is set to true
  customLight: "#bddfe0",   

  // light color HEX if isCustomColors is set to true
  customDark: "#334054",    

  // "cover" or "100%" based on the background-size property in css
  backgroundSize: "cover",  

  // Option to rename the class for the element containing bg image
  bgClass: "contrast-bg",   

  // Option to rename the class for the target element
  elementClass: "contrast-el",   

  // Set to true if the element is a div (to change it's background)
  isDiv: false,             

  // Turn this so the module runs on window resize
  isResponsive: true        
  
});

You Might Be Interested In:


2 thoughts on “Dynamically Change Font Color Based On Background – Contrast.js

  1. David

    Trying to figure out how to get this to work with a menu fixed over an image background as you scroll down the image. We are testing things on a sandbox website.

    Reply
  2. Clark

    How to modify this to work with addEventListener(“scroll,function() Do not need it for “resize” but for scrolling on a background image.

    Can anyone help with this.

    Reply

Leave a Reply