HTML Markup | JavaScript | Java | Computer Sci | Home & Links
JR's HomePage | JavaScript Home | Site Map | Page Bottom
Unique Random Numbers | Nearest Number | Date Displays
Days in Month | Six Day Cycles | TextArea Format Dump
Text Formatting | Secure Feedback Link

JavaScript Projects [Short]

This page is a listing of short projects that can be copied, modified and tested within an evening. The projects focus on single objects (Math and Date) or simple techniques. The working samples can be used as quick study learning sessions. Be sure to check Big Projects, Form Projects and Webpage Effects pages for ideas.

Unique Random Numbers

Generating random numbers in a set range is very easy:

var Max=100; // end of range
loRnd=Math.floor(Math.random()*Max); // value from 0 to Max-1
hiRnd=Math.ceil(Math.random()*Max); // value from 1 to Max 

However creating a set of unique random numbers is a bit more complex. Here is a quick cut/paste routine.

var picked=[]; // the global array for selected values
function getUnique(NumUnique,MaxValue)
  {
    var found=false;var count=0;
    for (var i=0;count<NumUnique;count++)
    {
      found=false; rndValue=Math.floor(Math.random()*MaxValue);
      for (var j=0;j<pic.length;j++)
          {if (pic[j]==rndValue) {found=true;break;} }
      if (found) {count--;} else {picked[count]=rndValue;}
    } }

Nearest Number Function

When doing metric conversions there is often a need to select the closest of two values. For example standard sizes may be 1/4 or 1/2 when measured in inches. A metric size may convert to .335 inches. Is this closest to 1/4 or 1/2. The nearest function returns the correct answer.

function near(t,x,y){
if (Math.abs(t-x)<Math.abs(t-y)){return x;}
return y;}

Date Display Routines

Date displays normally use Date objects. Instances are created with the Date(datestring) constructor. datestring can be null which is then set from the system clock. Using a datestring with the day zero sets the object to the last day of the previous month. With the addition of the Array and Math objects you can format the display in many ways. Some fun projects using date displays include:

  1. Indicate actual day of your birthday either this year or birthyear
  2. Indicate the first date/day of the past or coming week
  3. Calculate how many days left until Xmas or another special date
  4. Calculate exactly how old someone is

1. Finding the day name for a particular date uses the getDay() method which returns a dayOfWeek number. This number is used to index an array of day names.

2. To calculate the start of the current week all you need to do is examine today's day number. If it is not zero (ie. Sunday) then set the date back one. Don't forget to watch for the beginning of a year

3. Countdown to special date displays make use of the getTime() method. The following snippet is very easy to understand! The only trick is to allow for special days that have already gone by this year.

4. Calculating long spans is a little trickier. Using the technique of countdowns will yield a raw day number which could be broken crudely into years, months and days but leap years must be considered!

BEWARE: There are several built-in string methods [toString(), toLocaleString() and toUTCString()] for converting date objects into strings. Although the date object is in a standard format, the strings returned by the string methods are unique to each browser. These differences between browsers makes it unwise to use these string methods and parsing the results. You may wish to test this fact by observing the following toString display within each browser that you may have.

A much more predictable way is to access each component of a date and build up your own date and/or time string. The following example builds a string for each of the current date and the current time.

Days In Month

At times you may need to know how long a specific month is.

Six Day Cycles

Some workplaces work on a six-day calendar (i.e. Monday=Day 1, Tuesday=Day 2, etc with Saturdays and Sundays being Day 0 since they are weekends). So for the following week Monday is Day 2, Tuesday is Day 3, etc. Create a function that returns the appropriate day number.

One solution would use these steps:

  1. Establish origin date as previous Sunday (day 0). Modify date display routine #2 for this.
  2. Calculate total days since origin.
  3. Calc total weeks since origin.
  4. Calc shift as number of completed weeks.
  5. Calc cycle number as (normal+shift) mod 6.

TextArea Format Dump

This project investigate how the textarea element treats 'hard returns'. It is simply a button that calls the byteDump() function which shows the charCode for each character in the string returned by the textarea's value. Firefox uses 'lf' (dec 10) while Opera and MSIE use 'cr''lf' (dec 10,13) in Windows XP. I would appreciate reports from those using other platforms.

Text Formatting

Text formatting can be as simple as changing case or initializing all words or first words in sentence. More complex forms of formatting could be adding/removing database tagging or removing obsolete HTML elements. Text justification and decimal roundoff are examples of formatting routines often needed for output display.

Right justification is a simple matter of padding a string from the left hand side. Here is a short funcion to do it.

Decimal roundoff is another common formatting requirement. This is done by moving the decimal to where needed, clipping with the round method and restoring the number.

Secure Feedback Link

Unprotected mailto links can be data-mined with SpamBots by businesses and spammers to build mailing lists. You can reduce the chance of your mailing address being data-mined by moving the link info to a dynamic JavaScript function such as:

Note1: Be sure to include an onload="feedback()" attribute on the body element and either a
<div id="feedback"> or a <span id="feedback"> element where you want the link to be displayed.

Note2: As with all scripts, the feedback function can be defined in an external file (say onload.js). Link to the external file with <script src="onload.js" type="text/javascript"></script> in the head section of all HTML documents using the feedback link. This is a good method for those who wish to include feedback links on many pages and makes changing the link a one-stop operation as well.

Beware: Several software vendors provide a ?protection? program that simply changes the address into character codes. These methods do not fool the data-miners though as the addresses can easily be reconstructed by their SpamBots. The scripting method described on this page provides slightly better protection as it is more dynamic. For more sophisticated techniques involving encoding you may wish to google Email Protect or similar terms.


JR's HomePage | Comments [jsproj2.htm:2010 02 06]