Three JavaScript snippets for your web design toolkit

Ryan Boudreaux offers three handy scripts that you can use for common functionality requests like pop-up windows for additional information and dynamic menus.

This post includes a short list of three useful JavaScript programming snippets that I have utilized to solve common issues that crop up when special functionality is requested for websites. For instance, we all know as web developers that opening a link in a new window is probably one of the least enjoyable online experiences, but there are some folks who do like and appreciate that option, and on occasion, I have customers who request it. This is just one of the scripts that I include in this post, which you can add to your script library and toolkit.

Open link URL in a new, resized window

This JavaScript onclick functionality has it place in specific cases, such as when additional information is needed but does not require a full web page. It's a kind of pop-up, so it also helps if you include a "Close" button on the resulting window, so users can easily dismiss it. This in-line script allows you to modify several options including height, width, resizing, add-in scrollbars, toolbars, or menu bars, and also allows you to omit any of them from your script. The Onclick JavaScript defines a window1 equals window.open with the options to open the html file ‘newWindow.html', along with an ‘advisorywindow', a width of 475 pixels x 286 pixels, resizable, scroll bars, toolbar, and menu bar.

The in-line script sample displayed below can be added to any URL you wish to have opened in a modified window:

Figure A

Close and Print buttons

As I mentioned above, the added functionality of the Close and Print button option helps users with two practical functions, and these are especially beneficial for users who want the option of printing an online statement, receipt, or other items such as a ticket or coupon, and then easily closing the window when the action is completed. The following form uses the post method named "CloseOrPrint" with a submit input type,a value of "Close", an onClick action of "self.close()". The script also contains a JavaScript document.write function with the submit input type, a value of Print, and an Onclick option to ‘print':

Dynamic menus

Users like the ability to have a choice of inputs and the ability to change contents on the fly; in this example, we will use the months of the year, and when the month is selected the associated number of days in that month is populated. This similar functionality is also found on many websites that offer a menu of countries and their associated states or provinces, or in the case of the US, a listing of states with their associated parish or county listed. The dynamic menu functionality described here is inspired from the visual quick start guide book JavaScript, Eight Edition.

First, we will set up the days of the month as an array with the variable named monthDays as shown in the code snippet below. The array contains the 12 values (total days in each month) for the 12 months, which are the correct number of days in each given month in order from January through December: (Note: in a leap year the value for February will need to be updated in the monthDays variable as it is displayed below):

var monthDays = new Array(31,29,31,30,31,30,31,31,30,31,30,31);

Then we set up the variable for the month using this which is the month the user selects from the list, and then it gets stored as monthStr, as shown in the code snippet below:

var monthStr = this.options[this.selectedIndex].value;

Next, we create an if statement for the value of monthStr is equal to "", and then the user can choose the month from the drop-down menu and not the name "Month"; this line checks to be sure that the value of monthStr is not a null value. If the condition is true, the monthStr is turned into a number with the parseInt(monthStr) method, and then the variable theMonth is set to the result.

if (monthStr != "") {

var theMonth = parseInt(monthStr);

Finally, to change the Day menu, we set the options length to zero, which clears out anything that happened to be there previously, so that the menu starts fresh with each instance. The loop below processes the number of days as selected by the month and adds a new option for each day. The option is passed by the new Option(i+1) so that it displays 1 to 31:

document.getElementById("days").options.length = 0;

for(var i=0; i<monthDays[theMonth]; i++) {

document.getElementById("days").options[i] = new Option(i+1);

The HTML sets up the form action as displayed below:

<form action="#">

<select id="months">

<option value="">Month</option>

<option value="0">January</option>

<option value="1">February</option>

<option value="2">March</option>

<option value="3">April</option>

<option value="4">May</option>

<option value="5">June</option>

<option value="6">July</option>

<option value="7">August</option>

<option value="8">September</option>

<option value="9">October</option>

<option value="10">November</option>

<option value="11">December</option>

</select>

&nbsp;

<select id="days">

<option>Day</option>

</select>

</form>

The full JavaScript code snippet is displayed below:

window.onload = initForm;

function initForm() {

document.getElementById("months").selectedIndex = 0;

document.getElementById("months").onchange = populateDays;

}

function populateDays() {

var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);

var monthStr = this.options[this.selectedIndex].value;

if (monthStr != "") {

var theMonth = parseInt(monthStr);

document.getElementById("days").options.length = 0;

for(var i=0; i<monthDays[theMonth]; i++) {

document.getElementById("days").options[i] = new Option(i+1);

}

}

}

The output is shown in Figure B:

Figure B

JavaScript delivers a dynamic influence to websites and gives your users more interaction options when they visit. These three snippets simplify the process of including them for your users.

About Ryan Boudreaux

Ryan has performed in a broad range of technology support roles for electric-generation utilities, including nuclear power plants, and for the telecommunications industry. He has worked in web development for the restaurant industry and the Federal g...

Full Bio

Ryan has performed in a broad range of technology support roles for electric-generation utilities, including nuclear power plants, and for the telecommunications industry. He has worked in web development for the restaurant industry and the Federal government.

I'd really like to know why so many web designers now feel they have to use JavaScript for every damn page they create, even the ones that just provide static information for reading.
Back to the blog subject - I hope you are aware that one of the security settings for top security of your browser is to disable the ability of Java to open a page by itself and to disable the ability for Java to change size, menu, etc. The reason being to stop driveby attacks working in the background with a miniaturised or hidden window.

Simply you just need to modify the array in the leap year as I showed in the text description. However, there are functions to check for leap year which might be able to be incorporated into your code using the function isLeapYear() at the URL http://www.hscripts.com/scripts/JavaScript/isLeapYear.php

Bookmarked. :)
How does that code account for Leap years?
I notice that you have:
"[b][i]new Array(31,29, ...[/i][/b]" listed in the text description
"[b][i]new Array(31,28, ...[/i][/b]" listed in the actual code.

I suspect that part of the reason is so that the designer can use variables to control the page or the data on it (like in this article).
I've just finished the intro to HTML5 and CSS part of my course.
It's nightmarishly difficult to do anything that's even slightly tricky with css.
For example, I wanted to make 4 columns of info that auto-sized to the height of the column that contained the most info.
I had to give up and give them all fixed heights.
I suspect that it probably wouldn't be too difficult to accomplish that using js.
I run FF + NoScript. :)

make everything on a web page over fancy. In this I wonder why you want four columns, and if it's really necessary to have four. The next question is why not use frames, even basic html handles frames; I know it's usually difficult to use CSS and frames, but there's nothing says you HAVE to have a CSS at all.
My own website is just stock standard basic html with a couple of frames and a static display of data, as that's all I need. Yes, I know if you have a need to have visitor data input you need to do something a lot more fancy; but only a fraction of the web pages out there need that, so it should be reserved for only when it's needed and not done that way on every page.

"[i]Thanks for letting me know about this site.[/i]"
No problems. :)
Another site you can look at is "When can I use" (caniuse).
This site has tables for individual elements and properties (HTML, css, js, etc.).

the validity of the "Your Browser" test if they keep the scores. When I first ran it it go down scored in several areas simply because I have those capabilities turned off or plug-ins that disable those capabilities as part of my security settings. Thus the score is in no way relevant to the real capabilities of the browser.
The test said my browser didn't play mpg3 or mpg4, but I play them in the browser all the time - so I don't know how they determine that. However, I do have the system set for it to ask me before playing video, just like a lot of things are set to ask before doing.
Thanks for letting me know about this site.

Go to "The HTML5 Test".
Click on the "Other Browsers" tab.
1st - Google Chrome (I don't like it).
2nd - Maxthon (the interface isn't very customisable though).
We basically ignore Internet Explorer (even v10).
We are supposed to check our assignment site with Chrome & FF.
I've also installed Opera and Maxthon.
Some people in my class have Macs, so I guess they check with Safari too.
There are HTML5 tags that aren't supported by any browsers (yet).
Chrome, FF and Opera all support WebM (.webm).
Chrome, FF and Opera all support Ogg (.ogg).
IE and Safari will play Ogg using plugins.
I guess that MP4 (.mp4) is for Apple.

because if they were then you would only need the one file that complied with the HTML5 standard. Is the need for three videos due to some of them not being html 5 compliant? If so, which ones do you have to cater to? I'm interested to know which ones aren't being nice.

"[i]One of which is the big US push for using the Cloud for you office and data storage services, that concept is not that bad when you have an unlimited data plan, ...[/i]"
You also need [b]Unlimited Bandwidth[/b].
I forsee the entire Internet collapsing, when millions of people all try to edit 1+ GB of video on "Cloud" servers.

I should have been more specific.
The specifications of the assignment required the use of the HTML5 video tag.
Obviously video files were needed to demonstrate that the code had been correctly implemented.
The 3 videos were required so that Firefox, Chrome, Opera, Maxthon and other HTML5 compliant browsers could play them.
Even with 3 different video formats, IE9 would only play the soundtrack (no video).

a lot of the design concepts are coming out of the USA where most of the people currently have unlimited download Internet plans - that's why there's a big discussion going on over there about paying for downloads by the usage for the phone plans.
In short, the way computers and the Internet are used in the USA is often very different to how the rest of the world use them, and that leads to significant mismatches. One of which is the big US push for using the Cloud for you office and data storage services, that concept is not that bad when you have an unlimited data plan, but when you pay by the megabyte (like we do in Australia) it adds a huge expense to the project.

That quite a lot of Web Pages are now accessed by Mobile Devices not [b]"Real Computers"[/b] with Mobile Data Plans which are exorbitantly expensive to use, so it makes much more sense to follow the [b]KISS Principal.[/b] [i]Keep It Simple Stupid[/i]
I can not help but wonder just how many users get peeved off with massive Page Downloads which are expensive to them and how many stop using those sites as a direct result of all the crap included.
But then again I was always taught to be economical with anything I did and just because you have the capacity didn't mean you needed to use it all. ;)
Col

use browsers that weren't 100% Industry Standard in their operation. However, I'm shocked about the video aspects, last I heard all the browsers handled .avi and .mpg perfectly.
Want a real shock by looking at a site made from extremely basic html code, check out my site at www.bywater.net - all plain stock standard html, but then I'm not trying to deliver anything over fancy. I could add video and sound if I wanted, but most people find them a distraction unless absolutely necessary to the message.

The web mail site I use has 100+ scripts running (and Flash ads too)!
Smaller sites are better (less problems and easier to debug/monitor) and as you pointed out, faster to load.
That site must have been appallingly written (css files are tiny).
For example, the basic HTML5 web site assignment I had to complete had:
- 1 css file which was less than 5 KB (200 lines including comments).
- 4 HTML files totalling ~19 KB.
- 29 images totalling ~700 KB.
- 3 video files totalled 71 MB (3 formats were required to support the maximum possible number of browsers).
If it was up to me, I'd use a table for my page layouts.
Not much can go wrong with 4 or 5 cells in a table.
It also bypasses all of the problems that divs cause when you want to use borders.

CSS and Java that anything that conflicts with them is seen as evil. The current group of teachers are script happy and insist on having scripts for everything.
Not so long back I looked at a web site a friend paid to have created and the four pages had sixty-three scripts between them to display totally static information. There was one script for the banner info, one for the footer info, one for the menu calling the sub-menus and then each of those had their own scripts for their contents. Heck, in one case he had a script calling three scripts that then called two other scripts. The images were resized by the scripts with the original high resolution images being downloaded. The whole lot came to 180 MB of download. I redid it for him as basic html and got it down to 2 MB of download, all set within a three frame page and no CSS as the frames did most of that and one line in the headers of the displayed pages did the rest, I also saved about 100 MB by resizing the images in GIMP to the constrained sizes on the page so the small versions were all that was loaded.
The above was the result of being taught to be script happy with CSS, while I was taught to be plain and basic. Basic takes less download and that's important when the user pays for each MB, like they do here. Also, the smaller the page, the quicker it is to download, important where broadband is not available to everyone, like down here in rural Australia.

Every HTML course (I've been on) has taken the position that frames are "evil".
Apparently the "elites" also consider tables to be "evil" these days.
This means that the only option for laying out a page is to use divs (they have to be controlled using css).
I spend almost all of my page creation time debugging divs (e.g. 90% - divs, 10% - [i]everything[/i] else).
I suspect that is why so many pages have their layouts controlled by js.
Since the page is part of my course exercises and it must successfully validate as HTML5, all styling must be done in css.
We can choose our own layout structure (it's not necessary for the page to have 4 columns).
If I use 4 columns instead of 2, all of the info (lists of links) will fit on one screen (no scrolling).
I agree that Flash and js are overused on most web pages. :)
Rollover buttons are a good example.
Why use js when it is easy to do it in css?
I also prefer "functional and non-glitzy", to "non-functional and glitzy". :)