--
Published on Sat, Nov-07-2009 by Dainis

20 Javascript codes to make your web design look excellent


Scripting language is of two types, client side scripting and server side scripting language. The difference between the client side scripting and server side scripting language is that client side scripting programs could be executed on any client computer and server scripting programs could be executed only on the server. Javascript and Vbscript are client side scripting languages.

You May Be Interested In The Following Posts


For example, if there is a contact form of the website with few fields. Email is one of the fields in that contact form so now if a user enters some number only or character only or email in invalid format and send to server then the server will have to process an email in invalid format. To process, the server will check and verify the format of the email and when it will find that email is in invalid format then it will tell back to client computer that the email is invalid format so enter the email in correct format. This was only one client computer that send the wrong data but when a website is running globally, there might be thousands of users logged on at the same time and what would be happen to server if all clients send wrong data at the same time. To prevent this mishappening, it would be better if the format of email is checked at the client computer only and if the email is in the correct format then only it is send to the server for processing.

Javascript is a popular scripting language and has been in use for many years. Days when flash was not popular and not used by many designers, Javascript was used to give nice effects to webpages. Javascript is still better than flash in minor designing needs because javascript pages are ranked better than flash pages in search engines. Some of the powerful features of this scripting language are described as below.

1. Nearly all browsers support javascript and you dont need to install any plugin to execute javscript codes whereas to run flash pages, flash plugin should be installed in your browser.

2. Javascript is same as any other functional programming language that can handle objects also. Variables could be declared and functions could be created. Property like inheritance of OOPS is also supported in Javascript but it is not same as inheritance in Java. Javascript programs be executed on both server and the client.

Javascript codes enhance your web design skills. Now to know more about javascript, learn these 20 Javascript codes to make your web design look excellent.

1. Javascript alerts

Javascript alerts are very important and used to display a message or warning to the user in a dialog box. Now see this code that will display an alert message on a webpage.

<script language=javascript>
alert(‘My name is John);
</script>

Copy this code and paste in notepad or any text editor and save it in .html format. As soon as you run this page, it will display a box with the message “My name is John ”. So using these lines, you can display any message. In this code, first line is used to open Javascript tag, last line is used to close Javascript tag and the middle line has alert function that is used to display any message in Javascript.

2. Opening New Window

A new window can be opened in any page using Javascript code. There are two ways to open a new page. A new page can be made to open by clicking a link or by clicking a button. Now see both these codes below.

<Script Language=”JavaScript”>
function load() {
var load=
window.open(‘http://www.webdesignerdepot.com’,”,’scrollbars=no,menubar=no,height=600,width=
800,resizable=yes,toolbar=no,location=no,status=no’);
}
// –>
</Script>
<a href=”javascript:load()”>Open Window</a>

Now in the above lines of code, the part of code in the script tag should be placed in the head section where as the last line should be copied in the body tag wherever you want to display the link. After clicking the link, it will open the site that is written in the window.open function.

<form>
<input type=”button” value=”Open Window”
onclick=”window.open(‘http://webdesignerdepot.com ‘)”>
</form>

The above lines of code can be placed anywhere in your html page wherever you want to display the link. Clicking the link will open the site that is written in window.open function.

3. Set as Users homepage

Many sites provide a button in their webpage and if you click on that button then that site will be set as your homepage that means whenever you open your browser that site will be opened automatically. You can also provide a button in your webpage that if clicked on the client computer then your site will be made as home page on the client computer. See these lines of code below.

<FORM>
<INPUT TYPE=”button” VALUE=”Make This Site Your Home Page”
onClick=”this.style.behavior=’url(#default#homepage)’; this.setHomePage(‘ http://webdesignerdepot.com’);”>
</FORM>

Copy this code and paste in your browser wherever you want to display the button.

4. Close Window

In many sites you must have seen that when you logout from your account then a message box is displayed asking to close the window and if you click “OK” then the browser is closed. This is done to avoid reuse of that window. You can do so in your website also just by placing one line code in your page wherever you want to display the message. See the line of code below.

<a href=”javascript: self.close()”>Close Window</a>

Self.close closes the window. One more function is used for the same purpose that is Window.close.

5. Statusbar Message

In some sites you must have seen some message displayed in statusbar. Its not a difficult job and you could also do this just by placing few lines of code in your html document. See the lines of code below.

<SCRIPT language=”JavaScript”>
var current = 0
var x = 0
var speed = 100
var speed2 = 100
function initArray(n) {
this.length = n;
for (var i =1; i <= n; i++) {
this[i] = ‘ ‘
}
}
typ = new initArray(4)
typ[0]=”My name is Nitesh.”
typ[1]=”I am a freelancer.”
typ[2]=”I am a programmer.”
typ[3]=”Article writing is my hobby.”
function typewrite() {
var m = typ[current]
window.status = m.substring(0, x++) + “”
if (x == m.length + 1) {
x = 0
current++
if (current > typ.length – 1) {
current = 0
}
setTimeout(“typewrite()”, speed2)
}
else {
setTimeout(“typewrite()”, speed)
}
}
typewrite()
// –>
</SCRIPT>

The above lines of code will display your desired message in status bar of your webpage.

6. Clock in Status bar

You can also display clock in status bar as you displayed message in the previous code. To do so use the lines of code written below.

<script Language=”JavaScript”>
var timerID = null;
var timerRunning = false;
function stopclock (){
if(timerRunning)
clearTimeout(timerID);
timerRunning = false;
}
function showtime () {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds()
var timeValue = “” + ((hours >12) ? hours -12 :hours)
timeValue += ((minutes < 10) ? “:0″ : “:”) + minutes
timeValue += ((seconds < 10) ? “:0″ : “:”) + seconds
timeValue += (hours >= 12) ? ” P.M.” : ” A.M.”
window.status = timeValue;
// you could replace the above with this
// and have a clock on the status bar:
//
timerID = setTimeout(“showtime()”,1000);
timerRunning = true;
}
function startclock () {
// Make sure the clock is stopped
stopclock();
showtime();
}
// –>
</script>

The above lines of code have initialized the clock in your webpage and now see this line.

<BODY onLoad=”startclock()”>

The function startclock() that is made in the above script can be added in the body tag of your page to display the clock in your status bar.

7. Clock in webpage

The above clock was displayed in the status bar only but we may also need to show the clock in webpage. To show the clock in webpage see the code below.

<script type=”text/javascript”>
var imageclock=new Object()
//Enter path to clock digit images here, in order of 0-9, then “am/pm”, then colon
image:
imageclock.digits=[“c0.gif”, “c1.gif”, “c2.gif”, “c3.gif”, “c4.gif”, “c5.gif”, “c6.gif”, “c7.gif”,
“c8.gif”, “c9.gif”, “cam.gif”, “cpm.gif”, “colon.gif”]
imageclock.instances=0
var preloadimages=[]
for (var i=0; i<imageclock.digits.length; i++){ //preload images
preloadimages[i]=new Image()
preloadimages[i].src=imageclock.digits[i]
}
imageclock.imageHTML=function(timestring){ //return timestring (ie: 1:56:38) into
string of images instead
var sections=timestring.split(“:”)
if (sections[0]==”0″) //If hour field is 0 (aka 12 AM)
sections[0]=”12″
else if (sections[0]>=13)
sections[0]=sections[0]-12+””
for (var i=0; i<sections.length; i++){
if (sections[i].length==1)
sections[i]=’<img src=”‘+imageclock.digits[0]+’” />’+’<img
src=”‘+imageclock.digits[parseInt(sections[i])]+’” />’
else
sections[i]=’<img
src=”‘+imageclock.digits[parseInt(sections[i].charAt(0))]+’” />’+’<img
src=”‘+imageclock.digits[parseInt(sections[i].charAt(1))]+’” />’
}
return sections[0]+’<img src=”‘+imageclock.digits[12]+’” />’+sections[1]+’<img
src=”‘+imageclock.digits[12]+’” />’+sections[2]
}
imageclock.display=function(){
var clockinstance=this
this.spanid=”clockspan”+(imageclock.instances++)
document.write(‘<span id=”‘+this.spanid+’”></span>’)
this.update()
setInterval(function(){clockinstance.update()}, 1000)
}
imageclock.display.prototype.update=function(){
var dateobj=new Date()
var
currenttime=dateobj.getHours()+”:”+dateobj.getMinutes()+”:”+dateobj.getSeconds() //create
time string
var currenttimeHTML=imageclock.imageHTML(currenttime)+’<img
src=”‘+((dateobj.getHours()>=12)? imageclock.digits[11] : imageclock.digits[10])+’” />’
document.getElementById(this.spanid).innerHTML=currenttimeHTML
}
</script>

Now write the above code within the head tag of your html document. This code will need 13 gif images. 10 images are used to display the numbers from 0 to 9, 2 images are used to display the time in AM and PM and the remaining image is used to display the colon between hours, minutes and seconds. You can design the gif images yourself simply in paint or advanced images in Photoshop if you know to use photoshop. The names of images should start from c0 to c9 for the numbers, cam for AM, cpm, for PM and colon for writing colon. Remember if you are giving different names to your images then you should change the name of images in “imageclock.digits” in the code also to display the images. Now after this see this code below.

<script type=”text/javascript”>
new imageclock.display()
</script>

Now write the above three lines of code in your body tag anywhere you want to display the clock.

8. Protect Content

Sometimes you need to protect the content of your site from copying. Matrimonial sites such as Jeevansathi.com used to protect the images of their profiles from being copied. You can also do so by using just few lines of code.

<SCRIPT language=”JavaScript”>
var message=”Copyright 2009 to www.allaboutwebsite.com. WARNING! All content contained
within this site is protected by copyright laws. “;
function click(e) {
if (document.all) {
if (event.button==2||event.button==3) {
alert(message);
return false;
}
}
if (document.layers) {
if (e.which == 3) {
alert(message);
return false;
}
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;
// –>
</SCRIPT>

Now the above code will protect the text or images from being copied. This method prevents the right click on your webpage and if someone right clicks, then the warning written in variable “message” is displayed in a dialog box. Though this method prevents right click but this is not a full secure method because more experienced users can copy the content either by taking
screenshots or by opening view source.

9. Protect page by Password

The above method can be used only for beginners but cannot stop experienced users so to stop experienced you can protect a page by password. See these lines of code below.

<SCRIPT language=”JavaScript”><!–
var statusMsg = “Password Protected Area”
function gateKeeper() {
var password = prompt(“Password required:”, “”);
this.location.href = password + “.htm”;
}
</SCRIPT>

Place the above lines of code within the head section of your html document. Then see more lines of code below.

<A HREF=”javascript:gateKeeper()”
onMouseOver=”self.status=statusMsg; return true”
onMouseOut=”self.status=”; return true”
onClick=”gateKeeper(); return false”>Open my Home page</A>

Now place the above four lines of code in body tag of your html document. If the user will click on the link “Open my Home page”, then the password prompt will be displayed. Now entering the password correctly the user will be redirected to the password.htm page and on your password.htm page you can open your home page in header.

10. Close Alert

You can also place close alert on your page. It means that when you close your page then you get close message such as “Good bye”. Read the code below.

<BODY onUnload=”window.alert(‘ Good Bye ‘)”>
</BODY>

Place this code in your HTML page and a dialog box saying “Good Bye” will be displayed when you close the webpage. The message displayed is written in window.alert function.

11. Checking if compulsory field is filled or not

You must have registered in many sites or created email in hotmail, yahoo etc and you must have noticed that registration forms of such sites have some compulsory fields. The compulsory fields are necessary to be filled but what if someone try to register without filling compulsory fields. So there must be some procedure or mechanism to check the compulsory fields of such forms. Javascript provides the facility to write such codes. Read the code below.

<script language=javascript>
function fun(){
if(document.form1.name.value==”){
alert(‘[Please enter your Name]‘);
document.form1.name.focus();
return false;
}
}
</script>

The above code should be written in the head section of your HTML page. This code checks if the value of the variable name initialized in the form is empty or not. If the variable “name” doesn’t have any value then on clicking the submit button, the error message “Please enter your Name” is displayed and if the value of this variable is not empty then the click on the submit will take you to the next page. Now read this code for the body section.

<form method=”POST” name=”form1″ action=”registrationprocess.php” script
language=”javascript” onsubmit=”return fun();”>
<tr>
<td align=”right” width=”265″><b><span class=”form_required”>Name:</span></b></td>
<td width=”401″>
<input maxLength=”50″ name=”name” size=”35″></td>
</tr>
</form

The above code should be there in the body section of your HTML page. onsubmit=”return fun();” -> This line in the form tag tells the browser that the function named “fun” will be called from the above javascript code. The name of the field in the form part of body section should be same as the name of the field written in the fun function. The name of the form should also be same at both places. In the above code, the name of the form is “form1” at both places. Finally on the execution of this code, if the user try to submit the registration details without filling anything in the textbox named “name” then a dialog box will be displayed asking the user to fill the name in the name field.

12. Matching the value of password and confirm password

Apart from checking the value of compulsory fields, sometimes you may also need to confirm that the value of two fields is same or not. Read the code below.

<script language=javascript>
function fun(){
if(document.form1.password.value!=document.form1.confirmpassword.value){
alert(‘[Please enter same Password]‘);
document.form1.email.focus();
return false;
}
}
</script>

This code will check if the value of password and confirm password is same or not. If the value of password and confirm password is unequal then the error message “Please enter same Password” is displayed and if the value of both fields is same then on clicking the submit button you are taken on to the next page. The name of both these fields should be same in the form part of the body section of your HTML document.

13. Checking the status of checkbox of page

In the registration form of many sites, there is a checkbox in the last of page before the submit button with the message “Select the checkbox if you agree with the terms and conditions” and user is able to proceed to the next page only after checking this checkbox. You can do this in your page also just by placing few lines of checkbox. Read the code below for checking the status of checkbox.

<script language=javascript>
function fun(){
if(document.form1.terms.checked==false){
alert(‘[You must agree with our terms and conditions]‘);
document.form1.terms.focus();
return false;
}
}
</script>

Now the code above checks the status of checkbox but the name of the checkbox should be “terms” in the form part of the body section of your HTML document. If the checkbox is checked then only the next page will be called otherwise the error message will be displayed.

14. Checking the value of Email field

In all the registration forms, there is a field email and user may enter wrong value or value in the wrong format in this field. Checking the value of email in the correct format is not an easy task as it was in earlier case because here number of cases are need to be considered. Read the code below.

<script language=javascript>
function fun(){
var at=”@”
var dot=”.”
var lat=document.form1.email.value.indexOf(at)
var lstr=document.form1.email.value.length
var ldot=document.form1.email.value.indexOf(dot)
if (document.form1.email.value.indexOf(at)==-1){
alert(“Please enter a proper email address\neg. abc@hotmail.com.”)
document.form1.email.focus();
return false;
}
if(document.form1.email.value.indexOf(at)==-1 || document.form1.email.value.indexOf(at)==0
|| document.form1.email.value.indexOf(at)==lstr){
alert(“Please enter a proper email address\neg. abc@hotmail.com.”)
document.form1.email.focus();
return false;
}
if(document.form1.email.value.indexOf(dot)==-1 ||
document.form1.email.value.indexOf(dot)==0 ||
document.form1.email.value.indexOf(dot)==lstr){
alert(“Please enter a proper email address\neg. abc@hotmail.com.”)
document.form1.email.focus();
return false;
}
if(document.form1.email.value.indexOf(at,(lat+1))!=-1){
alert(“Please enter a proper email address\neg. abc@hotmail.com.”)
document.form1.email.focus();
return false;
}
if(document.form1.email.value.substring(lat-1,lat)==dot ||
document.form1.email.value.substring(lat+1,lat+2)==dot){
alert(“Please enter a proper email address\neg. abc@hotmail.com.”)
document.form1.email.focus();
return false;
}
if(document.form1.email.value.indexOf(dot,(lat+2))==-1){
alert(“Please enter a proper email address\neg. abc@hotmail.com.”)
document.form1.email.focus();
return false;
}
if(document.form1.email.value.indexOf(” “)!=-1){
alert(“Please enter a proper email address\neg. abc@hotmail.com.”)
document.form1.email.focus();
return false;
}
}
</script>

All the conditions of the above code when satisfied then only the value of email is in the correct format otherwise the error message is displayed. Remember the name of email field in the form should be “email” in the body section of your HTML document.

15. Mouseover Function

Mouseover function can give better look to your webpage in terms ofinstructions or other message. The message or instructions can be shown when the mouse is over the links or button. Read the code below.

<a href=”” onMouseOver=”alert(‘My name is Nitesh’);return true;”>Mouseover Function</a>
In the above code, when you take your mouse over the link “Mouseover Function”, the message
“My name is John ” is displayed.
16. Raining Effect: You can also give raining effect on your webpage. Read the code below.
<SCRIPT LANGUAGE=”JavaScript”>
<!– Begin
var no = 50;
var speed = 1;
var ns4up = (document.layers) ? 1 : 0;
var ie4up = (document.all) ? 1 : 0;
var s, x, y, sn, cs;
var a, r, cx, cy;
var i, doc_width = 800, doc_height = 600;
if (ns4up) {
doc_width = self.innerWidth;
doc_height = self.innerHeight;
}
else
if (ie4up) {
doc_width = document.body.clientWidth;
doc_height = document.body.clientHeight;
}
x = new Array();
y = new Array();
r = new Array();
cx = new Array();
cy = new Array();
s = 8;
for (i = 0; i < no; ++ i) {
initRain();
if (ns4up) {
if (i == 0) {
document.write(“<layer name=\”dot”+ i +”\” left=\”1\” “);
document.write(“top=\”1\” visibility=\”show\”><font color=\”blue\”>”);
document.write(“,</font></layer>”);
}
else {
document.write(“<layer name=\”dot”+ i +”\” left=\”1\” “);
document.write(“top=\”1\” visibility=\”show\”><font color=\”blue\”>”);
document.write(“,</font></layer>”);
}
}
else
if (ie4up) {
if (i == 0) {
document.write(“<div id=\”dot”+ i +”\” style=\”POSITION: “);
document.write(“absolute; Z-INDEX: “+ i +”; VISIBILITY: “);
document.write(“visible; TOP: 15px; LEFT: 15px;\”><font color=\”blue\”>”);
document.write(“,</font></div>”);
}
else {
document.write(“<div id=\”dot”+ i +”\” style=\”POSITION: “);
document.write(“absolute; Z-INDEX: “+ i +”; VISIBILITY: “);
document.write(“visible; TOP: 15px; LEFT: 15px;\”><font color=\”blue\”>”);
document.write(“,</font></div>”);
}
}
}
function initRain() {
a = 6;
r[i] = 1;
sn = Math.sin(a);
cs = Math.cos(a);
cx[i] = Math.random() * doc_width + 1;
cy[i] = Math.random() * doc_height + 1;
x[i] = r[i] * sn + cx[i];
y[i] = cy[i];
}
function makeRain() {
r[i] = 1;
cx[i] = Math.random() * doc_width + 1;
cy[i] = 1;
x[i] = r[i] * sn + cx[i];
y[i] = r[i] * cs + cy[i];
}
function updateRain() {
r[i] += s;
x[i] = r[i] * sn + cx[i];
y[i] = r[i] * cs + cy[i];
}
function raindropNS() {
for (i = 0; i < no; ++ i) {
updateRain();
if ((x[i] <= 1) || (x[i] >= (doc_width – 20)) || (y[i] >= (doc_height – 20))) {
makeRain();
doc_width = self.innerWidth;
doc_height = self.innerHeight;
}
document.layers["dot"+i].top = y[i];
document.layers["dot"+i].left = x[i];
}
setTimeout(“raindropNS()”, speed);
}
function raindropIE() {
for (i = 0; i < no; ++ i) {
updateRain();
if ((x[i] <= 1) || (x[i] >= (doc_width – 20)) || (y[i] >= (doc_height – 20))) {
makeRain();
doc_width = document.body.clientWidth;
doc_height = document.body.clientHeight;
}
document.all["dot"+i].style.pixelTop = y[i];
document.all["dot"+i].style.pixelLeft = x[i];
}
setTimeout(“raindropIE()”, speed);
}
if (ns4up) {
raindropNS();
}
else
if (ie4up) {
raindropIE();
}
// End –>
</script>
</body>
<font face=”Tahoma”><a target=”_blank” href=”http://www.allaboutwebsite.com/”><span
style=”font-size: 8pt; text-decoration: none”>Allaboutwebsite Services</span></a></font>

The above code in the body section of your HTML document will give raining effect to your webpage.

17. Stars Moving

If you want to show stars moving in the background of your webpage then you can give this effect using the following code.

<FONT face=Tahoma color=white>
<body>
<BODY BGCOLOR=”#000000″ onLoad=”fly()”>
<SCRIPT LANGUAGE=”JavaScript”>
SmallStars = 30;
LargeStars = 10;
SmallYpos = new Array();
SmallXpos = new Array();
LargeYpos = new Array();
LargeXpos = new Array();
Smallspeed= new Array();
Largespeed= new Array();
ns=(document.layers)?1:0;
if (ns) {
for (i = 0; i < SmallStars; i++) {
document.write(“<LAYER NAME=’sn”+i+”‘ LEFT=0 TOP=0 BGCOLOR=’#FFFFF0′
CLIP=’0,0,1,1′></LAYER>”);
}
for (i = 0; i < LargeStars; i++) {
document.write(“<LAYER NAME=’ln”+i+”‘ LEFT=0 TOP=0 BGCOLOR=’#FFFFFF’
CLIP=’0,0,2,2′></LAYER>”);
}
}
else {
document.write(‘<div style=”position:absolute;top:0px;left:0px”>’);
document.write(‘<div style=”position:relative”>’);
for (i = 0; i < SmallStars; i++) {
document.write(‘<div id=”si”
style=”position:absolute;top:0;left:0;width:1px;height:1px;background:#fffff0;fontsize:
1px”></div>’);
}
document.write(‘</div>’);
document.write(‘</div>’);
document.write(‘<div style=”position:absolute;top:0px;left:0px”>’);
document.write(‘<div style=”position:relative”>’);
for (i = 0; i < LargeStars; i++) {
document.write(‘<div id=”li”
style=”position:absolute;top:0;left:0;width:2px;height:2px;background:#ffffff;fontsize:
2px”></div>’);
}
document.write(‘</div>’);
document.write(‘</div>’);
}
WinHeight = (document.layers)?window.innerHeight:window.document.body.clientHeight;
WinWidth = (document.layers)?window.innerWidth:window.document.body.clientWidth;
for (i = 0; i < SmallStars; i++) {
SmallYpos[i] = Math.round(Math.random() * WinHeight);
SmallXpos[i] = Math.round(Math.random() * WinWidth);
Smallspeed[i]= Math.random() * 5 + 1;
}
for (i = 0; i < LargeStars; i++) {
LargeYpos[i] = Math.round(Math.random() * WinHeight);
LargeXpos[i] = Math.round(Math.random() * WinWidth);
Largespeed[i] = Math.random() * 10 + 5;
}
function fly() {
var WinHeight = (document.layers)?window.innerHeight:window.document.body.clientHeight;
var WinWidth = (document.layers)?window.innerWidth:window.document.body.clientWidth;
var hscrll = (document.layers)?window.pageYOffset:document.body.scrollTop;
var wscrll = (document.layers)?window.pageXOffset:document.body.scrollLeft;
for (i = 0; i < LargeStars; i++) {
LargeXpos[i] -= Largespeed[i];
if (LargeXpos[i] < -10) {
LargeXpos[i] = WinWidth;
LargeYpos[i] = Math.round(Math.random() * WinHeight);
Largespeed[i] = Math.random() * 10 + 5;
}
if (ns) {
document.layers['ln'+i].left = LargeXpos[i];
document.layers['ln'+i].top = LargeYpos[i] + hscrll;
}
else {
li[i].style.pixelLeft = LargeXpos[i];
li[i].style.pixelTop = LargeYpos[i] + hscrll;
}
}
for (i = 0; i < SmallStars; i++) {
SmallXpos[i] -= Smallspeed[i];
if (SmallXpos[i] < -10) {
SmallXpos[i] = WinWidth;
SmallYpos[i] = Math.round(Math.random()*WinHeight);
Smallspeed[i] = Math.random() * 5 + 1;
}
if (ns) {
document.layers['sn'+i].left = SmallXpos[i];
document.layers['sn'+i].top = SmallYpos[i]+hscrll;
}
else {
si[i].style.pixelLeft = SmallXpos[i];
si[i].style.pixelTop = SmallYpos[i]+hscrll;
}
}
setTimeout(‘fly()’, 10);
}
// End –>
</script>
<!– Script Size: 3.79 KB –>
</body>
</html>

The above javascript code will give the effect of moving stars in thebackground of your webpage as shown in the figure below.

18. Stars falling

In the previous code, you gave the effect of stars moving but in this code you can also give the effect of stars falling in your webpage. Read the code below.

<script>
// Set the number of snowflakes (more than 30 – 40 not recommended)
var snowmax=35
// Set the colors for the snow. Add as many colors as you like
var snowcolor=new Array(“#aaaacc”,”#ddddFF”,”#ccccDD”)
// Set the fonts, that create the snowflakes. Add as many fonts as you like
var snowtype=new Array(“Arial Black”,”Arial Narrow”,”Times”,”Comic Sans MS”)
// Set the letter that creates your snowflake (recommended:*)
var snowletter=”*”
// Set the speed of sinking (recommended values range from 0.3 to 2)
var sinkspeed=0.6
// Set the maximal-size of your snowflaxes
var snowmaxsize=22
// Set the minimal-size of your snowflaxes
var snowminsize=8
// Set the snowing-zone
// Set 1 for all-over-snowing, set 2 for left-side-snowing
// Set 3 for center-snowing, set 4 for right-side-snowing
var snowingzone=3
///////////////////////////////////////////////////////////////////////////
// CONFIGURATION ENDS HERE
///////////////////////////////////////////////////////////////////////////
// Do not edit below this line
var snow=new Array()
var marginbottom
var marginright
var timer
var i_snow=0
var x_mv=new Array();
var crds=new Array();
var lftrght=new Array();
var browserinfos=navigator.userAgent
var ie5=document.all&&document.getElementById&&!browserinfos.match(/Opera/)
var ns6=document.getElementById&&!document.all
var opera=browserinfos.match(/Opera/)
var browserok=ie5||ns6||opera
function randommaker(range) {
rand=Math.floor(range*Math.random())
return rand
}
function initsnow() {
if (ie5 || opera) {
marginbottom = document.body.clientHeight
marginright = document.body.clientWidth
}
else if (ns6) {
marginbottom = window.innerHeight
marginright = window.innerWidth
}
var snowsizerange=snowmaxsize-snowminsize
for (i=0;i<=snowmax;i++) {
crds[i] = 0;
lftrght[i] = Math.random()*15;
x_mv[i] = 0.03 + Math.random()/10;
snow[i]=document.getElementById(“s”+i)
snow[i].style.fontFamily=snowtype[randommaker(snowtype.length)]
snow[i].size=randommaker(snowsizerange)+snowminsize
snow[i].style.fontSize=snow[i].size
snow[i].style.color=snowcolor[randommaker(snowcolor.length)]
snow[i].sink=sinkspeed*snow[i].size/5
if (snowingzone==1) {snow[i].posx=randommaker(marginright-snow[i].size)}
if (snowingzone==2) {snow[i].posx=randommaker(marginright/2-snow[i].size)}
if (snowingzone==3) {snow[i].posx=randommaker(marginright/2-
snow[i].size)+marginright/4}
if (snowingzone==4) {snow[i].posx=randommaker(marginright/2-
snow[i].size)+marginright/2}
snow[i].posy=randommaker(2*marginbottom-marginbottom-2*snow[i].size)
snow[i].style.left=snow[i].posx
snow[i].style.top=snow[i].posy
}
movesnow()
}
function movesnow() {
for (i=0;i<=snowmax;i++) {
crds[i] += x_mv[i];
snow[i].posy+=snow[i].sink
snow[i].style.left=snow[i].posx+lftrght[i]*Math.sin(crds[i]);
snow[i].style.top=snow[i].posy
if (snow[i].posy>=marginbottom-2*snow[i].size ||
parseInt(snow[i].style.left)>(marginright-3*lftrght[i])){
if (snowingzone==1) {snow[i].posx=randommaker(marginrightsnow[
i].size)}
if (snowingzone==2) {snow[i].posx=randommaker(marginright/2-
snow[i].size)}
if (snowingzone==3) {snow[i].posx=randommaker(marginright/2-
snow[i].size)+marginright/4}
if (snowingzone==4) {snow[i].posx=randommaker(marginright/2-
snow[i].size)+marginright/2}
snow[i].posy=0
}
}
var timer=setTimeout(“movesnow()”,50)
}
for (i=0;i<=snowmax;i++) {
document.write(“<span id=’s”+i+”‘ style=’position:absolute;top:-
“+snowmaxsize+”‘>”+snowletter+”</span>”)
}
if (browserok) {
window.onload=initsnow
}
</script>

The above code has required comments placed at the required lines to understand. This code when placed in the HTML document give the effect of stars falling in your webpage.

19. Always Changing Background Color

If you want the background of your page to change its color everytime then you can do this in Javascript. Read the code below.

<html>
<head>
<script>
function initArray()
{
this.length = initArray.arguments.length
for (var i = 0; i < this.length; i++)
this[i+1] = initArray.arguments[i]
}
var hexChars = “0123456789ABCDEF”;
function Dec2Hex (Dec)
{
var a = Dec % 16;
var b = (Dec – a)/16;
hex = “” + hexChars.charAt(b) + hexChars.charAt(a);
return hex;
}
function bgChanger (begin, end, steps)
{
steps = steps -1 ;
redA = begin.charAt(0) + begin.charAt(1);
red_valA = parseInt(redA,’16′);
redB = end.charAt(0) + end.charAt(1);
red_valB = parseInt(redB,’16′);
red_int = ((red_valB – red_valA) / steps) * -1;
grnA = begin.charAt(2) + begin.charAt(3);
grn_valA = parseInt(grnA,’16′);
grnB = end.charAt(2) + end.charAt(3);
grn_valB = parseInt(grnB,’16′);
grn_int = ((grn_valB – grn_valA) / steps) * -1;
bluA = begin.charAt(4) + begin.charAt(5);
blu_valA = parseInt(bluA,’16′);
bluB = end.charAt(4) + end.charAt(5);
blu_valB = parseInt(bluB,’16′);
blu_int = ((blu_valB – blu_valA) / steps) * -1;
step = 2;
red = red_valA;
grn = grn_valA;
blu = blu_valA;
document.bgColor = begin;
while ( steps >= step )
{
red -= red_int;
red_round = Math.round(red);
red_hex = Dec2Hex(red);
grn -= grn_int;
grn_round = Math.round(grn);
grn_hex = Dec2Hex(grn);
blu -= blu_int;
blu_round = Math.round(blu);
blu_hex = Dec2Hex(blu);
document.bgColor = red_hex + grn_hex + blu_hex;
step++;
}
document.bgColor = end;
}
</script>
</head>
<body bgcolor=#000000 text=#FFFFFF link=”FF0000″ vlink=”8888FF” alink=”FF00FF”>
<script>
<!–
// black to black (pause)
i=1;
while(i<=10)
{
bgChanger(“000000″,”000000″,25);
// black to red
bgChanger(“000000″,”FF0000″,25);
// red to black
bgChanger(“FF0000″,”000000″,25);
// black to purple
bgChanger(“000000″,”AA00EE”,25);
// purple to black
bgChanger(“AA00EE”,”000000″,25);
// black to blue
bgChanger(“000000″,”0000FF”,25);
// blue to black
bgChanger(“0000FF”,”000000″,25);
// black to black (pause)
bgChanger(“000000″,”000000″,25);
i=i+1;
}
// –>
</script>
</head>
<body>
<BODY BGCOLOR=000000 text=”#ffffff” link=”#0000ff” vlink=”#c00c0″>

In the above code, the function bgchanger is used to change the background color of page. This function is repeatedly called here in repeated loops to give the effect of background changing its color always

Advertisement


Leave Your Response

About PsDeluxe

Psdeluxe is a Design blog dedicated to mainly Photoshop lovers and enthusiasts. We regularly update blog with free and easy to learn free Adobe photoshop tutorials, useful freebies for design projects, powerful tools that will make your work easier and we publish showcase of most beautiful and interesting designers works around the work that hopefully will inspire. Learn Adobe Photoshop techniques with us. Talented and professional designers are always welcome to join our author team. Feel free to subscribe to our Rss feed to be first who get all valuable information for designers.



     Hostgator Coupons | ThemeLabs | MaxReview theme | Review themes

Recommended Links



Wordpress review theme