Vous êtes sur la page 1sur 6

JavaScript Basic Syntax Javascript is a client-side scripting language. The script is executed by user's browser.

Javascript has nothing to do on web server. Basic usages of JavaScript is for client side form fields validation for emptyness, Dropdown Menus, popup windows, alerts, prompts etc. Example #1 Basic Structure<script type="text/javascript"> //....Your JavaScript code goes here </script> We can repeat above block as many times as required in a single HTML document. The above JavaScript block can be embedded in normal HTML coding provided the JavaScript code must contain starting and ending tags Some of the basic rules for JavaScript are: JavaScript is case sensitive. Whitespace, tabs, and newline characters are ignored except when part of string constants. They can be added as needed for readability. Single line comments begin with // Multiline comments begin with /* and end with */ Commas are used to separate words in a list Round brackets are used for operator precedence and argument lists. Square brackets are used for arrays and square bracket notation. Curly or brace brackets are used for blocks. Keywords are reserved words that have special meanings within the language syntax. Identifiers are names for constants, variables, functions, loop labels, objects and classes. The first character must be an ASCII letter, underscore or dollar sign. Following characters can also include digits. JavaScript style begin class identifiers with a capital letter, uppercase constant ids and lowercase variables. Note: An identifier must NOT be any word on the JavaScript Reserved Word List. Example #2 Printing "Hello World!"<html> <head> <title>My First Page With JavaScript </title> </head> <body> <script type="text/javascript"> <!-document.write("Hello World!") //--> </script> </body> </html> As seen in the above example to use JavaScript we need to tell first the browser by using a <script> tag. Next we need to set the type of script equal to"text/javascript". In case some browsers do not support Javascript (This can be set from browser's setting), it displays the code in plain text. To overcome this problem we added the comment. The comment was ended with a "//-->" because "//" signifies a comment in Javascript, so we add that to prevent a browser from reading the end of the HTML comment in as a piece of Javascript code. Notice that there is no semicolon at the end of the statement document.write("Hello World!"). Javascript does not require that you use semicolons to signify the end of each statement, but it is OK if you use, JavaScript will work normally.

write and writeln In order to output text in JavaScript you must use write() or writeln(). Here's an example: <html> <head> <title> Welcome to my site </title> </head> <body> <script language="javascript"> <! document.write("Welcome to my site!"); // --> </script> </body> </html> Note: the document object write is in lowercase as JavaScript is case sensitive. The difference between writeand writeln is: write just outputs a text, writeln outputs 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 JavaScriptcode: document.write("Hi there.") In this code, document is the object. write is the method of this object. Let's have a look at some of the other methods that the document object possesses. lastModified You can always include the last update date on your page by using the following code: <script language="JavaScript"> document.write("This page created by John N. Last update:" + document.lastModified); </script> All you need to do here is use the lastModified property of the document. Notice that we used + to put togetherThis page created by John N. Last update: and document.lastModified. bgColor and fgColor Lets try playing around with bgColor and fgColor: <script> document.bgColor="black" document.fgColor="#336699" </script> Message Box There are three message boxes: alert, confirm, and prompt. alert <body> <script> window.alert("Welcome to my site!") </script> </body> You can put whatever you want inside the quotation marks. confirm An example for confirm box: window.confirm("Are you sure you 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() Example: <html> <head> <script> var x=confirm("Are you sure you 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 will take you to yahoo, and clicking ok will continue with the loading of the current page "Welcome to my website!". Note:if (!x)means: if click "cancel". In JavaScript, the exclamation mark ! means: "none". The basic for loop syntax is: for (initialization; condition; incrementor) { code; } The initialization defines the loop variable and its initial value (such as var i=1). The loop will continue to iterate while the conditional expression evaluates as true (like i<5). Each time the loop is executed, the incrementor code is exectued (i++ would increment the loop variable i by 1 each iteration). Putting these together in a simple example, Example #3 Basic loop structure <script type="text/javascript"> var nextline = "<br />"; document.write("For loop code is starting"); document.write(nextline); for(var i = 0; i < 5; i++){ document.write("Counter i = " + i"); document.write(nextline); } document.write("For loop code is ended!"); </script> This code would generate the output, For loop code is starting

Counter i = 0 Counter i = 1 Counter i = 2 Counter i = 3 Counter i = 4 For loop code is ended! Basic HTML Codes and Syntax: A Quick Reference <> All HTML tags are encased within carats, a "less-than" brace at the beginning of the tag, and a "greater-than" brace at the close of the tag. {} All style-sheet tags are encased within braces in the same manner as described above for carats. When to use which braces Carats are used exclusively on HTML documents (.htm or .html), whereas braces are used exclusively for style elements, either for embedded style (in the header of an HTML document), inline style, or externally-linked cascading style sheet documents (.css). / A forward-slash is always applied to a closing HTML tag. For example, to make a word bold, one would input the code <b>my bold text here</b>, with the ending bold tag "b" prefaced by a forward-slash. <html> Tag denoting the content of the document as being HTML. Must be included for the document to be read properly by a web browser. <head> Tag denoting the header of an HTML document. Within the header can usually be found the <title> and <meta> tags, embedded styles (if any), and javascript or other advanced scripting languages (if any). None of the information contained in the header is part of the main, viewable body of a web page. <title> Tag denoting the title of the web page, which is distinct from the page's filename. This is the wording that appears in the top of the web browser. For example, this page's title is "Basic HTML Codes and Syntax," which can be seen not only at the top of the page itself, but also in the top of the browser above the menu toolbars. <link rel="stylesheet" href="*.css" type="text/css"> Tag in which the external CSS, if applicable, is linked to the HTML file, with the asterisk in the example being replaced by the filename of the CSS document. <meta * > Meta tags contain a variety of information, such as the language the page was composed in, the keywords by which the page can be accessed via search engines, and the program used to compose the page, with the asterisk in the example being replaced by the type and content of the specific meta tag. <script language="JavaScript"> Javascript allows for automatic and dynamic functions such as rollover buttons and image swapping. Content contained in this type of script tag is usually generated automatically if designers are using a program such as FrontPage or Dreamweaver to create their HTML documents. <!-- and //--> Content contained between the combination of a less-than carat, exclamation point, and two

dashes (closed by two forward-slashes, two dashes, and a greater-than carat brace) is completely invisible to a person viewing the page in a web browser. This is useful for embedding Javascript or other advanced scripting languages, as well as making notes if you're creating a template for another designer. <body> Tag denoting the main, viewable content of the web page. The body tag may either stand alone as shown in the example, or it may contain additional information about the page's attributes, such as font, background, and margins. <table> Tag denoting the start of a table, either for data or layout purposes. Like the body tag, the table tag may either stand alone or contain additional information abou its attributes. When to let the <body> or <table> stand alone If you are using embedded or externally-linked CSS, these tags may stand alone. If you're designing your page using only HTML code, however, it's best to apply attributes to the <body> and the <table>. As an example, a <body> tag that has attributes applied to it might look something like this: <body bgcolor="#006600" text="#FFFFFF" link="#FF0000" vlink="#003399" alink="#333333"> bgcolor: background color of the page text: default text color link: color of an unvisited link vlink: color of a visited link alink: color of an active link # followed by six-character combination of letters and/or numbers: hexademical codes for various colors. For a complete reference on hex codes, consult the Color Hex Values picker. <tr> Tag denoting the start of a table row. Always stands alone, serves no purpose other than to further describe the table's dimensional area. <td> Tag denoting the start of an individual cell of a table. A cell may be either a row or a column. For example, the table used to delineate the text of this page is a one-celled table, whereas a small data table like this one: DateTimePlaceTodayNowHereYesterdayEarlierTherecontains nine individual cells, requiring nine opening and closing <td> tags. Unlike a <tr>, a <td> can have attributes specific to itself but not to the encompassing table at large, such as a separate background color, as in this example: DateTimePlaceTodayNowHereYesterdayEarlierThere<h1>, <h2>, etc. Tags denoting that the text contained within is a heading, and therefore, by default, is displayed as larger, bolder, and more distinct than the rest of the text on the page. The temptation for the designer would be to merely give such text a larger font size and put it into bold face, but by coding it as a heading, this text will be read with a more "authoritative" tone on screen reading software for the visually-impaired user. It is, therefore, important for accessibility reasons to use headings where appropriate. <p> Tag denoting a paragraph break, which may also contain stylistic information about the paragraph of text it contains. By inserting a paragraph break into a page, the next line of text will be effectively "double spaced" down an extra line. <br> Tag denoting a line break. Unlike a paragraph break, a line break code always stands alone. By

inserting a line break into a page, the next line of text will be "single spaced" down only one line. No closing tag is needed for a line break insertion. Line breaking using an HTML editor You may have noticed in using either FrontPage or Dreamweaver that hitting "enter" once will create an automatic paragraph break. Unlike a word processing program, the default behavior for the "enter" key in an HTML editing program is to insert a full paragraph break rather than a line break. To create a line break, then, you must hit the "shift" and "enter" keys together. <img src=" * " alt=" * "> Syntax for inserting an image into an HTML document, where the first asterisk would be replaced by the filename of the image, and the second asterisk would be replaced by a short description of the image for accessibility purposes. No closing tag is needed for an image insertion. <a href=" *.htm"> Tag denoting the start of a hyperlink, with the filename of the linked page replacing the asterisk. What follows the link tag may be a line of text or an image, and the closing syntax is </a>. <ul> Tag denoting the beinning of an unordered list, such as list item one list item two list item three <ol> Tag denoting the beginning of an ordered list, such as list item here next list item final list item You can use another attribute SRC to include an external file containing JavaScript code: <script language="JavaScript" src="hello.js"></script>

Vous aimerez peut-être aussi