Hi Developers,
Lets see How to Change Text Color Based On Background Color Using Javascript
Create an HTML file and the below code in your file,
<html>
<head>
<title>Change Text Color Based On Background Color Using Javascript
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<style>
#backG {
width: 200px;
color: white;
background: #000;
margin: 0 auto;
padding:10px;
border-radius:5px;
}
</style>
</head>
<body id="body" align="center">
<h1 style="margin-top:20px;margin-bottom:20px;font-size:18px;">
<b>Change Text Color Based On Background Color Using Javascript - ITSolutionsGuides</b>
</h1>
<p id="col_UP" style="font-size: 15px; font-weight: bold;"> </p>
<button onclick="col_Fun()" style="padding:10px;">
click here
</button>
<br>
<br>
<div id="backG">Hello World</div>
</body>
</html>
Add the javascript code
var el_up = document.getElementById('col_UP');
var rgbValue = [255, 0, 0];
function setColor() {
rgbValue[0] = Math.round(Math.random() * 255);
rgbValue[1] = Math.round(Math.random() * 255);
rgbValue[2] = Math.round(Math.random() * 255);
var color = Math.round(((parseInt(rgbValue[0]) * 299) +
(parseInt(rgbValue[1]) * 587) +
(parseInt(rgbValue[2]) * 114)) / 1000);
var textColor = (color > 125) ? 'black' : 'white';
var backColor =
'rgb(' + rgbValue[0] + ', ' + rgbValue[1] + ', '
+ rgbValue[2] + ')';
$('#backG').css('color', textColor);
$('#backG').css('background-color', backColor);
}
function col_Fun() {
setColor();
}
We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.
Be the first to know about releases and tutorial news and solutions.
We care about your data in our privacy policy.
ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.
Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides