DHTML
Using JavaScript
More Really Neat Trickery
With this lecture, we are going to learn some JavaScript odd and ends that you should find quite interesting, and possibly even a bit humorous.
In an earlier lecture, we learned how to open up new windows and even position them. For those of you who really enjoyed that little adventure, we have good news: There's more! You can also move windows and resize them to your liking.
Moving Windows
Moving a window is actually quite simpler that you might think. To accomplish this might feat, we can make use of another window method, moveBy(). The moveBy method has 2 parameters, horizontal pixels and vertical pixels. It takes the following form:
window.moveBy(horizontal_pixels,vertical_pixels);
With this information, it is easy to move a window. Check out an example. It doesn't do too much, and when you've run out of screen, there's nothing else it can do. Here's the very simple code we used to do this:
function moveWindow(amount) {
if (self.moveBy) {
self.moveBy(amount,0);
}
}
As you can see, there's not much to this script. It has one parameter, the amount to move the window, which is passed to if from the onclick() event handler attached to the button.
First, we set up a conditional to see if the browser supports the moveBy() method. If it does, then we use self to refer to the current window instead of window. (Either way will work.) The vertical parameter is set to zero, as we are not going up or down, and the horizontal parameter is set to the value of the amount variable. We have set the amount in the onclick handler to 10, so every time you click the button, the window will move 10 pixels to the left.
If you wanted to move the window to the right, you would use a negative number. Similarly, if you wanted to move the window up or down, you would use a negative or positive number, respectively, in the first parameter.
With this knowledge at our fingertips, we can craft another cool page to amaze your friends and impress your neighbours.
This one is a little more complicated, but there should be nothing in there you don't know. Let's take a look:
var amount = prompt('How much do you want to move by? (20 is good)','');
amount = parseInt(amount);
function moveWindow(dir) {
// Specify a default amount in case none is entered.
if (amount == '') {
amount = 5;
}
// If the browser can do this.
if (self.moveBy) {
// If we are going left or right.
if ((dir == "left")||(dir == "right")) {
// If dir is left, and more then zero we need to make amount negative.
if ((dir == "left")&&(amount > 0)) {
amount = -amount;
}
// And if dir is right, and less than zero, we need amount reversed.
if ((dir == "right")&&(amount < 0)){
amount = -amount;
}
// move the window.
self.moveBy(amount,0);
}
// Same as above, but with the vertical parameter.
if ((dir == "up")||(dir == "down")) {
if ((dir == "up")&&(amount > 0)) {
amount = -amount;
}
if ((dir == "down")&&(amount < 0)){
amount = -amount;
}
self.moveBy(0,amount);
}
}
else {
alert('Your browser doesn\'t support MoveBy');
}
This code is fairly well commented so you should read the comments to get a good idea of what's going on here. All we are doing is setting up a bunch of conditionals to test to see which way we want to go, and to make the amount variable positive or negative depending on which way. The only thing we are really changing in here is the amount variable. Also, we put in an alert for our browser impaired friends. (This script will work on both IE and Netscape versions 4 or greater.)
Now that we know how to move windows, we can accomplish cool things like this example. (We'll leave you to figure out how we did that one.)
Note: There is another window method similar to moveBy(), called moveTo(). Instead of moving the window relative to where it is, such as moveBy() does, moveTo() moves the window to an absolute position on the screen.
Note: The Opera browser seems to have a problem with moveBy(), treating it more like moveTo(). If you are going to be using moveBy() in any of your Web pages, you might want to make your viewers are aware that they should be running the latest versions of IE or Netscape in order for everything to work properly.
Resizing Windows
Let's move on to another neat window trick. We can also resize windows to our liking with the resizeBy() window method. This method uses 2 parameters as well, with the first for the horizontal (or X) size, and the second for the vertical (or Y) size.
This example resizes the window by 50 pixels
Here's the code for that example:
function resizeWin(amount) {
if(window.resizeBy) {
window.resizeBy(amount,amount);
}
}
Not too much going on here, just a simple script that resizes the window in both directions. Let's try something a little more exciting:
And here's the script:
function resizeWin() {
// If the browser can do this.
if(window.resizeBy) {
// Get the amount to resize by.
var amount = prompt('Enter the number of pixels to resize by','');
// Make sure it's a number.
amount = parseInt(amount);
// Set up a loop to resize the window more each time.
for(i = 1; i < amount; i++) {
window.resizeBy(1,1);
}
}
else {
alert('Your browser doesn\'t support resizeBy');
}
}
By now, this should be old hat to you. You should be careful when experimenting with this one, you can easily get a window that never stops growing. (IT'S ALIVE, IT'S ALIVE! BWAHAHAHAHAHA!)
If we put the two of these techniques together, we can get something really interesting.
Note: Netscape 4.x has a minor quirk with the resizeBy() method. If you are creating a new window, and you try to use the resizeBy() method on this new window, then the resizable window feature must be enabled. If you don't have resizable=yes specified, then the window will not resize with the resizeBy() method.
There is another window method that resizes a window, called resizeTo(). This method also takes two parameters, but in this case, they size the window to a width and height specified in the method. For example:
window.resizeTo(640, 480);
Will resize the window so that it is 640 pixels wide, and 480 pixels high.
Working With Time and Date
You may have already seen Web sites that have the time and date showing on a page. While this may seem a little pointless (as most operating systems have a clock plainly showing somewhere on the screen), it can come in handy for other things. We'll leave most of the applications of this for you figure out, but we will show you how to get and display the time and date using JavaScript.
JavaScript has a convenient way to easily get the time and date, and work with this information in a variety of ways. The time and date can be gotten using the Date() object.
By itself, the Date object gives the time and date in the following form:
Thu Feb 22 02:26:03 2011
This is probably not going to be the way that you want to display your date. The best way to use the Date() object is to use a constructor to make a new date object like so:
var date_object = new Date();
Note that the Date() object always starts with a capital "D".
Once we have our new date object, we can access its properties and methods easily. Some of the more popular methods of the date object are:
date_object.getYear();(or getFullYear) - This returns the year. (more on this in a bit)date_object.getMonth();- This returns the current month, from 0 to 11 (where 0 is January, and 11 is December).date_object.getDate(); - This returns the day of the month, from 1 to 31, representing the day of the month.date_object.getDay();- This returns the day of the week, from 0 to 6 (where 0 is Sunday, and 6 is Saturday).date_object.getHours();- This returns the current hour.date_object.getMinutes();- This returns the current minutes.date_object.getSeconds();- This returns the current seconds.date_object.getMilliseconds();- This returns the current milliseconds.
There are a number of other methods for the Date() object, but many of them may not be very useful. A good example of one of these is the getTime() method, which gives the number of milliseconds that have elapsed since midnight on January 1, 1970. But who knows, maybe you have a need for that kind of information. If you do, you can use getTime() to obtain it.
One problem you may encounter is in getting the current year. You may have noticed that there are two different methods that can accomplish this: getYear() and getFullYear(). The latter of these two, getFullYear() is the currently recommended method. Keep in mind however, if you use getFullYear(), it is not supported in earlier browsers such as Netscape 3. In Netscape 3, this method will cause an error. The other method, getYear(), also comes with its own problems. While getYear() will display the proper year in Netscape 3, subsequent versions of Netscape will show an incorrect date. (For the year 2003, the number 103 will be displayed.) In order to use getYear(), you must do a browser detection, and then add 1900 to the year if a netscape version greater than 3 is detected. For this example, we will use the getFullYear() method.
Except for the getDate() object, (which conveniently gives the days of the month from 1 to 31) most of the above methods start at 0. Before you start wondering why they have made life so difficult by doing this, remember that JavaScript arrays start with zero as well. This makes it easy to make an array that contains strings of the proper names for things like days of the week and months of the year. So to display a properly formatted date, we can start with a few arrays.
var the_date = new Date();
var month_array = new Array();
month_array[0] = "January";
month_array[1] = "February";
month_array[2] = "March";
month_array[3] = "April";
month_array[4] = "May";
month_array[5] = "June";
month_array[6] = "July";
month_array[7] = "August";
month_array[8] = "September";
month_array[9] = "October";
month_array[10] = "November";
month_array[11] = "December";
var day_array = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
// With these arrays defined, we can now format our date:
var weekday = day_array[the_date.getDay()];
var month = month_array[the_date.getMonth()];
var day = the_date.getDate();
var year = the_date.getFullYear();
document.write('Today is: ' + weekday + ', ' + month + ' ' + day + ', ' + year);
As you can see, this will output a nice, formatted date.
If we use JavaScript to output the time, we get this in the military format. For most users, that's not how they are used to seeing the time. Therefore, we will need to convert the military time to a more familiar format.
See if you can figure out how to do that, then check this example when you are done or if you are stumped.
There are a few other things you will need to do to get a properly formatted time. First, keep in mind that JavaScript starts counting at zero (0). Therefore if the hour is midnight, getHours will return a zero. Therefore, you will need some kind of conditional to check for this, and change it to "12" accordingly. Second, JavaScript will never return numbers like these: "3:04". We are all used to having the "0" before a single digit minute or second. JavaScript would return the minute portion of that example as: "3:4". Therefore, you will need to write another conditional to check if the minutes/seconds are less than 10, and add (concatenate) the extra zero.
More Really Neat Trickery Summary
- Windows can be moved a given number of pixels using the
moveBy()method of the window object. - The
moveTo()method of the window object moves the window to an actual location on the screen. - Windows can be resized by a given number of pixels using the
resizeBy()method of the window object. - The
resizeTo()method resizes the window to a specified width and height. - You can access both the time and the date by creating a new
Date()object. - The
Date()object has many methods that will return everything from the current year to the current time. - The method
getFullYear()is the recommended way to get the current year, but this method will result in an error if run in versions of Netscape earlier than 4. - The method
getYear()also returns the current year, but you must add 1900 to the year in Netscape versions 4 and up. - JavaScript always outputs the current time in a military format.
DHTML - TOC - Introduction - Books -
Using JavaScript - Links - Questions -
1 - 2 - 3 - [ 4 ] - 5 - 6 -
