In this tutorial, you will learn how to get the color code of the element by mouse click in JavaScript.
We can do it by some JavaScript method or function.
Get the color code of the element by mouse click in JavaScript.
let’s learn this with an explanation.
<script> document.addEventListener('DOMContentLoaded', function() { //rest of the code }) </script>
This ” document.addEventListener(‘DOMContentLoaded’, function() { “ function waits until the DOM/HTML page gets fully loaded, all the other functions of the code come under this function, so they get executed after the page loaded.
let move=document.querySelector('#move');
this line selects the html div element and assigns it to the verbal ‘move’.
let hexcolor=`#${Math.random().toString(16).slice(2,8).padEnd(6,0)}`
this part generate a random hexadecimal color code and assigns it to the variable ‘hexcolor’. it uses the ‘math.random()’ to generate a random number, and convert it to the hexadecimal string using ‘.toString(16)’ slices it to get the first 6 characters and pads it with zeros if necessary to make it’s 6 characters long.
bt.addEventListener('click',function(){ move.style.background=hexcolor; })
this line set the background color of the div element refence by the variable ‘move’ to the value stored in the ‘hexcolor’ variable.
Full JavaScript code is here.
<script> document.addEventListener('DOMContentLoaded', function() { let move=document.querySelector('#move'); let bt=document.querySelector('#bt'); let d=document.querySelectorAll('.d'); let hexcolor=`#${Math.random().toString(16).slice(2,8).padEnd(6,0)}` bt.addEventListener('click',function(){ move.style.background=hexcolor; d[1].innerHTML=hexcolor d.forEach(function(d){ d.style.color=hexcolor; }) }) }) </script>
Check it out here:
Click Here