![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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; }
Advertisements