Variables and Values
Variables and Types of DataVariables can be used to hold values or expressions. A variable's value can change during the execution of a script. You can refer to a it by its name to display or change its value. The same variable can be used for different types of information. There are a few rules that need to be followed when naming variables:
- Upper case and lower case letters of the alphabet, underscores, and dollar signs can be used
- Numbers are allowed after the first character
- No other characters are allowed
- Variable names are case sensitive: different case implies a different name
- A variable may not be a reserved word
Primitive Types are provided by the system. With primitive types, users may also define their own classes. Primitive types for JavaScript are booleans, numbers and text.
- Boolean variables can only have 2 possible values, true or false.
- You can use Integer and Float types on your variables, but they are treated as a numeric type.
- String types and char types are all strings, so you can build any string literal that you wished for.
A Complex type is an object, be it either standard or custom made. Its home is the heap and goes everywhere by reference.
- Array Types are all untyped in JavaScript, so you can put everything you want in an Array and worry about that later. Arrays are objects, they have methods and properties you can invoke at will. Arrays can also be created with the array notation, which uses square brackets. Arrays are accessed using the square brackets. There is no limit to the number of items that can be stored in an array.
- Object Types within Javascript are created using the new operator. Objects can also be created with the object notation, which uses curly braces. JavaScript Objects can be built using inheritance and overriding, and you can use polymorphism. There are no scope modifiers, with all properties and methods having public access. You can access browser built-in objects and objects provided through browser JavaScript extensions.
Creating Variables
Creating variables in JavaScript is usually referred to as declaring variables. You declare JavaScript variables with the var keyword eg:
var x;
var carname;
These variables are empty.
A variable declared within a JavaScript function becomes LOCAL and can only be accessed within that function. You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared. Local variables are destroyed when you exit the function.If you assign values to variables that have not been declared yet, the variables will automatically be declared as global variables.
Variables declared outside a function become GLOBAL, and all scripts and functions on the web page can access it. Global variables are destroyed when you close the page. If you declare a variable, without using "var", the variable always becomes GLOBAL.
Assigning Values
Below is another example of variables with values assigned to them:
var x=7;
var carname="VW";
After the execution of the statements above, the variable x will hold the value 7, and carname will hold the value VW. When a text value is assigned to a variable, quotes must be used around the value. If you redeclare a JavaScript variable, it will not lose its value.
Calculations
Small calculators can be created using JavaScript. These calculators are plain and can only add, subtract, multiply and devide. This calculator can either resemble a real calculator, with buttons for each number/symbol; or text boxes can be used were the user can enter the numbers, click a button for the action, and the result will also be displayed in a textbox. There will be 3 text boxes: 'Number One', 'Number Two', and 'Total.' (Keep in mind that you can only work with two numbers at once.)
Operator Precedence
JavaScript Operators have a predefined order of precedence which are used to process and evaluate a JavaScript expression. JavaScript Operator Precedence is similar to the Mathematical Operator Precedence and Associativity. Like basic algebra Operator Precedence, JavaScript multiplication and division Operator have higher precedence over addition and subtraction Operator.
Arrays
An array is a special variable, which can hold more than one value, at a time. It can hold all your variable values under a single name and you can access the values by referring to the array name.
Array Methods
| concat() | Joins two or more arrays, and returns a copy of the joined arrays |
| join() | Joins all elements of an array into a string |
| pop() | Removes the last element of an array, and returns that element |
| push() | Adds new elements to the end of an array, and returns the new length |
| reverse() | Reverses the order of the elements in an array |
| shift() | Removes the first element of an array, and returns that element |
| slice() | Selects a part of an array, and returns the new array |
| sort() | Sorts the elements of an array |
| splice() | Adds/Removes elements from an array |
| toString() | Converts an array to a string, and returns the result |
| unshift() | Adds new elements to the beginning of an array, and returns the new length |
| valueOf() | Returns the primitive value of an array |
Arrays of Elements
The elements object (array) allows you to access any element within a form generically, via a loop for example. Each element inside the form is stored as an array element inside elements. Each element in the array has its own ID so that it can be easily accessed.
Strings
The String object is used to manipulate a stored piece of text. String objects are created with new String().
Program Flow
Testing ValuesThe test() method tests for a match in a string. This method returns true if it finds a match, otherwise it returns false. It can save a lot of time, seeing that you do not have to go and search manually.
Loops
Loops execute a block of code a specified number of times, or while a specified condition is true. Instead of adding several almost equal lines in a script when you want the same block of code to run over and over again in a row, loops can be used to perform this task.
In JavaScript, there are two different kinds of loops:
- for - loops through a block of code a specified number of times. The for loop is used when you know in advance how many times the script should run.
- while - loops through a block of code while a specified condition is true. The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true.
Break
In javascript, you can sometimes get stuck in a loop. This is called an infinite loop. Javascript allows you to break out of an infinite loop with the use of the "break" keyword. When javascript encounters the break keyword, it cases the javascript to stop executing the loop and executes the first statement that comes after the loop.
Continue
The continue statement will break the current loop and continue with the next value.
Branching/Multiple Brancing with 'if'
Branching is the use of closures to get the browser to interpret a block of code only one time, when otherwise, it would interpret that block over and over and over again.
The Conditional Operator
JavaScript also supports an implicit conditional form. It uses a question mark after the condition to be tested (rather than the word if before the condition). It also specifies two alternatives, one to be used if the condition is met and one if it is not. A colon must separate these alternatives. If you have several conditions to be tested together, and you know that one is more likely to pass or fail than the others, you can use a feature called 'short circuit evaluation' to speed the execution of your script. When JavaScript evaluates a logical expression, it only evaluates as many sub-expressions as required to get a result.
Using Functions
JavaScript functions perform actions; they can also return values. Sometimes these are the results of calculations or comparisons. Functions are also called "global methods". Functions combine several operations under one name. This lets you streamline your code. You can write out a set of statements, name it, and then execute the entire set by calling it and passing to it any information it needs. You pass information to a function by enclosing the information in parentheses after the name of the function. Pieces of information that are passed to a function are called arguments or parameters. Some functions do not take any arguments at all while others take one or more arguments. In some functions, the number of arguments depends on how you are using the function. JavaScript supports two kinds of functions: those that are built into the language, and those you create yourself.
Active Pages
Dates and TimesThe Date object is used to work with dates and times. Date objects are created with the Date() constructor. Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time. All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
Timeout
It might be possible that in some applications, a developer wants to display the time left for the session to be over or timeout. That will enable the user to save the entered information or it can be used for any other purpose depending on the requirement. Timeouts are often used on internet banking sites so that someone else cannot access your accounts if you forgot to log off, or for other safety reasons.
Scrolling Text
These scripts scroll information on the screen - either on the status bar, or in a text box. Some scripts print out messages. They can also be used to display news, special highlights, etc.
Sounds
There are different ways to play sound from JavaScript. The simplest cross-browser script for playing a sound file is:
self.location="AUDIO_FILE_URL"
Most modern browsers will remove the current page in the active browser window or tab, and replace it with a sound control. Some older browsers used to open a separate sound control window. This is not very user friendly and can be slightly annoying because every time you open a sound file, you loose the original and have to keep going back to the page.
Controlling Sounds
This is a more complex example in which you won't see a separate sound control window:
In Firefox, Safari, and Google Chrome the audio playback functionality relies on plugins such as Apple QuickTime. With the audio plugin(s) installed, you will need an OBJECT tag for the browser to activate the plugin. Here is an example of an OBJECT tag:
<OBJECT DATA="audioURL.mid" TYPE="audio/midi" TITLE="Description"
WIDTH=250 HEIGHT=20>
<PARAM NAME=autostart VALUE=true>
<PARAM NAME=hidden VALUE=false>
</OBJECT>
Using these tags will give you a "play sound" and "stop sound" button. This allows you to control the sound and stop it from playing continously. Embed Array
JavaScript lets you create arrays inside arrays, known as nested/embedded arrays. In a nested array, the elements of one array are themselves arrays. To access the elements of the inner arrays, you simply use two sets of square brackets.You can nest arrays as deeply as you like.
Working with Images
Image FilesThe way a browser normally works, images are loaded only after an HTTP request is sent for them, either passively via an <img> tag or actively through a method call. So if you have JavaScript that swaps an image on mouseover, or changes an image automatically after a timeout, it could take a really long time to load the image. Preloading is a technique where the image is downloaded to the cache before it's needed. That way when the image is really needed it can be retrieved from the cache and displayed immediately. The simplest way to preload an image is to instantiate a newImage() object in JavaScript and pass it the URL of the image you want preloaded. In order to preload this image for faster response time, you simply create a new Image()object, with the same name as your image, and load it simultaneously to the page with the onLoad() event handler.
Image Objects
The Image object represents an embedded image. For each <img> tag in an HTML document, an Image object is created. Below is a list of image object properties:
| align | Sets or returns the value of the align attribute of an image |
| alt | Sets or returns the value of the alt attribute of an image |
| border | Sets or returns the value of the border attribute of an image |
| complete | Returns whether or not the browser is finished loading an image |
| height | Sets or returns the value of the height attribute of an image |
| hspace | Sets or returns the value of the hspace attribute of an image |
| longDesc | Sets or returns the value of the longdesc attribute of an image |
| lowsrc | Sets or returns a URL to a low-resolution version of an image |
| name | Sets or returns the name of an image |
| src | Sets or returns the value of the src attribute of an image |
| useMap | Sets or returns the value of the usemap attribute of an image |
| vspace | Sets or returns the value of the vspace attribute of an image |
| width | Sets or returns the value of the width attribute of an image |
| onabort | Loading of an image is interrupted |
| onerror | An error occurs when loading an image |
| onload | An image is finished loading |
Simple Animation
The idea behind Javascript-based animation is that a number of DOM elements are moved around the page according to some sort of pattern determined by a logical equation or function.To achieve the effect of animation, elements must be moved at a given interval or frame rate; from a programming perspective, the simplest way to do this is to set up an animation loop with a delay. Javascript doesn't have a "pause" feature, unlike some earlier higher-level languages.
Animated/Animating gifs
Animated GIF's are the easiest to create and implement. GIF is the most widely supported format since everyone using a graphical browser has the capability to view GIF images. In an animated GIF file, several GIF89 images are stored in a single file and then played in sequence. The image file is downloaded once and replayed from the computer's disk cache. It is possible to include an animated GIF on your page and give the user some control over its display. If you can use the animation in a link, control it with a JavaScript rollover. The image only displays when the visitor moves the mouse over the graphic.
Image Maps
An image-map is an image with clickable areas. The name attribute is required in the map element. This attribute is associated with the <img>'s usemap attribute and creates a relationship between the image and the map. The map element contains a number of area elements, that defines the clickable areas in the image map. In XHTML, the name attribute of the <map> tag is deprecated, and will be removed. The id attribute should be used instead.
Interactive Systems
CheckboxesWith checkboxes, multiple sekections can be made. The state of a box can be of two things- "on" when it is selected, and "off", when it is not. This state is represented in JavaScript by a boolean property called "checked". Using this property, you can not only determine the state of a box, but change it as well, by assigning either a value of "true" or "false" to it.
Radio Boxes
With radio boxes, only one box can be checked. If one is already selected and the user clicks on another, the previous box will be "unchecked." A way to then determine which box is selected, is to use a for-loop to loop through the box array, and pick out the one that's selected. This technique calls for a loop to check the entire array of boxes, and simply pick out the one that's selected.
Another method to determine which box is selected is to use the onClick event handler. Since <input> tags in general all react to onClick events, this is a simple way to determine the selection of a user.
Links from Lists
This is a type of data storage structure that has some similarities to the array data type. The key difference is that, rather than storing values using numeric indexes, it stores them by creating links between successive elements so that they form a chain. Linked lists make removing and re-ordering elements really easy and efficient.
Feedback Online
The mailto is a quick way to add the facility of receiving feedback from visitor on your web site. With the HTML mailto, you create a link which when clicked by the visitor launches their email program with a new email message window. The visitor could then formulate the email message and send it off to you. In its simplest form, the HTML mailto requires an email address.
Checking Entries
JavaScript can be used to validate data in HTML forms before sending off the content to a server. Form data that typically are checked by a JavaScript could be:
- has the user left required fields empty?
- has the user entered a valid e-mail address?
- has the user entered a valid date?
- has the user entered text in a numeric field?
Using a few simple extensions to the HTML standard, Web authors are able to achieve sophisticated control over the layout of information in the web browser window by dividing the window into rectangular sections and loading separate HTML files into each section of the window. In addition, links in one frame can update another frame - just as a button click in one form can affect another form (OOP), and the result of processing form data in a CGI script on a server can be targeted at another frame. A page is divided into frames using the FRAMESET tag. The tag is used in the top-level document defining a window containing frames and is used to specify how to divide the document window. The FRAMESET container tag takes several attributes. The two basic ones are ROWS and COLS. A FRAMESET tag takes either one of these or both to divide a document into a set of rows or columns. For example,
<FRAMESET COLS="25,*,25">
would define three columns. The two outer columns would each be 25 pixels wide, and the middle column would take the remaining space depending on the size of the window. In this example the asterisk (*) represents the remaining available space after the space is allocated for the other frames.
In addition to specifying the size of frames in pixels, the size of columns and rows can be defined using percentages relative to the space available to the document. Eg,
<FRAMESET ROWS="35%,*">
This FRAMESET tag would divide the display into two rows. The top row would be 35 percent of the height of the display area, and the bottom row would fill the remaining space (using the asterisk again). The FRAMESET ROWS and COLS tags can take 3 different values, as you can see from above - the absolute pixel value, given by just a number, the percentage value, which is the percentage of the user’s display resolution to be used, given in n% and the asterisk (*) which represents the remaining space. Each value provided in the ROWS or COLS tags will indicate an addition of one more row or column.
Window Control
Below is a list of the most common attributes to windows:
- url - The url string to be diplayed in the window. This setting is optional for when you want to write content to the window depending on user input.
- name - The unique name string given to a window. This value can be used for target attributes for links. If this value is not unique, any other windows created with the same name will replace this window.
- parameters - Comma seperated string of parameters. There should be no spaces in this list. Any parameters left out will be displayed by default. Basic format is parameter1=value1,parameter2=value2,etc.... If the parameter is specified, but no value is assigned, it will default to yes (This rules does not apply to parameters that need values such as width, height, etc).
- height - Height of the content of the window in pixels. This does not include menubar/statusbar.
- width - Width of the content of the window in pixels.
- menubar - Specifies if the menubar (File, Edit, View, etc) is displayed. yes or no.
- scrollbars - Specifies if the scrollbars are displayed. yes or no.
- toolbar - Specifies if the button images (back, forward, reload, stop, etc) bar is displayed. yes or no.
- status - Specifies if the status bar is displayed. yes or no.
- left (use screenX for Netscape 4) - The horizontal window position in pixels from the left of your monitor screen.
- top (use screenY for Netscape 4) - The vertical window position in pixels from the top of your monitor screen.
- resizable - Specifies if the window is resizable. yes or no. Watch for spelling, many people mistankingly use "resizeable" instead, which will not work.
In JavaScript, PHP, and ASP there are functions that can be used to URL encode a string.In JavaScript you can use the encodeURI() function. Below are a few of the URL Encoding References.
| ASCII Character | URL-encoding |
|---|---|
| space | %20 |
| ! | %21 |
| " | %22 |
| # | %23 |
| % | %25 |
| & | %26 |
| ( | %28 |
| ) | %29 |
| * | %2A |
| , | %2C |
| . | %2E |
| / | %2F |
| 0 | %30 |
| 1 | %31 |
| 2 | %32 |
| 3 | %33 |
| 4 | %34 |
| A | %41 |
| B | %42 |
| C | %43 |
| D | %44 |
| E | %45 |
| F | %46 |
Java Applets
Java Programming LanguageJava applications are typically compiled to bytecode that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere." Java allows you to play online games, chat with people around the world, calculate your mortgage interest, and view images in 3D, just to name a few. It's also integral to the intranet applications and other e-business solutions that are the foundation of corporate computing.
Developing Applets
Are an application designed using component-based architecture can be developed into a Java applet. With component-based design, the graphical user interface (GUI) can be built with smaller building blocks or components. The following general steps are used to create an applet GUI:
- Create a class MyTopJPanel that is a subclass of javax.swing.JPanel. Lay out your applet's GUI components in the constructor of the MyTopJPanel class.
- Create a class called MyApplet that is a subclass of javax.swing.JApplet.
- In the init method of MyApplet, instantiate MyTopJPanel and set it as the applet's content pane.
Creating a Threaded Applet
Threads are needed when you want to perform actions over and over again. An applet is a separate stream of execution, to perform a background task. The body of the thread's code is in the run() function. Eg. for a simple animation, the purpose of the thread is to increment the variable i once every 1000 milliseconds, and cause the applet to redraw itself.
Sending Parameters to Applets
Parameters are passed to applets in NAME=VALUE pairs in <PARAM> tags between the opening and closing APPLET tags. Inside the applet, you read the values passed through the PARAM tags with the getParameter() method of the java.applet.Applet class. You also need an HTML file that references your applet.
The PARAM element is also straightforward. It occurs between <APPLET> and </APPLET>. It has two attributes of its own, NAME and VALUE. NAME identifies which PARAM this is. VALUE is the string value of the PARAM. Both should be enclosed in double quote marks if they contain white space. An applet is not limited to one PARAM. You can pass as many named PARAMs to an applet as you like. An applet does not necessarily need to use all the PARAMs that are in the HTML. Additional PARAMs can be safely ignored.
Using Fonts and Colours in Applets
This Java applet lets you choose colors and fonts for your applications. The values of the colors you get, can be used in many programming languages (not only in Java). It will be very helpful for developers and programmers as you can easily try out various combinations of background and foreground (color of the text) colors. You can also try out different fonts in this applet. Once you are satisfied, get the respective RGB values from the text fields. These values you can pass in the java.awt.Color constructor to get the desired effect for your applications. For use in html pages you get hex values too. You can also use this applet to convert RGB values to hex and hex values to RGB values. To try out fonts, just choose different options like font name, size, and style. As soon as you make these choices, the font of the text in the applet will change reflecting your choices.
Java Security
Java security technology includes a large set of APIs, tools, and implementations of commonly used security algorithms, mechanisms, and protocols. The Java security APIs span a wide range of areas, including cryptography, public key infrastructure, secure communication, authentication, and access control. Java security technology provides the developer with a comprehensive security framework for writing applications, and also provides the user or administrator with a set of tools to securely manage applications.
References:
- www.w3schools.com
- www.quirksmode.org/js/strings.html
- www.hunlock.com/blogs/Mastering_Javascript_Arrays
- webdevelopmenttutorials.com
- blog.stchur.com
- javascript.internet.com
- www.javascripter.net
- www.javascriptkit.com
- www.jsmadeeasy.com
- en.wikipedia.org
- www.java.com
- homepage.ntlworld.com
- www.tipsntracks.com
- www.javascriptkit.com
- www.schillmania.com
- www.netmechanic.com
- www.techrepublic.com
- library.thinkquest.org
- download.oracle.com
- http://profs.etsmtl.ca
- www.oracle.com
- www.akgupta.com
- www.cafeaulait.org
- msdn.microsoft.com