JavaScript …..What’s Next
Submit all answers to the sections.
Variables
If you need to save something in memory or you want to use a variable for a value that varies (thus creating a generalizing usage),
you need to use a variable.
var or not to var that is the question….
You don’t need to use the var before a variable declaration.
var x=9; //creates an number variable called x
name= “Margaret”; //creates a string variable called name
Valid variable names
my_name
invoice2
_total
Average
Invalid variable names
100_numbers(name starts with a numeral)
rate%_of_inflation(non legal character)
Data types
· Number: an integer or a floating-point number.
· String: Consists of alphabet, numerals or any other characters (even escape characters).
· Boolean: A logical true or false value.
· Null: Consists of a value, null.
· Undefined: Consists of a value, undefined.
Numbers as data types
A number data type can be an integer or a floating-point.
Some integer values
4
123
50
72
Some floating-point values
10.34
-467.234
90.00
0.006
3.0e10
6.023e-23
34e1
String Data Types
Any character or string or characters enclosed in double or single quotes is a string data type.
"www.webdevelopersnotes.com"
''
"Hello\nWorld"
"Gone in 60 seconds"
"12345678"
External Files
You can specify save JavaScript in a file and pull it into use by a webpage by…
<script language=”JavaScript” src="xxx.js">
</script>
Pop-up Boxes
· alert
alert("I am an alert box!!");
alert("Hello \n again!”);
· confirm
var r=confirm("Press a button");
if (r==true)
{ document.write("You pressed OK!"); }
else
{ document.write("You pressed Cancel!"); }
· prompt
var name=prompt("Please enter your name","Harry Potter");
if (name!=null name != "")
{ document.write("Hello " + name + "! How are you today?"); }
(#1 Name: alert/confirm/prompt)
1. Put each of the above scripts in a JS file. Try each in a webpage executing each by pressing a button. Print the JS file and the webpage.
2. In comments in the webpage near the appropriate code… What type of variable is “r” and “name” from above examples?
Opening a new window through a function
<SCRIPT LANGUAGE="JavaScript"
<!--
function open_win()
{
window.open('welcome.html','welcome',
'width=300,height=200,menubar=yes,status=yes,location=yes,toolbar=yes,scollbars=yes');
}
//-->
</SCRIPT>
<A HREF="javascript:void(0)" onclick="open_win()">
Get a welcome message</A>
Really appreciating functions
What if you had ten links on a page each opening a new 400X200 pixel window with a different url? Writing separate code for each link can become quite a pain. A simple solution would be to create a function that opens the new window and call it through an event handler. However, we are still left with a problem! How do we instruct the same function to load a different url in each new window?
(#2 Name: Open_win)
1. Write open_win function that opens the url that is passed in.
2. Create a webpage that opens up three different webpage using buttons and and the open_win function from above.
Date and Time in JavaScript
The date object is very useful for obtaining the date and time on the client. It supports various methods, which return a specific value.
To start working with dates and time, we first initialize a variable and assign it a value with the new operator and the Date() constructor. The main function of the new operator with Date() constructor is to create a new date object that is stored in the variable. Here is the code:
var d = new Date();
Thus, variable d contains a new date object. We can now call the various methods of this date object.
var t_date = d.getDate(); // Returns the day of the month
var t_mon = d.getMonth(); // Returns the month as a digit
var t_year = d.getFullYear(); // Returns 4 digit year
var t_hour = d.getHours(); // Returns hours
var t_min = d.getMinutes(); // Returns minutes
var t_sec = d.getSeconds(); // Returns seconds
var t_mil = d.getMilliseconds; // Returns Milliseconds
(#3 Name: Date and Time)
1. Now display the date, month and year in an alert box, using the values from above.
alert("Today is " + t_date + "-" + t_mon + "-" + t_year);
Does the month display correctly? If not fix it.
2. Display the time using the variables that store hours, minutes, seconds and milliseconds values.
alert("The time is " + t_hour + ":" + t_min + ":" + t_sec);
Generating Random Numbers in JavaScript
var rand_no = Math.random();
alert(rand_no);
Try it!
JavaScript ceil() method
The JavaScript ceil() rounds a decimal number to the next higher integer. Thus,
Math.ceil(2.456) //gives 3
Math.ceil(46.9) //gives 47
Math.ceil(0.0006) // gives 1
To remove numbers after the decimal and provide us with an integer between 1 and 100, we will pass the random number generated by random() to ceil().
var rand_no = Math.ceil(100*Math.random())
alert(rand_no);
Math.floor() method
The floor() rounds a number down to the lower integer. Thus:
Math.floor(2.456) //gives 2
Math.floor(46.9) //gives 46
Math.floor(0.0006) // gives 0
Math.floor(1.0006) // gives 1
Math.floor(0.932) // gives 0
But this throws up another problem. Numbers between 0.9 and 1.0 will all be rounded down (after multiplying with 10) to 9. The solution lies in multiplying the random number generated by random() with 11 - one number more than the range.
var rand_no = Math.floor(11*Math.random())
alert(rand_no);
How to use JavaScript random number
Suppose you want a random number between 1 and 100. How do you get it from the long decimal number thrown up by the random() method?
The first step is to multiply the long decimal random number generated by the random() method with 100.
var rand_no = Math.random();
rand_no = rand_no * 100;
alert(rand_no);
(#4 Name: Random Numbers)
1. How do we modify the above code to display 6 random numbers at a time? Do it! Display in an alert box. (Numbers should be displayed each on a separate line).
2. How do we modify the above code to display random numbers between 1 and 100? Do It! Use the above alert box to show you what random numbers are generated. Modify the formula and view several outputs of the result. Perfect your formula.
JavaScript Arrays
Consider the following table:
Number / City name1 / New York
2 / London
3 / New Delhi
4 / Sydney
5 / Tokyo
6 / Moscow
7 / Lima
To store these city names, we can either employ different variables such as city1, city2, city3 ... or insert these values into an array. Let's see how we make an array.
var city = new Array();
city[0] = "New York";
city[1] = "London";
city[2] = "New Delhi";
city[3] = "Sydney";
city[4] = "Tokyo";
city[5] = "Moscow";
city[6] = "Lima";
We can also write the array initialization and assignment statements as one.
var city = new Array("New York", "London", "New Delhi",
"Sydney", "Tokyo", "Moscow", "Lima");
var msg = "";
for (x = 0; x < 7; x++)
{
msg = msg + city[x] + "\n";;
}
alert(msg);
The length of an array is found though its length property.
var num = new Array(200, 400, 300, 250, 670, 430, 220, 870, 30);
var len = num.length
var msg = "";
for (x = 0; x < len; x++)
{
num[x] = num[x] + 50;
msg = msg + num[x]+ "\n";
}
alert(msg);
(#5 Name: Arrays)
1. Try each of the above scripts to see how they work. Use a separate JS file and a webpage with buttons. Include a screen shot of each result.
Loops
· for
for (i=0;i<=10;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
· while
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
· do while
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
while (i<=10);
(#6 Name: Loops)
1. Try each of the above loops to see how they work. Use a JS file and a webpage with three buttons. Include a screen shot of each result.
Random Text Display Using JavaScript
When to randomly display text on a web page?
On several web sites, random testimonials are displayed from a set. So each time the web page loads a testimonial is selected and displayed at random. The code can also be used to display a random quote or a greeting.
(#7 Name: Magic 8 Ball)
Create a Magic 8 Ball Application. Create whatever images and interface you would like on your webpage. In the JavaScript, You will need to:
1. Initialize an array
2. Store the text strings in that array
3. Find the length of this array
4. Using the Math.random() to generate a random number
5. Using the randomly generated number as index for retrieving a text string from the array.
6. Displaying the text through an alert() box or document.write()
Random Image Display Using JavaScript
The steps involved in randomly displaying an image from a set are very similar to those used for displaying random text strings.
1. Find six different images.
2. Initialize an array
3. Store the image file names in that array
4. Find the length of this array
5. Use the Math.random() to generate a random number
6. Use the randomly generated number as index for retrieving an image file name from the array.
7. Display the image.
var img_name = new Array("purple.gif", "red.gif",
"blue.gif", "yellow.gif", "green.gif", "pink.gif");
var len = img_name.length;
var rnd_no = Math.floor(len*Math.random());
document.r_img.src = img_name[rnd_no];
<img src="purple.gif" width="100" height="50"
name="r_img" alt="Random image" />
or
var img_name = new Array("purple.gif", "red.gif",
"blue.gif", "yellow.gif", "green.gif", "pink.gif");
var len = img_name.length;
var rnd_no = Math.floor(len*Math.random());
document.getElementById("randomimage").src = img_name[rnd_no];
<img src="purple.gif" width="100" height="50"
id="randomimage" alt="Random image" />
(#8 Name: Images)
1. Try each of the above codes. Make sure each works with your six different images.