How to set a random colour using jQuery and JavaScript

The following script (jQuery and JavaScript) shows how to set a random colour on elements – in this case, a background colour in inputs.

function set_input_random_colour() {
var random_colour =  'rgb('+ (Math.floor(Math.random() * 256)) + ','+ (Math.floor(Math.random() * 256)) + ','+ (Math.floor(Math.random() * 256)) + ')';
jQuery( '.entry-content' ).find( 'input[type=text]' ).each(function() {
  var input = jQuery( this );
  input.css( 'background', random_colour );
});
}
jQuery(document).ready( function($) {
set_input_random_colour();
});

How is the random colour generated?

The variable random_colour uses the Math object to pick three random values between 0 and 256, these values are combined as a string to form a RGB colour value.

Math.random gives a random number between 0 – 1, e.g. 0.6288472721544226 – we then times it by 255 + 1 (hence the 256) which would give us 160.98490167153219 then Math.floor is used to remove any decimal places, e.g. 160.

How can this script be used?

I use random colours on elements when debuging and optimising JavaScript scripts – with it I am able to confirm the elements that are selected, make sure only the nesecary elements are selected and check that the script does not run more times than nesecary.

Demo






Was this article helpful?

Related Articles