JavaScript for Beginners (reprint) _ Basics

Source: Internet
Author: User
Tags html tags list of attributes

Note: I edited the original text, some words to mark the color, easy to read. Originally prepared to translate, but feel that the article is simple and understandable, and the original written very well, so it is not shortcoming. Hopefully it will be helpful for JavaScript beginners. You can follow the author to do the sample code, and when you finish reading the article, you will be able to master the basics of JavaScript, you will find in fact it is easy.

Contents
Embedding and including
Write and Writeln
Document Object
message box
Function
Event Handler
Form
Link
Date
Window
Frame

embedding and including

Let ' s-a simple example:

< html >


< head >


< title > This is a JavaScript example </ title > /c0>


< script language = "JavaScript" >
<!--
" hello world! );
//-->
</ script >
</ head >
< body >  hi,  man!  </ body >
</ html >

Usually, JavaScript code starts with the tag <script language= ' JavaScript ' > and ends with the tag </ Script>. The code placed between and Sometimes, people embed the code in the <body> Tags:

< html >


< head ></ >
< body >
< script >
... //  the  code embedded in the <body> tags.
</ script >
</ body >
</ html >

Why do we place JavaScript code inside comment fields <!-- and //--> ?
It's for ensuring that the Script isn't displayed by old browsers that does not support JavaScript. This is optional, but considered good practice. The LANGUAGE attribute also is optional, but recommended. You may specify a particular version of JavaScript:

< script language = "JavaScript1.2" >

Can use another attributes SRC to include a external file containing JavaScript code:

< script language = "JavaScript" src = "hello.js" ></ script >

For example, shown below is the code of the external file hello.js:

document.write ("Hello world!")

The external file is simply a-text file containing JavaScript code with the file name extension ". js".

Note:

    1. including an external file only functions reliably across platforms n the version 4 browsers.
    2. The code can ' t include tags <script language...> and </script>, or you'll get a error mes Sage.

Write and Writeln

In order to output text in JavaScript with must use write () or writeln (). Here ' s a example:

< HTML >


< head >


< title > Welcome to i site </ title ></ head >


< body >
< script  LANGUAGE = "JAVASCRIPT" >
<!--
" welcome to my site! );
//  -->
</ SCRIPT >
</ body >
</ HTML >

Note:the Document Object write is in lowercase as JavaScript's case sensitive. The difference between write and writeln is: write just outputs a text, writeln output s the text and a line break.

Document Object

The document object is one of the most important objects of JavaScript. Shown below is a very simple JavaScript code:

document.write ("Hi there.")

In here code, the document is the object. The write is the method by this object. Let's have a look at some's the other methods that document object possesses.

LastModified

You can always include the ' last update date ' your page by using the following code:

< script language = "JavaScript" >
document.write ( "This page created by John N. Last update: " + document.lastmodified" ;
</ Script >



All your need to do are use the LastModified property of the document. Notice so we used to put the + together this page created by John N. Last update: and document.write .

bgcolor and Fgcolor

lets try playing around with bgcolor and fgcolor:

< script >
Document.bgcolor = " black "
Document.fgcolor = " #336699 "
</ Script >






Message Box

Alert

There are three message boxes: alert, confirm, and prompt. Let's look at the one:

< body >
< script >
Window.alert ( " Welcome to my site! " )
</ Script >
</ body >



can put whatever you want inside the quotation marks.

Confirm

An example for Confirm box:

Window.confirm ("Are you sure your want to quit?")

Prompt

Prompt box is used to allow a user to enter something according the promotion:

window.prompt ("Please enter user name")



in all our examples above, we wrote the box methods as Window.alert (). Actually, we could simply write the following instead as:
Alert ()
Confirm ()
Prompt ()



Variables and Conditions

Let ' s-an example:

< script >
var  x = window.confirm (" Are you sure you want to quit )

if Font size= "2" >   (x)
    window.alert ( Thank  you. )
else
    window.alert ( Good choice. )
</ script >

there are several concepts that we should know. The var x = is a variable declaration. If you are want to create a variable, you must declare the variable using the var statement.  ; x 'll get the result, namely, true or false  . Then we use a condition statement if else to give the script the ' ability to choose between TW o paths, depending on this result (condition for the following action). If The result is true (the user clicked "OK"), "Thank You" appears in the Window box. If is False (the user clicked "Cancel"), the "Good choice" appears in the window box instead. So we can do more complex boxes using Var, if and those basic methods.

< script >
var y = window.prompt ( "Please enter your name " )
Window.alert (y)
</ Script >

Another Example:  

< html >< head >


< script >


var x = confirm ( " Are you sure your want to quit?" " )
if ( ! x)
Window.location = " http://www.yahoo.com "
</ script >
</ head >
< body >
welcome to my website!.
</ body ></ html >

If you click "Cancel", it would take you to Yahoo, and clicking OK would continue with the loading of the ' current page ' Welcometo my website! ". Note: if (!x) means:if click "Cancel". In JavaScript, the exclamation mark ! means: "none".

Function

Functions are chunks of code. Let ' s create a simple function:

function test ()
{
document.write ("Hello can you to me?")
}

Note ' If ' this is were within your <script> </script> tags, you are not "Hello can What do you do with me? " On your screens because functions are not executed by themselves until with call upon them. So we should do something:

function test ()
{
document.write ("Hello can you to me?")
}
Test ()

Last line test () calls the function and now you'll have the words "Hello can you"?

Event Handler

What are event handlers? They can is considered as triggers that execute JavaScript then something happens, such as click or move your mouse over a Link, submit a form etc.

OnClick

OnClick handlers execute something only if users click on buttons, links, etc. Let ' s-an example:

< script >
function SS ()
{
Alert ( " Thank you! " )
}
</ Script >
< form >
< input type = "button" value = "Click here" onclick = "ss ()" >
</ form >



The function SS () is invoked the user clicks the button. Note:event handlers are not added inside the <script> tags, but rather, inside the HTML tags.

OnLoad

The onload event handler is used to call the execution of JavaScript after loading:

< body onload = "ss ()" >
< frameset onload = "ss ()" >
< img src = "whatever.gif" onload = "ss ()" >

Onmouseover,onmouseout

These handlers are used exclusively with links.

< a href = "#" onMouseOver = "document.write (' Hi, nice to" you! " > over here! </ a >
< a href = "#" onmouseout = "alert (' Good try! ')" > Get out here! </ a >

OnUnload

OnUnload executes JavaScript while someone leaves the page. For example to thank users.

< body onunload = "alert" (' Thank for visiting us. Soon ') >

Handle Multiple Actions

How does you have a event handler call multiple functions/statements? That ' s simple. You are just need to embed the functions inside the event handler as usual, but separate each of them using a semicolon:

< form >
< input type = "button" value = "click here!" OnClick = "alert (' for visiting my site! '); window.location= ' http://www.yahoo.com ' " >
</ form >


Form

Let ' s say your have a form like this:

< form  name = "AA" >
< input  type = "text"  size = ""  value = ""  name = "BB" >< br >
| Font face= "Verdana" > < input  type = "button" value = "Click here" onclick = "alert (document.aa.bb.value) " >
</ form >

Notice that we gave the names to the form and the element. So JavaScript can gain access to them.

OnBlur

If you are want to get information from the users and want to check each element (ie:user name, password, email) individually , and alert the user to correct the wrong input before moving on, can use OnBlur. Let ' s and how OnBlur works:

< HTML >
< Head >
< script >


function Emailchk ()
{
var x = Document.feedback.email.value
if (X.indexof ( " @ " ) ==- 1 )
{
Alert ( " It seems you entered a invalid email address. " )
Document.feedback.email.focus ()
}
}
</ script >
</ Head>



< body >


< Form
name = "Feedback" >


Email: < input type = "text" size = "" name = "Email"
onblur = "Emailchk ()" >< BR >
comment:  < textarea  The name = "comment"  rows = "2"  cols = "" ></ textarea >< br >
< input  type = "Submit"   Value = Submit >
</ form >
</ body </ html >



If You enter a email address without The @, you'll get a alert asking you to re-enter the data . What is: x.indexof ("@") ==-1? This is the JavaScript can search every character within a string and look for what we want. If it finds it would return the position of the char within the string. If it doesn ' t, it'll return-1. Therefore, x.indexof ("@") ==-1basically means: "If the string doesn ' t include @, then:

Alert ("It seems you entered a invalid email address.")
Document.feedback.email.focus ()

What ' s Focus () ? This is the text box that which basically forces the cursor to being at the specified text box. onsubmit Unlike onblur, onsubmit handler are inserted inside the <form> tag, and not inside any one elem Ent. Lets do a example:

< script >


<!--


function Validate ()
{
if (document.login.userName.value = = "" )
{
Alert ( "Please enter User Name " )
Return false
}
if (document.login.password.value = "" )
{
Alert ( "Please enter Password " )
return false
}
}
-->
</ Script >



< form  name = "Login"   OnSubmit = "return validate ()" >
< input type = "text" size = "name" = "UserName" > /c6>
< input type = "text" size = "M" name = "password" >
< input type = "Submit" name = "Submit" value = "Submit" >
</ form >



Note:
if (document.login.username.value== ""). This means ' If the box named UserName of the form named login contains nothing, then ... ' . return FALSE. This is used to stop the form from submitting. By default, a form would return true if submitting. return validate () That means, "if submitting, then called" Function Validate () " .

Protect a file by using Login

Let ' s try an example

< html >< head >


< SCRIPT Language = "JavaScript" >


function checklogin (x)
{
if ((x.id.value != " Sam " ) | | (x.pass.value != " Sam123 " ) ))
{
Alert ( " Invalid Login " );
Return false ;
}
Else
location = " main.htm "
}
</ script >



</ head >< body >


< form >


< p > UserID: < input type = "text" name = "id" ></ P >
< p > Password: < input type = "Password" name = "Pass" ></ p >
< p >< input type = "button" value = "Login" onClick = "Checklogin" (t His.form) " ></ P >
</ form >
</ body ></ html >



|| means "or", and, != indicates "Not equal". So we can explain the script: "If the ID does not equal ' Sam ', or the password does 'equal '", Sam123 Show An alert (' Invalid Login ') and stop submitting. Else, open the page ' main.htm '.
 

Link

In most cases, a form can is repaced by a link:

< a href = "JavaScript:window.location.reload ()" > click to reload! </ a >

More Examples:      

< a href = "#" onClick = "alert (' Hello, world! ')" > Click me to say Hello </ a >< br >



< a href = "#" onMouseOver = "location= ' main.htm '" > Mouse over to the main Page ;/ a >


Date

Let ' s-an example:

< HTML >< head >< TITLE > Show
Date </ TITLE ></ head >
< body >
< script  LANGUAGE =" JavaScript " >
var  x =   new  date ();
document.write  (x);
</ SCRIPT >
</ body ></ HTML >

To activate a date Object and can do this: var x = new Date (). Whenever you want to create a instance of the date object, use this important word: new followed by the Object Name ().

dynamically display different pages

can display different pages according to the different time. This is example:

var bantime= new Date ()
var ss=bantime.gethours ()
if (ss < =12 )
document.write ("= ' banner1.gif ' > ")
Else
document.write (" < img src = ' banner2.gif ' > ")
 
Date Object
Methods
GetDate
GetTime
getTimezoneOffset
Getday
GetMonth
GetYear
Getseconds
Getminutes
GetHours

Window

Open a window

to open a window, simply use the method "window.open ()":

< form >
< input type = "button" value = "Click here to" " onclick =" window.open (' test.htm ') ' >
</ form >


You can replace the test.htm with the any URL, for example, with http://www.yahoo.com

Size, toolbar, menubar, scrollbars, location, status

Let's add some of attributes to the above script to control the size of the window, and show: toolbar , scrollbars etc. The syntax to add attributes is:

Open ("URL", "name", "Attributes")

For Example:

< form >
< input type = "button" value = " click here to"
onclick = "window.open (' page2.htm ', ' win1 ', ' Width=200,height=200,menubar ')" >
</ form >

Another example with no attributes turned on, except the size changed:

< form >
< input type = "button" value = " click here to"
onclick = "window.open (' page2.htm ', ' win1 ', ' width=200,height=200 ')" >
</ form >

This is the complete list of attributes you can add:
Width Height Toolbar
Location Directories Status
ScrollBars Resizable MenuBar



Reload

to reload a Windows, Use this method:
   
Window.location.reload ()

Close Window

Your can use one of the codes shown below:

< form >
< input type = "button" value = "Close Window" onClick = "Window.close ()" > /c16>
</ form >
< a href = "javascript:window.close ()" > Close window </ a >
 

Loading

The basic syntax when loading new content to a window is:

window.location= "Test.htm"

This is the same as

< a href = "Test.htm>try this </a>

Let's provide an example, where a confirm box would allow users to choose between going to two:

< script >


<!--


function SS ()
{
var ok = confirm (' Click ' OK ' to go to Yahoo, " cancel " To go to Hotmail ')
if (OK)
Location = " http://www.yahoo.com "
Else
location = " http://www.hotmail.com "
}
-->
</ Script >
 

Remote Control Window

Let's say you have opened a new window to the current window. After this, you'll wonder how to make a control between the two windows. To does this, we need to the "a" to "window". Look at below:

aa=window.open (' test.htm ', ', ', ' width=200,height=200 ')

by giving this window a name "AA", it would give you access to anything that ' s inside the this window from the other W indows. Whenever we want to access anything that's inside this newly opened windows, for example, to write to this window, we would Do this: aa.document.write (' This is a test. ').

Now, let's ' s an example the background color of another window:

< html >< head >< title ></ title ></ Head >


< body >


< form >


< input type = "button" value = "Open another page"


OnClick = "Aa=window.open (' test.htm ', ', ', ' width=200,height=200 ')" >


< input  type = "Radio"  name = "x"   OnClick = "aa.document.bgcolor= ' Red" >
< input type = "Radio" name = "x" onClick = "aa.document.bgcolor= ' green '" > /c9>
< input type = "Radio" name = "x" onClick = "aa.document.bgcolor= ' yellow '" " ;
</ form >
</ body ></ html >

Opener

Using the "opener" property, we can access the main window from the newly opened window.

Let ' s create Main page:

< html >


< head >


< title ></ title >
</ head >
< body >
< form >
< input  type = "button"  value = " Open another page "
= "Aa=window.open (' test.htm ', ', ', ' width=100,height=200 ')" >
</ form >
</ body >
Font face= "Verdana" > </ html >


Then Create Remote Control page (in this example, which is test.htm):

< html >


< head >


< title ></ title >


< script >


function Remote (URL) {
Window.opener.location = Url
}
</ Script >


</ head >


< body >
< p >< a  href = "#"   OnClick = remote (' file1.htm ') > File1 </ a ></ P >
< p >< a  href = "#"  onclick = "Remote (' file2.htm ')" > ' File2 </ a ></ p >
</ body >
</ html >


Try it now!

Frame

One of the most popular uses of loading multiple frames is to load and change the content of the "more than one frame at once. Lets say we have a parent frame:

< html >
< frameset  cols =" 150,* " >
< frame  src = "page1.htm"  name = "Frame1" >
< frame  src = "page2.htm"  name = " Frame2 " >
</ frameset >
</ html >

we can add a link in the ' Child frame ' frame1 ' that WI ll change the contents of Page1, but Page2 too. Shown below is the HTML code for IT:&NBSP;  

< html >
< body >
< H2 > this is page 1  </ h2 > /span>
< a  href = " Page3.htm "
onclick = "parent.frame2.location= ' page4.htm '" > click here </ a >
</ body >
</ html >

notice:you should use "parent.frame2.location " to Access another frame. "parent " standards for the parent frame containing the frameset code.




source:http://www.codeproject.com/jscript/jsbeginner.asp

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.