top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Generate Random Colors in JavaScript

+4 votes
360 views

Introduction

Here I will explain how to generate random colors for div using JavaScript and change color of div at regular intervals of time using JavaScript.

 

Description   
I will explain how to generate random colors for div using JavaScript

To implement this we need to write the code like as shown below

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Generate Random Colors using javascript</title>

<script type="text/javascript">

 

// Run function for every second of timer

setInterval(rgbcolors, 1000);

 

function rgbcolors() {

// rgb string generation

var col = "rgb("

+ Math.floor(Math.random() * 255) + ","

+ Math.floor(Math.random() * 255) + ","

+ Math.floor(Math.random() * 255) + ")";

//change the text color with the new random color

document.getElementById("divstyle").style.color = col;

}

</script>

 

</head>Sample Program

<body>

<form id="form1" runat="server" >

<div id="divstyle" style="font:bold 24px verdana">tech.queryhome.com</div>

</form>

</body>

</html>

posted Jan 6, 2016 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Introduction

In an application I required to generate some random colors. Writing these colors manually was not easy. So I decided to use .NET Reflection to generate colors usingSystem.Drawing.Color class

Description

We can use GetProperties method of Type class to get all the properties of Color class. It returns an array of PropertyInfo class. Follow these steps to create a RandomColor class to return a random color using NextColor method

Step:1 Write following code to create a RandomColor class after addingSystem.Reflection namespace

RandomColors Class c

In this class, first all the properties of Color are retrieved in a PropertyInfo array.NextColor method picks a random property from PropertyInfo array and returns it after converting it to the Color type.

Step:2 To use this RandomColor class, create a new Windows Forms Application and write following in its load event

RandomColors - Microsoft Visual Studio_2013-01-31_23-32-13

Here it adds 100 Labels in the form with random background color. Of course you need to write RandomColor class in the same namespace as the Form1 class

Form1 will look like following

RandomColors

Thanks for reading!

READ MORE
...