IT SOLUTIONS
Your full service technology partner! 
-Collapse +Expand
JavaScript
Search JavaScript Group:

Advanced
-Collapse +Expand JavaScript Store

Prestwood eMagazine

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

   ► KBJavaScript Knowledge Base  Print This    All Groups  

JavaScript Flashcards Library

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

Contribute a Flashcard

35 JavaScript and AJAX FlashCards

Group: JavaScript and AJAX


Topic: Beginners Corner

Q&A: Close Browser with JavaScript
Question: How do you close a browser in a link?

Answer:

You can do close a browser using JavaScript. Here is an example:

javascript:self.close()

Posted By Mike Prestwood, Post #100907, KB Topic: Beginners Corner
Q&A: Hide JavaScript Code
Question: How do I protect my javascript code?

Answer:

In the main you don't, as the language is ran from source, you need to deliver the source code, with JScript, there is the Script Encoder (see MSDN) but this is nothing more than obfuscation in effect, disabling the Right Mouse button, also achieves nothing to protect your script in a web browser. Your code is likely protected under copyright laws.
Posted By Mike Prestwood, Post #100905, KB Topic: Beginners Corner
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
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
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
Q&A: JavaScript Defined
Question: What is JavaScript?

Answer:

JavaScript is a platform-independent, event-driven, interpreted programming language developed by Netscape Communications Corp. and Sun Microsystems. Originally called LiveScript (and still called LiveWireTM by Netscape in its compiled, server-side incarnation), JavaScript is affiliated with Sun's object-oriented programming language JavaTM primarily as a marketing convenience. They interoperate well but are technically, functionally and behaviorally very different.

JavaScript is useful for adding interactivity to the World Wide Web because scripts can be embedded in HTML files (i.e., web pages) simply by enclosing code in a tag pair. All modern browsers can interpret JavaScript -- albeit with some irritating caveats. (More about them below.)

In practice, JavaScript is a fairly universal extension to HTML that can enhance the user experience through event handling and client-side execution, while extending a web developer's control over the client's browser. And that's worth a FAQ.

Posted By Mike Prestwood, Post #100902, KB Topic: Beginners Corner
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.

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
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
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
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
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.

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).

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
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
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

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
Q&A: Browser Size
Question: How do you specify the browser size of a window in a link?

Answer:

You can do this using JavaScript. Here is an example:

javascript:MM_openBrWindow('http://www.prestwood.com/shop/purchase_orders.html', 'compare', 'scrollbars=no, resizable=no, width=600, height=420')

Posted By Mike Prestwood, Post #100906, KB Topic: JavaScript and AJAX
Definition

JavaScript

Definition: JavaScript is a platform-independent, event-driven, interpreted programming language developed by Netscape Communications Corp. and Sun Microsystems. Originally called LiveScript (and still called LiveWireTM by Netscape in its compiled, server-side incarnation), JavaScript is affiliated with Sun's object-oriented programming language JavaTM primarily as a marketing convenience. They interoperate well but are technically, functionally and behaviorally very different.
Posted By Mike Prestwood, Post #100903, KB Topic: JavaScript and AJAX
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
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
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
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
JavaScript File Extensions

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

JavaScript Inheritance (No, but sort of.)

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

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
Q&A: JavaScript Similiar to C
Question: How is JavaScript syntax like C / C++?

Answer:

The languages have enough in common to make learning one easy if you know the other. By the same token, the differences are subtle enough to trip up those proficient in both. Here's a short list comparing C and JavaScript:
  • Terminating JavaScript command lines in semicolons is optional; in C it's mandatory. Recommended practice is to use them religiously in both languages (and Java as well).
  • Both JavaScript and C are case-sensitive; 'doThis' is different from 'DOTHIS'. Experienced programmers learn to love this feature, which drives beginners nuts.
  • Both JavaScript and C are block-structured computer languages and employ curly brackets -- '{' and '}' -- to delimit blocks.
  • Both JavaScript and C employ quotation -- enclosure in single or double quote marks -- to designate text strings.
  • Arrays in both JavaScript and C are zero-based; the first element is myArray[0], not myArray[1].
  • Both JavaScript and C employ '==' for comparison, '=' for equality, and '!' for negation. In fact the set of JavaScript operators is essentially borrowed from C (right down to the deprecated ternary construct a ? b : c).
  • Both JavaScript and C employ the symbols /* to designate a comment */. JavaScript also permits the use of '//' for short comments, as in C++.

Finally, JavaScript's statements are a strict subset of C++'s, offering a smaller selection of identical looping and conditional constructs.

Posted By Mike Prestwood, Post #100904, KB Topic: JavaScript and AJAX
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
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
Q&A: Share data From ASP To JavaScript
Question: How do you pass values from ASP to Javascript in the same page?

Answer:

The same way you do with HTML. Here is a simple example:

<%
Dim MyName
MyName = "Mike Prestwood"
%>
<script language="javascript">
<!--
document.write('Hi <%=MyName%>')
-->
</script>
Posted By Mike Prestwood, Post #100796, KB Topic: JavaScript and AJAX



Topic: Language Reference

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
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
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
JavaScript Overloading

JavaScript Overloading

  • Operator - No.
  • Method -

 

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



Topic: OOP

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.

Go ahead!   Use Us! Call: 916-726-5675  Or visit our new sales site: 
www.prestwood.com


©1995-2020 Prestwood IT Solutions.   [Security & Privacy]