02/10/2014

JavaScript Errors: Throw and Try to Catch

The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch, regardless of the result.
Errors Will Happen!
When executing JavaScript code, different errors can occur. Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things:
Example
<body>
<p id="demo"></p>
<script>
try {
adddlert("Welcome
guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
In the example above we have made a typo in the code in the try block
The catch block catches the error, and executes code to handle it:
JavaScript try and catch
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The JavaScript statements try and catch come in pairs:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
JavaScript Throws Errors
When an error occurs, JavaScript will normally stop and generate an error message. The technical term for this is:
JavaScript will throw an error. The throw Statement The throw statement allows you to create a custom error. The technical term for this is:
throw an exception.
The exception can be a JavaScript String, a Number, a Boolean or an Object:
throw"Too big"; // throw a text
throw500; // throw a number
If you use throw together with try and catch, you can control program flow and generate custom error messages.
Input Validation Example
This example examines input. If the value is wrong, an exception (err) is thrown. The exception (err) is caught by the catch statement and a custom error message is displayed:
<body>
<p>Please input a number between 5 and 10:</p>
<inputid="demo"type="text">
<buttontype=
"button"onclick=
"myFunction()">Test Input</button>
<pid="message"></p>
<script>
function myFunction() {
var message, x
message =
document.getElementById("message");
message.innerHTML = ""; x =
document.getElementById("demo").value;
try {
if(x == "") throw "is
Empty";
if(isNaN(x)) throw "not a number";
if(x > 10) throw "too high";
if(x < 5) throw "too low";
}
catch(err) {
message.innerHTML =
"Input " + err;
}
}
</script>
</body>
The finally Statement
The finally statement lets you execute code, after try and catch, regardless of the result:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result }

01/10/2014

JavaScript String Methods

String methods help you to work with strings.
Finding a String in a String
The indexOf() method returns the index of the position of the 1st occurrence of a specified text in a string:
Example:
<body>
<p id="p1">Please locate where 'locate' occurs!</p>
<button onclick="myFunction()">read it</button>
<p id="demo"></p>
<script>
function myFunction() { var str =
document.getElementById("p1").innerHTML;
var pos =
str.indexOf("locate");
document.getElementById("demo").innerHTML = pos;
}
</script>
</body>
The last IndexOf()method returns the index of the last occurrence of a specified text in a string:
Example
<body>
<p id="p1">Please locate where 'locate' occurs!</p>
<button onclick="myFunction()">read it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str =
document.getElementById("p1").innerHTML;
var pos =
str.lastIndexOf("locate"); document.getElementById("demo").innerHTML = pos;
}
</script>
</body>
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found. JavaScript counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is the third......
Both methods accept a second parameter as the starting position for the search.
Searching for a String in a String
The search()method searches a string for a specified value and returns the position of the match:
Example:
<body>
<p id="p1">Please locate where 'locate' occurs!</p>
<button onclick="myFunction()">read it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str =
document.getElementById("p1").innerHTML;
var pos =
str.search("locate");
document.getElementById("demo").innerHTML = pos;
}
</script>
</body>
Did You Notice?
The two methods, indexOf() and search(), are equal. They accept the same arguments (parameters) and they return the same value.
The two methods are equal, but the search() method can take much more powerful search values.

JavaScript Strings

A JavaScript string simply stores a series of characters like "John Elwin". A string can be any text inside quotes. You can use single or double quotes:
Example:
<body> <p id="demo"></p> <script> var carName1 = "Volvo XC60"; var carName2 = 'Volvo XC60'; document.getElementById("demo").innerHTML = carName1 + " " + carName2; </script> </body>
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example:
<body> <p id="demo"></p> <script> var answer1 = "It's alright"; var answer2 = "He is called 'John'"; var answer3 = 'He is called "John"'; document.getElementById("demo").innerHTML = answer1 + "<br>" + answer2 + "<br>" + answer3; </script> </body>
Or you can put quotes inside a string by using the \ escape character:
Example:
<body> <p id="demo"></p> <script> var answer1 = 'It\'s alright'; var answer2 = "He is called \"John\""; document.getElementById("demo").innerHTML = answer1 + " " + answer2; </script> </body>
String Length
The length of a string is found in the built in propertylength:
Example:
<body> <p id="demo"></p> <script> var txt= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; document.getElementById("demo").innerHTML = txt.length; </script> </body>
Special Characters
In JavaScript, strings are written as characters inside single or double quotes. Because of this, JavaScript will misunderstand this string:
"We are the so-called "Vikings" from the north"
The string will be chopped to "We are the so-called"
To solve this problem, you can place a backslash (\) before the double quotes in "Vikings": "We are the so-called \"Vikings\" from the north." The backslash is an escape character. Escape characters turns special characters into string characters: The escape character (\) can be used to insert a postrophes, new lines, quotes, and other special characters into a string. The table below lists other special characters that can be added to a text string with the backslash sign:
Code Table
Inputs Output
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
String Properties
Property Table
Property Description
constructor Returns the function that created the String object's prototype
length Returns the length of a string
prototype Allows you to add properties and methods to an object

JavaScript Events

HTML events are things that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can react on these events.
HTML Events
An HTML event can be something the browser does, or something a user does. Here are some examples of HTML events:
*An HTML web page has finished loading
*An HTML input field was changed
*An HTML button was clicked often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected. HTML allows event handler attributes,with JavaScript code, to be added to HTML elements.
With single quotes:

<some-HTML-elementsome-event='some JavaScript'>
With double quotes:
<some-HTML-elementsome-event="some JavaScript">
In the following example, an onclick attribute with code, is added to a button element:
Example:
<body>
<button onclick=
"getElementById('demo').innerHTML=Date()">The time is?</button>
<p id="demo"></p>
</body>
In the example above, the JavaScript code changes the content of the element with id="demo".
In the next example, the code changes the content of it's own element usingthis.innerHTML:
Example:
<body>
<button onclick=
"this.innerHTML=
Date()">The time
is?</button> </body>
JavaScript code is often several lines long. It is more common to see event attributes calling functions:
Example:
<body>
<button onclick=
"this.innerHTML=
Date()">The time
is?</button>
</body>
<body>
<button onclick=
"displayDate()">The time
is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
Common HTML Events
Here is a list of some common HTML events:
Event List
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
What can JavaScript Do?
Event handlers can be used to handle, and verify, user input, user actions, and browser actions:
*Things that should be done every time a page loads
*Things that should be done when the page is closed
*Action that should be performed when a user clicks a button
*Content that should be verified when a user input data
Many different methods can be used to let JavaScript work with events:
*HTML event attributes can execute JavaScript code directly
*HTML event attributes can call JavaScript functions
*You can assign your own event handler functions to HTML elements
*You can prevent events from being sent or being handled