jQuery addClass example
Change class name on click in jQuery
HTML
<button id="new_color">Try Random Color</button>
<p id="preview">Click the button!</p>
CSS
#preview {
display: block;
height: 40px;
line-height: 40px;
font-size: 20px;
vertical-align: middle;
width: 150px;
text-align: center;
}
JavaScript
const getRandNum = () => Math.floor(Math.random() * 256);
const get_random_color = () => (`rgb(${getRandNum()}, ${getRandNum()}, ${getRandNum()})`);
const checkColor = (color) => {
let clrarr = color.match(/\d+/g).map(num => +num);
// alert(clrarr);
if(clrarr[0] + clrarr[1] + clrarr[2] >= 255 * 3 / 2)
return true;
return false;
}
$('#new_color').click(function(){
const p = $('#preview');
const bg_color = get_random_color();
const color_is_light = checkColor( bg_color );
const text_color = color_is_light ? 'black' : 'white';
p.css({
color: text_color,
backgroundColor: bg_color
});
});