Tips & Tricks

Generate Hex Code using JavaScript

Here is the quick tip in javascript. This will generate the hex code for you, using just one line of code.

First of all thanks to Paul Irish for such a great code which helps us to get the hex code using JavaScript.

Have a look at below code block for the same.

[cc lang=”javascript”]
“#”+Math.floor(Math.random()*16777215).toString(16)
[/cc]

Above line will return the a valid hex code for you.

Now suppose you want to change font color of any [code]p[/code] tag then you just need to use below code. First of all give that tag any unique ID and have a look at below code block.

[cc lang=”javascript”]
// Considering you have included the MooTools already
window.addEvent(‘domready’, function(){
(function(){
var color = ‘#’+Math.floor(Math.random()*16777215).toString(16);
$(“highlight”).setStyle(‘color’, color )}
).periodical(1000);

});
[/cc]

Have a look at this demo page which shows this trick in live mode.

Reference

Shares:
  • Peter
    February 16, 2012 at 1:15 pm

    For those who don’t know: ‘16777215’ is the total number of available colors and ‘.toString(16)’ converts the output to a hexadecimal base.

    Reply
  • Peter
    December 20, 2019 at 2:53 pm

    For those who don’t know: ‘16777215’ is the total number of available colors and ‘.toString(16)’ converts the output to a hexadecimal base.

    Reply
  • bhuumi
    February 26, 2012 at 11:34 pm

    its for any random color code. can i use for specific color code or specific color code range?

    Reply
    • Avinash
      February 27, 2012 at 9:32 am

      Well, if you want from specific color code then you can create array of codes and get random array value and for the specific range I will look into it and post it if there is any solution for this….

      Reply
  • bhuumi
    December 20, 2019 at 2:53 pm

    its for any random color code. can i use for specific color code or specific color code range?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *