I.T. Discussion Community!
-Collapse +Expand
JavaScript
Search JavaScript Group:

Advanced
-Collapse +Expand JavaScript Store

Prestwood eMagazine

August Edition
Subscribe now! It's Free!
Enter your email:

   ► KBJavaScript Knowledge Base  Code Snippet DB All Groups   Print This   

JavaScript Code Snippets Page

These Code Snippets are contributed by you (our online community members). They are organized by our knowledge base topics. Specifically, by the JavaScript sub-topics.

Contribute a Code Snippet
Expand All

28 JavaScript and AJAX Code Snippets

Group: JavaScript and AJAX


Topic: Beginners Corner

-Collapse +Expand 1. JavaScript Assignment (=)
 

JavaScript uses = for it's assignment operator.

//Regular assignment.
LastName = 'Spitz';
  
//Variable declaration with assignment.
var FullName = 'Randy Spitz';
var Age = 38;
Posted By Mike Prestwood, Post #101379, KB Topic: Beginners Corner
-Collapse +Expand 2. JavaScript Comments (// or /* ... */)
 

Commenting Code
JavaScript uses "//" for a single line comment and /* */ for a multiple line comment.

//This is a single line comment.

/*
Multiple line
comment.
*/
Posted By Mike Prestwood, Post #101504, KB Topic: Beginners Corner
-Collapse +Expand 3. JavaScript Comparison Operators (==, !=)
 

Common comparison operators:

== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

//Does JavaScript evaluate the math correctly? No!
if (.1 + .1 + .1 == .3) {
document.write("correct");
}
else {
document.write("not correct");
}
Posted By Mike Prestwood, Post #101874, KB Topic: Beginners Corner
-Collapse +Expand 4. JavaScript Development Tools
 

Languages Focus: Development Tools

Primary development tool(s) used to develop and debug code.

JavaScript Development Tools

Many developers just use a text editor. There are JavaScript editors available including 1st JavaScript Editor, Antechinus JavaScript Editor Professional, and SplineTech JavaScript Debugger PRO.

Posted By Mike Prestwood, Post #101614, KB Topic: Beginners Corner
-Collapse +Expand 5. JavaScript End of Statement (; is optional)
 

In JavaScript, using a semicolon at the end of statements is optional. You might think a semicolon then is just another comment specifier but it is not. The semicolon is an optional end of statement specifier. To put two statements on a single code line, you must use a semicolon. However, the semicolon is optional, but probably confusing, when you break a single statement into multiple code lines.

document.write("Hello1");
document.write("Hello2");

//Semicolons are optional:
document.write("Hello3")
document.write("Hello4")

//This works too but only if you use a semicolon:
document.write("Hello5"); document.write("Hello6");

//Two lines also works:
document.write
("Hello7")
Posted By Mike Prestwood, Post #101690, KB Topic: Beginners Corner
-Collapse +Expand 6. JavaScript If Statement (if..else if..else)
 

Same as C/C++ but, as usual, the semicolons are optional.

var x = 8;
  
if (x == 10) {
 document.write("x is 10.");
} else if (x < 10) {
 document.write("x is less than 10."); 
} else {
 document.write("x must be greater than 10.");
}
Posted By Mike Prestwood, Post #101878, KB Topic: Beginners Corner
-Collapse +Expand 7. JavaScript Literals (quote or apostrophe)
 

Literals use either an apostrophe (also known as a single quote) as in 'Prestwood' or quoted as in "Prestwood". If you need to embed an apostrophe in an apostrophe-literal or a quote in a quoted-literal, preced it with a slash as in \' and \".

Alert("Hello");
Alert("Hello \"Mike\".")
  
Alert('Hello');
Alert('Hello Mike\'s website.')
 
//Does JavaScript evaluate this simple
//floating point math correctly? No! 
if ((.1 + .1 + .1) == .3) {
 document.write("Correct")
} else {
 document.write("Not correct")
}
Posted By Mike Prestwood, Post #101522, KB Topic: Beginners Corner
-Collapse +Expand 8. JavaScript Logical Operators
 

JavaScript logical operators:

and, && and, as in this and that
or, || or, as in this or that
!, Not Not, as in Not This

//Given expressions a, b, c, and d:
if !((a && b) && (c || d)) {
  //Do something.
}
Posted By Mike Prestwood, Post #101886, KB Topic: Beginners Corner
-Collapse +Expand 9. JavaScript Overview and History
 

Language Overview: Class-like language with limited but usable class-like and object-like functionality but no formal inheritance nor visibility control, etc.

Target Platforms: JavaScript is most commonly used to extend HTML by executing code on the browser side when visiting a website. It does have other uses including server side scripting and AJAX.

Posted By Mike Prestwood, Post #101721, KB Topic: Beginners Corner
-Collapse +Expand 10. JavaScript Report Tools Overview
 

No built-in report writer but because JavaScript most frequently targets website development (a document interfaced GUI), a common solution is to simply output an HTML formatted page with black text and a white background (not much control but it does work for some situations).

Posted By Mike Prestwood, Post #101902, KB Topic: Beginners Corner
-Collapse +Expand 11. JavaScript String Concatenation (+)
 

To concatenate two strings, a string to an integer, or a string to a floating point number, use the + operator. JavaScript performs implicit casting when concatenating a string and a number. For example, to convert a floating point number to a string just concatenate an empty string to the number as in "" + 3.2.

 
// -->
Posted By Mike Prestwood, Post #101591, KB Topic: Beginners Corner
-Collapse +Expand 12. JavaScript Unary Operators
 

An operation with only one operand (a single input). JavaScript unary operators include ++ and --. They can be used either before or after a variable as in: a++, b--, and ++a, and --b.

var iCounter=0;
 
for (iCounter=0;iCounter<=5;iCounter++)
{
document.write("Count is " + iCounter + "<br>");
}
Posted By Mike Prestwood, Post #101558, KB Topic: Beginners Corner
-Collapse +Expand 13. JavaScript Variables (var x = 0;)
 

JavaScript is a loosely typed language. Each variable is cast in usage as string, number, boolean, function, or object.

Variable names are case sensitive.

Alternatively, you can specify the value when you declare a variable:

var FirstName = "Mike";
var LastName = "Prestwood";
var Age = 42;
var FirstName;
var LastName;
var Age;
Posted By Mike Prestwood, Post #101566, KB Topic: Beginners Corner



Topic: JavaScript and AJAX

-Collapse +Expand 14. Associative Arrays in JavaScript
 

An associative array links a set of unique values (keys) to another set of values (not necessarily unique). Associative arrays are also known as a dictionary or a hash table in other languages.

//Initialize array.
var MyStateList= new Array()
 
//Assign values.
MyStateList["CA"]="California";
MyStateList["OR"]="Oregon";
MyStateList["NV"]="Nevada";
 
//Use array.
Alert("OR is " + MyStateList["OR"])
Posted By Mike Prestwood, Post #101202, KB Topic: JavaScript and AJAX
-Collapse +Expand 15. JavaScript Case Sensitivity (Yes)
 

JavaScript is case sensitive. Change the case, and it no longer works! Notice the "W" in "Write" is capitalized.

<script language=JavaScript> 
<!--
document.Write("Hello"); //Does not work!
//-->
</script>

Variable names are case sensitive.

This does work:

<script language=JavaScript> 
<!--
document.write("Hello");
//-->
</script>
Posted By Mike Prestwood, Post #101339, KB Topic: JavaScript and AJAX
-Collapse +Expand 16. JavaScript Code Blocks ({ })
 

Inhtml pages, you embed JavaScript code between <script> and </script> (see example). Also it's tradtional to put an HTML comment around your code too so that really old browsers don't crash (probably not all that important these days).

For JavaScript, Java, PHP, and C++, I prefer to put the first { at the end of the first line of the code block as in the example above because I see moreJavaScript codeformatted that way.

<script language="JavaScript" type="text/javascript">
<!--
function DisplayDialogLg(StrURL) {
}
if (x == -1) {
}
-->
</script>
Posted By Mike Prestwood, Post #101497, KB Topic: JavaScript and AJAX
-Collapse +Expand 17. JavaScript Event Handler
 

The JavaScript event handler contains events centered around the Document Object Model (DOM). Common events include onMouseOver and onMouseOut, onFocus and onBlur, onClick and onDblClick, onChange and onSelect, onLoad and onUnload.

For example, onMouseOver and onMouseOut are frequently used with websites to change an image when your mouse moves over it. The onClick event is used to trigger code upon a mouse click.

In the following example, we use a standard image tag set to an image, change it on mouse over, then set it back on mouse out.

<img id="Image1" src="i_search.gif"
 onmouseover="document.images['Image1'].src='i_coat.gif';"
 onmouseout="document.images['Image1'].src='i_search.gif';">
Posted By Mike Prestwood, Post #102046, KB Topic: JavaScript and AJAX
-Collapse +Expand 18. JavaScript Exception Trapping (try/catch/finally)
 

See "throw" to raise (throw) an error.

try {
  //Do something.
}
catch(e) {        //one or more.
  //Do something.
}
finally {         //0 or one.
  //Do something.
}
Posted By Mike Prestwood, Post #101367, KB Topic: JavaScript and AJAX
-Collapse +Expand 19. JavaScript File Extensions
 

.js is the common standard for browser-side JavaScript and .jsp is the common standard for server-side JavaScript.

Posted By Mike Prestwood, Post #101352, KB Topic: JavaScript and AJAX
-Collapse +Expand 20. JavaScript Inheritance (No, but sort of.)
 

JavaScript does not offer a formal inheritance machanism. There are some tricks some developers are fond of.

Posted By Mike Prestwood, Post #101393, KB Topic: JavaScript and AJAX
-Collapse +Expand 21. JavaScript Member Method
 

Not fully OOP as you can call the method outside of the class.

function Dog() {
  //Class variables here.

this.prototype.bark = function() {
//Class method code here.
}
}
Posted By Mike Prestwood, Post #101418, KB Topic: JavaScript and AJAX
-Collapse +Expand 22. JavaScript substr
 

Above returns "Mike P".

SubStr(StartIndex, NumberOfCharacters)

Notice JavaScript is 0 based (the first character is character 0).�0 is start character, 6 is number�of characters).�

You can also use substring where both numbers are indexes:

SubString(StartIndex, EndIndex)

The following returns "re".

var sName;
sName = "Mike Prestwood";
sName = sName.substring(6, 8);
document.write(sName);
var sName;
sName = "Mike Prestwood";
sName = sName.substr(0, 6);
document.write("Hello " + sName);
Posted By Mike Prestwood, Post #101372, KB Topic: JavaScript and AJAX
-Collapse +Expand 23. replaceAll
 

Implements replaceAll in javascript. This is achieved using prototype.js

Add this between the head tags (replace [[ with < and ]] with >):

[[script type="text/javascript" src="prototype.js"]] [[/script]]

Here's the code (replace [[ with < and ]] with >):

[[script type="text/javascript"]]
// define your replace all function like this 
String.prototype.replaceAll=function(s1, s2) 
{return this.split(s1).join(s2)}; 
// use your replaceAll function like this
var replacedText = text2replace.replaceAll("-what to replace-",
		" -with what to replace- "); 
[[/script]]
Posted By bhavyait, Post #100700, KB Topic: JavaScript and AJAX



Topic: Language Reference

-Collapse +Expand 24. JavaScript Associative Array (Array(), use [)
 

General Info: Associative Array

A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'

Languages Focus: Associative Array

Associative arrays are also known as a dictionary or a hash table in other languages.

JavaScript Associative Array

var MyStateList= new Array()
MyStateList["CA"]="California";
MyStateList["OR"]="Oregon";
Alert("OR is " + MyStateList["OR"])
Posted By Mike Prestwood, Post #101516, KB Topic: Language Reference
-Collapse +Expand 25. JavaScript Class..Object (Limited, class..new)
 

Creating classes in JavaScript is not really OOP, but rather a super type. That is, a type that has some class-like features but is missing the necessary OOP requirements.

There is nothing in Javascript to stop you from accessing the functions within your class outside of the class so this is not fully OOP but is usable.

//Class definition.
function Person() {
this.name = 'unknown';
this.age = 0;
}
 
//Use object created from class.
var Lisa = new Person();
Lisa.name='Lisa';
Lisa.age=28;
Posted By Mike Prestwood, Post #101402, KB Topic: Language Reference
-Collapse +Expand 26. JavaScript Custom Routines (function)
 

JavaScript uses functions and loosely typed parameters. Function definitions must come before their usage so the usual preference when adding JavaScript to HTML pages is to include them between the head tags.

function SayHello(pName) {
 document.write("Hello " + pName + "<br>");
}
 
function add(p1, p2) {
 var result;
 
 result = p1 + p2;
 return result;
}
Posted By Mike Prestwood, Post #101633, KB Topic: Language Reference
-Collapse +Expand 27. JavaScript Overloading
 

JavaScript Overloading

  • Operator - No.
  • Method -

 

Posted By Mike Prestwood, Post #101462, KB Topic: Language Reference



Topic: OOP

-Collapse +Expand 28. JavaScript Inheritance-Multiple (Not Supported)
 

There is a trick to fake one descendant class multiple inheritance. Not really worth exploring though but...inside a constructor, call another constructor function. The new object instance will inherit any properties and methods defined in that constructor. However, the new object will not inherit methods defined in the second constructor's prototype chain.

Posted By Mike Prestwood, Post #101447, KB Topic: OOP
-
  Load Time=less than 1 second.
 
Print This


-
 
Have a question? Need our services? Contact us now.
--Mike Prestwood

Call: 916-726-5675

email: info@prestwood.com


438 People Online Now!!  
Sign In to see who's online now!  Not a member? Join now. It's free!
Show more stats...
Follow PrestwoodBoards on: 


©1995-2014 PrestwoodBoards  [Security & Privacy]
Professional IT Services: Coding | Websites | Computer Tech