Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Friday, November 12, 2010

CoolTuts - JavaScript - Variable

You can create a variable with or without the var statemet.
var strname = some value

Scope of the Variable
  1. When you declare the variable within a function, the variable can only be accessed within that function.
  2. When you declare the variable outside the function, all the functions on your page can access it.
  3. The life time of these variables starts when they are declared, and ends when the page is closed.

Monday, November 8, 2010

CoolTuts - JavaScript - Event Handlers

By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript.

Every element on a web page has certain events which can trigger JavaScript functions. We define the events in the HTML tags.

Event handlers are not added inside the <script> tags, but rather, inside the html tags, that execute the JavaScript when something happens, such as pressing a button, moving mouse over a link, submitting a form.

Basic syntax of event handlers is:
name_of_the_handler = "JavaScript code"

Example:
<a href="www.google.com" onClick="alert("hello")">Google</a>

when user clicks on the link, it will prompt an alert box before being taken to Google.

Some of the most commonly supported eventhandlers:
onClick -- Invokes JavaScript upon clicking (a link, or form boxes)
onLoad -- Invokes JavaScript after the page or an image has finished loading
onMouseover -- Invokes JavaScript if the mouse passes by some link
onMouseout -- Invokes JavaScript if the mouse goes pass some link
onUnload -- Invokes JavaScript right after someone leaves this page

OnClick Event Handler: OnClick event handler is executed when an element is clicked. It can only be added to visible elements on the page such as <a>, form buttons, check boxes, a DIV etc.

OnLoad Event Handlers This is used to call the execution of JavaScript after a page, frame or image has completely loaded.

onMouseover, onMouseout
onMouseover and onMouseout event handleres can be added to visible elements such as a link (<a>), DIV, even inside the <BODY> tag, and are triggered when the mouse moves over and out of the element.

onMouseover and onMouseout events are often used to create "animated" buttons.

onUnload Event Handler onunload executes JavaScript immediately after someone leaves the page.

Applicability of Event Handlers
onAbort ---<img> tags
onBlur --- window object, all form objects
onClick---Most visible elements such as <a>, <div>, <body>
onChange---Use this to invoke JavaScript if mouse goes pass some link
onError --- Text fields,Text Areas
onFocus---Most visible elements such as <a>, <div>, <body>
onLoad---<body>, <img>, and <frame>
onMouseover---Most visible elements such as <a>, <div>, <body>
onMouseout---Most visible elements such as <a>, <div>, <body>
onReset --- <form> tag, triggered when the form is resent via <input type="reset">
onSelect --- Elements with textual content. Most commonly used inside text fields and text areas
onSubmit --- <form> tag, triggered when the form is submitted
onUnload --- <body>---Most visible elements such as <a>, <div>, <body>

The Onload event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

onFocus, onBlur and onChange
These events are often used in combination with validation of form fields.

OnSubmit
onSubmit event is used to validate All form fields before submitting it.

CoolTuts - JavaScript - Creating Interacitve Boxes

Three commands involved in creating alert, confirm, prompt boxes are:
  1. window.alert()
  2. window.confirm()
  3. window.prompt()

window.Alert()
This commands pops up a message displaying whatever you put in it. User will have to click "OK" to proceed.
window.confirm()
This commands is used to confirm a user about certain action, and decide between two choices depending on what the user chooses. User will have to click on "OK" or "Cancel" to proceed.
window.prompt()
This command is used to allow a user to enter something and do something with that information. User will have to click on "OK" or "Cancel" to proceed after entering an input value.

CoolTuts - JavaScript - Getting Started

JavaScript code is written anywhere inside the <html> tags of your page. The beginning of your code begins with

JavaScript is a language of objects, and all objects have both methods and properties. "Document" is just one of the many objects. It is the object that controls the layout of a webpage-background color, text, images etc.

Document Object has the following properties:
bgColor
lastModified
referrer
fgColor

CoolTuts - JavaScript - Introduction

It is a scripting language developed by Netscape to add interactivity and power to web documents.

You can only create Static webpages, using HTML. By using JavaScript, with HTML you can convert the webpages to Dynamic webpages.
Java is more powerfull language compared to Javascript. You need to compile java program before you run it, whereas with JavaScript, no compilation is needed. JavaScript is typed and saved in text editor and it runned using the Browser.


Every one can use JavaScript without purchasing a license.

A JavaScript is usually embedded directly into HTML pages.

Sunday, October 10, 2010

CoolTuts - JavaScript - Strings

Concatenating Strings: To concatenate strings we use '+' operator

public class exercise{
public static void main(String[] args)
{
String FirstString = "Abc"
String SecondString = "def"
String FinalString;
FinalString = FirstString + SecondString;
System.out.println("Cancatenated String "+ MyString);
}
}

Length of the String: Returns the number of characters in the String.
String myStr = "abc"
System.out.println("Length of the string "+myStr.length());

IndexOf: Returns the position of the character in the String
String myStr = "abcdefg"
System.out.println("Position of the character "+myStr.IndexOf("c"));//Returns 2
System.out.println("Position of the character "+myStr.IndexOf("z"));//Returns -1 as character is not present in string

Tuesday, August 31, 2010

Validating form input using JavaScript

Forms are widely used on the Internet. The form input is often being sent back to the server. But how can you be certain that a valid input was done by the user? With the help of JavaScript the form input can easily be checked before sending it over the Internet.

Here it goes Firstle lets not give chance to enter empty fields.

Validation for Blank fields

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>

<script type="text/javascript">
function Verify(){
if(document.getElementById('uidTextBox').value.length==0)
alert("UserId can't be blank");
else if(document.getElementById('pwdTextBox').value.length==0)
alert("Password can't be blank");
else
{
alert("successfully logged in");
window.open("http://www.cooltuts.com/");
}
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<p><asp:TextBox ID="uidTextBox" runat="server" /></p>
<p><asp:TextBox ID="pwdTextBox" runat="server" /></p>
<p><asp:Button ID="btnSubmit" OnClientClick="Verify()" runat="server" Text="Button" /></p>
</div>
</form>
</body>
</html>


Email validation

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>

<script type="text/javascript">
function Verify(){
if(document.getElementById('emailTextBox').value.length==0)
alert("Email can't be blank");
else if((/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('emailTextBox').value))==false)
alert("Email Not in Correct Format");
else
{
alert("successfully logged in");
window.open("http://www.cooltuts.com/");
}
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<p><asp:TextBox ID="emailTextBox" runat="server" /></p>
<p><asp:Button ID="btnSubmit" OnClientClick="Verify()" runat="server" Text="Button" /></p>
</div>
</form>
</body>
</html>

Saturday, August 28, 2010

JavaScript Functions

Functions

We will use functions in most of our JavaScript programs. Therefore I will talk about this important concept already now. Basically functions are a way for bundling several commands together. Let’s write a script which outputs a certain text three times. Consider the following
approach:

<html>
<script language="JavaScript">

<!-- hide

document.write("Welcome to my homepage!<br>");
document.write("This is JavaScript!<br>");

document.write("Welcome to my homepage!<br>");
document.write("This is JavaScript!<br>");

document.write("Welcome to my homepage!<br>");
document.write("This is JavaScript!<br>");

// -->
</script>
</html>

This will write out the text

Welcome to my homepage!
This is JavaScript!

three times. Look at the source code - writing the code three times brings out the right result.
But is this very efficiently? No, we can solve this better. How about this code which does the same:

<html>
<script language="JavaScript">
<!-- hide

function myFunction() {

document.write("Welcome to my homepage!<br>");

document.write("This is JavaScript!<br>");
}

myFunction();
myFunction();
myFunction();

// -->
</script>
</html>

In this script we define a function. This is done through the lines:

function myFunction() {

document.write("Welcome to my homepage!<br>");

document.write("This is JavaScript!<br>");
}

The commands inside the {} belong to the function myFunction(). This means that our two do- cument.write() commands are bundled together and can be executed through a function call. In our example we have three function calls. You can see that we write myFunction() three times

just below the definition of the function. These are the three function calls. This means that the contents of the function is being executed three times. This is a very easy example of a function.
You might wonder why functions are so important. While reading this tutorial you will certainly realize the benefits of functions. Especially variable passing makes our scripts really flexible we will see what this is later on.

Functions can also be used in combination with event-handlers. Please consider this example:

<html>
<head>

<script language="JavaScript">
<!-- hide

function calculation() {

var x= 12;

var y= 5;

var result= x + y;

alert(result);
}

// -->
</script>

</head>
<body>

<form>
<input type="button" value="Calculate" onClick="calculation()">
</form>

</body>
</html>

(The online version lets you test this script immediately)

The button calls the function calculation(). You can see that the function does certain calculations. For this we are using the variables x, y and result. We can define a variable with the keyword var. Variables can be used to store different values -like numbers, text strings etc. The line var result= x + y; tells the browser to create a variable result and store in it the result of x + y (i.e. 5 + 12). After this operation the variable result is 17. The command alert(result) is in this case the same as alert(17). This means we get a popup window with the number 17 in it.

Javascript Events

Events and event handlers are very important for JavaScript programming. Events are mostly caused by user actions. If the user clicks on a button a click-events occurs. If the mousepointer moves across a link a Mouseover-event occurs. There are several different events. we want our JavaScript program to react to certain events. This can be done with the help of event-handlers. A button might create a popup window when clicked. This means the window should pop up as a reaction to a Click-event. The event-handler we need to use is called onClick. This tells the computer what to do if this event occurs. The following code shows an easy example of the event-handler onClick:

<form>
<input type="button" value="click me" onClick="alert('Yo')">
</form>

There are a few new things in this code - so let’s take it step by step. You can see that we create a form with a button (this is basically a HTML-problem so I won’t cover it here). The new part is onClick="alert(’Yo’)" inside the <input> tag. As we already said this defines what happens when the button is pushed. So if a Click-event occurs the computer shall execute alert(’Yo’).
This is JavaScript-code (Please note that we do not use the <script> tag in this case). alert() lets you create popup windows. Inside the brackets you have to specify a string. In our case this is ’Yo’. This is the text which shall be shown in the popup window. So our script creates a window with the contents ’Yo’ when the user clicks on the button.
One thing might be a little bit confusing: In the document.write() command we used double quotes" and in combination with alert() we use only single quotes ’ -why? Basically you can use both. But in the last example we wrote onClick="alert(’Yo’)" - you can see that we used both double and single quotes. If we wrote onClick="alert("Yo")" the computer would get confused as it isn’t clear which part belongs to the onClick event-handler and which not. So you have to alternate with the quotes in this case. It doesn’t matter in which order you use the quotes - first double quotes and then single quotes or vice versa. This means you can also write onClick=’alert("Yo")’.

There are many different event-handlers you can use. We will get to know some during this tutorial- but not all. So please refer to a reference if you want to know what kind of other event-handlers do exist.

If you are using the Netscape Navigator the popup window will contain the text JavaScript alert. This is a security restriction. You can create a similar popup window with the prompt() method. This window accepts an input. A malicious script could imitate a system message and ask for a certain password. The text in the popup window shows that the window comes from your web browser and not from your operating system. As this is a security restriction you cannot remove this message.

Friday, August 27, 2010

Hiding JavaScript Statements from Older Browsers

Browsers that were distributed before the script tag was invented will correctly ignore tags they do not "understand" such as the script tag. However, the JavaScript statements in between the script tags will appear to these browsers as plain text. Most often older pre JavaScript browsers will therefore render the JavaScript statements as paragraph text. This can be quite alarming if a nicely designed page suddenly appears to someone as a long stream of meaningless code.

To get around this, the code can be hidden inside an HTML comment tag. An HTML comment tag looks like this:

<--This is a comment.-->

The opening <-- part of the tag is usually placed on the next line right after the opening <SCRIPT> tag and the closing part of the comment tag on the line just before the closing </SCRIPT> tag. Just to make things more complicated the closing part of the HTML comment tag must be preceded by the // characters that precede a JavaScript comment. Here is a short example:

<SCRIPT Language="JavaScript">
<!--


// -->
</SCRIPT>

JavaScript statements are placed on the line after the <!-- and on lines before the // -->


Thursday, August 26, 2010

The Difference Between HTML and JavaScript

When the browser is reading in a HTML document it needs to be able to determine what text is HTML and therefore what to display in the browser window, and what text is JavaScript source code to be interpreted and executed. One way to let a browser know that part of an HTML document is JavaScript is to enclose it inside the HTML <SCRIPT></SCRIPT> tags as illustrated above. A browser that knows how to interpret Javascript will attempt to interpret text inside the script tags while reading and displaying HTML elements correctly.

Script tags are most often placed inside the head or body tags but may also be placed inside other elements. Not every version of every browser correctly interprets JavaScript code when script tags are placed inside other HTML elements such as table data cells.

JavaScript Statements and Source Code

The JavaScript text is often referred to as "source code" or just "code" and is made up of statements. In the example first javaScript post these two JavaScript statements:

document.write("<P>Script tags can be placed ")
document.write("in the Head of an HTML document.</P>")

write some text, considering of an HTML paragraph, into the Web page being loaded by the browser. The first statement writes the first half of the paragraph and the second writes the last half. A full description of the parts of these statements is provided later but the net effect is to make the text:

<P>Script tags can be placed in the Head of an HTML document.</P>

part of the HTML document.

Wednesday, August 25, 2010

Placing Javascript Statements inside HTML Documents

JavaScript programing statements (source code) made only be placed in certain locations within HTML documents. When a browser with a JavaScript interpreter reads the JavaScript code it can interpret and execute it so that some scripting task is completed. The simple document below shows JavaScript source code placed within HTML <SCRIPT></SCRIPT>

<HTML>
<HEAD>
<TITLE> </TITLE>
<SCRIPT>
document.write("<P>Script tags can be placed ")
document.write("in the Head of an HTML document </P>")
<SCRIPT>
</HEAD>

<BODY>
<H1>The Script Tag: Example 1</H1>
<P>Script tags can also be placed in the Body of an HTML document.</P>

<SCRIPT>
document.write("<P>Script tags will be ignored by ")
document.write("browsers that do not understand them.</P>")
</SCRIPT>

</BODY>
</HTML>

Friday, August 6, 2010

JavaScript Introduction

This Post is an introduction to Javascript.

What is JavaScript

Javascript is a new scripting language which is being developed by Netscape. With Javascript you can easily create interactive web-pages. This tutorial shows you what can be done with Javascript - and more importantly how it is done.

Javascript is not Java!

Many people believe that Javascript is the same as Java because of similar names. This is not true though. I think it would go too far at the moment to show you all the differences - so just memorize that Javascript is not Java.

Tuesday, May 4, 2010

CoolTuts - JavaScript - JavaScript Comments

JavaScript single line Comments
Comments can be added JavaScript, to make the code more readable.
Single line comments start with //.

JavaScript multiple line Comments
Multi line comments start with /* and end with */.