Change Text Color Based On Background Color Using Javascript

WebSolutionStuff | Dec-25-2020 | Categories : PHP jQuery CSS HTML

Hello Friends,

In this example we will see change text color based on background color using javascript, sometime we have requirments of change text or font color dependent on background color and at that time if you are changing text color manully then this post will definitely help you.

In this post i will show you how to change text color based on background color dynamically.

 

Create File And Add Below Code

 

<html> 
  
<head> 
    <title> 
        How to change text color depending  
      on background color using JavaScript
    </title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
    </script> 
    
</head> 
  
<body id="body" align="center" > 
    <h1 style="color:#03aa96;">   
            Websolutionstuff.com  
        </h1> 
    <p id="col_UP" style="font-size: 15px; font-weight: bold;"> </p> 
    <button onclick="col_Fun()">
        click here 
    </button> 
    <br> 
    <br> 
    <div id="backG">Welcome to websolutionstuff.</div> 
    
</body> 
  
</html>

 

 

Add CSS For Designing

 

#backG { 
    width: 200px; 
    height: 30px; 
    color: white; 
    background: #03aa96; 
    margin: 0 auto;
    padding-top:10px;
  } 

 

 

Add 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(); 
        }

 

Output : 

change_textcolor_based_on_background_color

 

Featured Post