
- HTML Tutorial
- HTML - Home
- HTML - Overview
- HTML - Basic Tags
- HTML - Elements
- HTML - Attributes
- HTML - Formatting
- HTML - Phrase Tags
- HTML - Meta Tags
- HTML - Comments
- HTML - Images
- HTML - Tables
- HTML - Lists
- HTML - Text Links
- HTML - Image Links
- HTML - Email Links
- HTML - Frames
- HTML - Iframes
- HTML - Blocks
- HTML - Backgrounds
- HTML - Colors
- HTML - Fonts
- HTML - Forms
- HTML - Embed Multimedia
- HTML - Marquees
- HTML - Header
- HTML - Style Sheet
- HTML - Javascript
- HTML - Layouts
- HTML References
- HTML - Tags Reference
- HTML - Attributes Reference
- HTML - Events Reference
- HTML - Fonts Reference
- HTML - ASCII Codes
- ASCII Table Lookup
- HTML - Color Names
- HTML - Entities
- HTML - Fonts Ref
- HTML - Events Ref
- MIME Media Types
- HTML - URL Encoding
- Language ISO Codes
- HTML - Character Encodings
- HTML - Deprecated Tags
Change text color based on a brightness of the covered background area in HTML?
It is possible to change the textcolour depending on the average brightness of the covered pixels ofits parent's background color by using the following code snippet.
var rgb = [255, 0, 0]; setInterval(display, 1000); function display() { rgb[0] = Math.round(Math.random() * 255); rgb[1] = Math.round(Math.random() * 255); rgb[2] = Math.round(Math.random() * 255); var d = Math.round(((parseInt(rgb[0]) * 299) + (parseInt(rgb[1]) * 587) + (parseInt(rgb[2]) * 114)) / 1000); // for foregound var f = (d> 125) ? 'black' : 'white'; // for background var b = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')'; $('#box').css('color', f); $('#box').css('background-color', b); } <scriptsrc = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div id = "box"> Demo</div>
The following is the CSS −
#box { width: 300px; height: 300px; }
- Related Articles
- How to change the Background Color of Text in C# Console
- How to change background color of canvas-type text using Fabric.js?
- How to change the text color of an element in HTML?
- How to change the background color of ListView items on Android?
- How to change background color of TableView items on iOS?
- Change the background color of a button with CSS
- How do you animate the change of background color of a view on iOS?
- How do you animate the change of background color of a view on Android?
- How to change the background color of ListView items on Android Kotlin?
- How to animate a change in background color using jQuery on mouseover?
- How to change background-color on a specific wider viewport in CSS ?
- How to change the background color of a Treeview in Tkinter?
- How to change the background color of ListView items on Android using Kotlin?
- Dynamically change the widget background color in Tkinter
- How to change value based on cell color in Excel?

Advertisements