Various JavaScript Statements

JavaScript is Case Sensitive

Unlike HTML, JavaScript is case sensitive – therefore watch your capitalization closely when you write JavaScript statements, create or call variables, objects and functions.

JavaScript Statements

A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser what to do.

This JavaScript statement tells the browser to write “Hello Dolly” to the web page:
document.write(“Hello Dolly”);

It is normal to add a semicolon at the end of each executable statement. Most people think this is a good programming practice, and most often you will see this in JavaScript examples on the web.
The semicolon is optional (according to the JavaScript standard), and the browser is supposed to interpret the end of the line as the end of the statement. Because of this you will often see examples without the semicolon at the end.

JavaScript Code

JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are written.
This example will write a heading and two paragraphs to a web page:

Example

<script type=”text/javascript”>
document.write(“<h1>This is a heading</h1>”);
document.write(“<p>This is a paragraph.</p>”);
document.write(“<p>This is another paragraph.</p>”);
</script>

JavaScript Blocks

JavaScript statements can be grouped together in blocks.
Blocks start with a left curly bracket {, and end with a right curly bracket }.
The purpose of a block is to make the sequence of statements execute together.
This example will write a heading and two paragraphs to a web page:

Example

<script type=”text/javascript”>{
document.write(“<h1>This is a heading</h1>”);
document.write(“<p>This is a paragraph.</p>”);
document.write(“<p>This is another paragraph.</p>”);}
</script>

It just demonstrates the use of a block. Normally a block is used to group statements together in a function or in a condition (where a group of statements should be executed if a condition is met).

  • Share/Save/Bookmark

Different between JavaScript into <head></head> and into <body></body>

JavaScript between <head></head> Tag :

JavaScript between<head></head> tag generally writing as a function & function call from HTML content of the webpage, like this :

Here I have made a JavaScript function “displaydate()” between <head></head> tag and calling this function inside html content. According to function it will display date into “<p id=”demo”></p>”



<html>
<head>
<script type=”text/javascript”>

function displaydate(){

document.getElementById(“demo”).innerHTML=Date();

}

</script>
</head>
<body>

<h1>My First Web Page</h1>

<p id=”demo”></p>
<script type=”text/javascript”>displaydate();</script>
</body>

</html>


Now JavaScript between<body></body> Tag :

JavaScript between <body></body> tag generally writing as a function or inline code, like this :

Here I just wrote a inline JavaScript code to display date” between <body></body> tag. There not need to call any function, when page request date will show on page. According to function it will display code into “<p id=”demo”></p>”
<html>

<head></head>

<body>

<h1>My First Web Page</h1>
<p id=”demo”></p>
<script type=”text/javascript”>document.getElementById(“demo”).innerHTML=Date();</script>
</body>

</html>

  • Share/Save/Bookmark

How to write Javascript into HTML code

To insert a JavaScript into an HTML page, use the <script> tag.
Inside the <script> tag use the type attribute to define the scripting language.
The <script> and </script> tells where the JavaScript starts and ends:

<html>
<body>
<h1>My First Web Page</h1>

<p id=”demo”>This is a paragraph.</p>

<script type=”text/javascript”>
… Your JavaScript code Here …
</script>

</body>
</html>

Try this example below (This will display date) :

<html>
<body>
<h1>My First Web Page</h1>

<p id=”demo”>This is a paragraph.</p>

<script type=”text/javascript”>
document.getElementById(“demo”).innerHTML=Date();
</script>

</body>
</html>

Some Browsers do Not Support JavaScript

Browsers that do not support JavaScript, will display JavaScript as page content. To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to “hide” the JavaScript.
Just add an HTML comment tag <!– before the first JavaScript statement, and a –> (end of comment) after the last JavaScript statement.

Example :

<script type=”text/javascript”>
<!–
document.getElementById(“demo”).innerHTML=Date();
//–>
</script>

  • Share/Save/Bookmark

Web Page Background Color Change with Javascript

 

Complete Code

<HTML>

<HEAD>

<SCRIPT LANGUAGE=”JavaScript”>

<!– Beginning of JavaScript –

function changecolor(code) {

document.bgColor=code

}

// – End of JavaScript – –>

</SCRIPT>

 

</HEAD>

<BODY>

<form>

<input type=”button” name=”Button1″ value=”RED” onclick=”changecolor(‘red’)>

<input type=”button” name=”Button2″ value=”GREEN” onclick=”changecolor(‘green’)>

<input type=”button” name=”Button3″ value=”BLUE” onclick=”changecolor(‘blue’)>

<input type=”button” name=”Button4″ value=”WHITE” onclick=”changecolor(‘white’)>

</form>

</BODY>

</HTML>

  • Share/Save/Bookmark

Javascript Message Box Example


Chapter 1, The Message Box

This is a very simple script. It opens up an alert message box which
displays whatever is typed in the form box below.

Type something in the box. Then click “Show Me”


HOW IT’S CODED

Here’s the entire page, minus my comments. Take a few minutes to learn as much
as you can from this, then I’ll break it down into smaller pieces.

<HTML>

<HEAD>

<SCRIPT LANGUAGE=”JavaScript”>

<!– Beginning of JavaScript –

function MsgBox (textstring) {

alert (textstring) }

// – End of JavaScript – –>

</SCRIPT>

</HEAD>

 

<BODY>

<FORM>

<INPUT NAME=”text1″ TYPE=Text>

<INPUT NAME=”submit” TYPE=Button VALUE=”Show Me” onClick=”MsgBox(form.text1.value)“>

</FORM>

</BODY>

</HTML>

  • Share/Save/Bookmark

Javascript Objects, Methods, Events

Objects and Properties

Your web page document is an object. Any table, form, button, image, or link on your page is also an object. Each object has certain properties (information about the object). For example, the background color of your document is written document.bgcolor. You would change the color of your page to red by writing the line: document.bgcolor=”red”
The contents (or value) of a textbox named “password” in a form named “entryform” is document.entryform.password.value.

Methods

Most objects have a certain collection of things that they can do. Different objects can do different things, just as a door can open and close, while a light can turn on and off. A new document is opened with the method document.open() You can write “Hello World” into a document by typing document.write(“Hello World”) . open() and write() are both methods of the object: document.

Events

Events are how we trigger our functions to run. The easiest example is a button, whose definition includes the words onClick=”run_my_function()”. The onClick event, as its name implies, will run the function when the user clicks on the button. Other events include OnMouseOver, OnMouseOut, OnFocus, OnBlur, OnLoad, and OnUnload.

  • Share/Save/Bookmark

Some Common FAQ about Javascipt

 

Are Javascript and Java the same?

No, they are two completely different computer languages. Only their names are similar. Actually Javascript is not Java and Java is not Javascript. You can say Java and Javascript is two different Animal.

What do we need to run Javascript?

Javascript support is built right into web browsers. Provided that the visitors to your site are using web browsers that support Javascript (most do) and have Javascript enabled (it is by default) then your Javascript will run.

Do I need to learn Javascript to be able to use it?

No. There are plenty of Javascripts that have already been written that people have made available for you to plug straight into your web page. All you need to know to be able to use such scripts is how to paste the supplied code into the required places in your web page.

What do I need to write Javascript?

Javascript is an interpreted language and so no special program is required to be able to create usable code. Any plain text editor such as Notepad is quite satisfactory for being able to write Javascript. That said, an editor which colourizes the code to make it easier to see what is what makes it easier to find your mistakes but then my Javascript Formatter can reformat your script to make errors even easier to spot.

Can I use HTML instead of Javascript?

No. HTML and Javascript are two completely different things. HTML is a markup language designed for defining static web page content. Javascript is a programming language designed for performing dynamic tasks.

Can I use PHP or some other server side language instead of Javascript?

Perhaps, it depends on where the code needs to run. If it can run before the page loads you can use a server side language. If it has to run after the page has loaded then you must use Javascript as this is the only scripting language supported by all web browsers that support client side scripting.

Does the Javascript go in the same file as the HTML?

It can but your scripts will be more easily reused on multiple pages of your site if you place them in separate files (using a .js extension helps identify them as Javascript). You then just link the Javascript to your HTML by inserting a <script> tag. The same Javascript can then be added to several pages just by adding the appropriate tag into each of the pages to set up the link.

 

  • Share/Save/Bookmark

Benefits of JavaScript

 

Javascript has Many benifits.  JavaScript’s main benefit is that it can be understood by the common human. It is much easier and more robust than Java. It allows for fast creation of web page events. Many JavaScript commands are what are known as Event Handlers: They can be embedded right into existing HTML commands. JavaScript is a little more forgiving than Java. It allows more freedom in the creation of objects. Java is very rigid and requires all items to be denoted and spelled out. JavaScript allows you to call on an item that already exists, like the status bar or the browser itself, and play with just that part. JavaScript is geared to web pages. Java is geared toward where it is needed most at the time.

Both will create great web page events. Both can offer interaction between the user and your Web page. But they are not created equally by any means.

So to answer the question of which to use where… use whichever fits your needs. That sounds like a cop-out answer, but remember that the applets and JavaScript are most often offered on the Net as fully functioning items. You simply grab them from the Net and use them on your page (provided you are given permission). There are many, many sites out there that do nothing more than hand out applets or JavaScript.

Gamelan.com is a good one for applets. Take a look at javascripts.com for over 2300 free JavaScript scripts. The HTML Goodies Applet and JavaScript Tutorials will teach you how to implement these items on your pages. They will not teach you to write the languages, but rather instruct you on placing functioning applets and JavaScript scripts on your Web pages. It is a good introduction to the formats. Once you know how to get these pups on your pages, you’ll understand more about their structures and can then more easily attempt to learn the language and create functioning JavaScripts or applets yourself.

 

  • Share/Save/Bookmark

What is JavaScript and how is it different from Java Technology?

The JavaScript programming language, developed by Netscape, Inc., is not part of the Java platform.

JavaScript, does not create applets or standalone applications. In its most common form today, JavaScript resides inside HTML documents, and can provide levels of interactivity to web pages that are not achievable with simple HTML.

Listed are key differences between the Java and JavaScript.

  • Java is an OOP programming language while Java Script is an OOP scripting language.
  • Java creates applications that run in a virtual machine or browser while JavaScript code is run on a browser only.
  • Java code needs to be compiled while JavaScript code are all in text.
  • They require different plug-ins.

Java vs. JavaScript: Similarities and Differences

They are both similar and quite different depending on how you look at them. First their lineage:

Java is an Object Oriented Programming (OOP) language created by James Gosling of Sun Microsystems. JavaScript is a scripting language that was created by the fine people at Netscape and was originally known as LiveScript. JavaScript is a (very) distant cousin of Java in that it is also an OOP language. Many of their programming structures are similar. However, JavaScript contains a much smaller and simpler set of commands than does Java. It is easier for the average weekend warrior to understand.

You may be wondering what OOP means by now. Object Oriented Programming is a relatively new concept, whereas the sum of the parts of a program make up the whole. Think of it this way: you are building a model car. You build the engine first. It can stand alone. It is an engine and everyone can see it’s an engine. Next you build the body. It can also stand alone. Finally, you build the interior including the seats, steering wheel, and whatnot. Each, by itself is a object. But it is not a fully functioning car until all the pieces are put together. The sum of the objects (parts) make up the whole.

Continuing with the model car example, when you built the engine, you didn’t use any of the parts that would later build the seats (a 350 four-barrel engine with a seat belt sticking out if the piston would look pretty silly). The point is that all the parts that made up the engine were of a certain class of parts. They all went together. Ditto with the body and then the interior.

The point is that in these languages, you build objects out of classes of commands to create the whole. Understand the terminology? Good. Moving along…

Java and JavaScript are Still Two Different Trees

Now let’s talk about how Java and JavaScript differ. The main difference is that Java can stand on its own while JavaScript must (primarily) be placed inside an HTML document to function. Java is a much larger and more complicated language that creates “standalone” applications. A Java “applet” (so-called because it is a little application) is a fully contained program. JavaScript is text that is fed into a browser that can interpret it and then it is enacted by the browser–although today’s web apps are starting to blur the line between traditional desktop applications and those which are created using the traditional web technologies: JavaScript, HTML and CSS.

Another major difference is how the language is presented to the end user (that’s you when you’re surfing). Java must be compiled into what is known as a “machine language” before it can be run on the Web. Basically what happens is after the programmer writes the Java program and checks it for errors, he or she hands the text over to another computer program that changes the text code into a smaller language. That smaller language is formatted so that it is seen by the computer as a set program with definite beginning and ending points. Nothing can be added to it and nothing can be subtracted without destroying the program.

JavaScript is text-based. You write it to an HTML document and it is run through a browser. You can alter it after it runs and run it again and again. Once the Java is compiled, it is set. Sure, you can go back to the original text and alter it, but then you need to compile again.

Java applets run independent of the HTML document that is calling for them (and Java is also what runs many appliances and mobile devices, and does not require a web browser). Sure, they appear on the page, but the HTML document did little more than call for the application and place it. If the programmer allows it, oftentimes parameters can be set by the HTML document. This includes the background color of the applet of the type of text it displays, etc. The delivery of the applet is done through a download. The HTML document calls for the application, it downloads to the user’s cache, and waits to run. JavaScript is wholly reliant on the browser to understand it and make it come to life.

  • Share/Save/Bookmark

What is Javascript?

Javascript is a programming language that is used to make web pages interactive. It runs on your visitor’s computer and so does not require constant downloads from your web site.

A Brief History of JavaScript

Proposed in 1962, the Internet was created in 1969, known then as the ARPANET, by the Advanced Research Projects Agency (ARPA), linking their four main computers in their four research headquarters in SouthWest USA. It had been four years since 1965, when they had first managed to connect two computers over the telephone system. By 1972, many computers in universities across the USA had been connected, and the email, newsgroup and telnet protocols were being developed. Many further internet protocols were developed in the 1970s and 1980s, such as FTP and Gopher, and the underlying TCP/IP protocol replaced the original NCP protocol in the early 1980s. And so the ARPANET became the Internet, a network of university and military computers connected to each other via many other computers, communicating using the TCP/IP protocol. The idea was that, even if the Cold War became real, and portions of the Internet were damaged by nuclear war, the remaining links could take over so the internet could still function.
The World Wide Web (which basically means using the HTTP protocol to retrieve hyperlinked documents) was proposed in March 1989 by Tim Berners-Lee, a British computer specialist, at the European Laboratory for Particle Physics (CERN) for Swiss scientists, so that they could easily publish and share their research with the 12 nations of the high-energy physics community. He created the world’s first browser, named ‘WorldWideWeb’, in 1990, and released it in 1991. In 1992, browsers became a worldwide tool for transmission of text based information, using the HTTP protocol. In 1993 the NCSA mosaic browser was created and offered the oportunity to use inline images, and colours and hyperlinks as well as plain text. It was also the first browser to run in a graphical interface environment. The first version of Netscape was released in 1994, written by a break-away group from the original Mosaic team.

The Javascript language is one of the most useful to come along in the history of the world wide web. It allows websites to be built that are much more interactive than the ones that came before them. Javascript was actually created to make better web browsers but it soon became obvious that it was also useful forwebsite developers. The result is the world wide web that we know today, with all of its interactivity.

Javascript was created during the mid nineties as a way to make web browsers more interactive. Up until that time most websites were very dull as they usually contained little besides text and had almost no interactivity. In order to address this problem when Netscape were developing their updated version of the Navigator browser they created Javascript in order to allow them to build a browser that would be more functional. With this they were very successful and Javascript soon became widely used for a number of other applications as well.

The main use of Javascript quickly went from building a better web browser to building a better website. It is used mainly to build dynamic web pages. A dynamic web page is simply one that shows new content every time somebody visits. In the early days of the web this wasn’t possible because of the limitations of HTML. It was really the development of PHP that made dynamic sites possible. However even this proved to be of limited value. What was really needed was a coding language that would allow for the development of sites that weren’t just dynamic but actually interactive.

This is something that Javascript made possible. On our own web siteYozo.be, we use Javascript intensely to make the page talk to the visitors as naturally as possible. It takes some skill, but it’s actually surprisingly simple.

Unlike most other programing languages that are used to create web pages it soon became apparent that there were a number of other potential uses for Javascript. Not only is it used to create web pages it is widely used in the development of PDF documents. This allows documents to be interactive as well. Javascript is also widely used in the development of desk top applications. The main reason for the popularity of Javascript is that it is a fairly easy language to learn and to code with.

One of the areas that has caused some controversy with Javascript is the name. It of course has a similar name to the popular programming language Java. In fact there is no relationship between them at all. They were developed completely independently of each other. However Sun Microsystems who did develop Java were involved in the announcement of the name, adding to the confusion. Most people have viewed this as a marketing ploy, a way to attract attention Netscape’s new browser. Although exactly what was in it for Sun Microsystems was never quite clear. Clearly some sort of arrangement was made but just what that is we are unlikely to ever know.

JavaScript name terminology

These names are subject to interpretation by the browser developers. For example, browsers may support what they call JavaScript1.5, but not even support DHTML. This makes the JavaScript version unreliable, do not rely on it.

ECMAscript : The core syntax for JavaScript, defining control stuctures, intrinsic objects and variable types, operators, functions, scope, etc.

DOM level 0 : Says how to refer to forms, inputs, images, links and anchors as children of the document object.

Layers DOM : Says how to refer to positioned elements (layers) and modify their style as children of the document object with nested references.

Proprietary DOM : Says how to refer to elements and modify their style using the all collection of the document or parent object and the style child object of the element.

W3C DOM : Says how to refer to elements and modify their style using various getElementBy… methods of the document or parent object and the style child object of the element. Also says how to represent all document elements as a tree structure. Also allows elements to be created, modified or deleted even after the document has loaded.

Mocha : An early name for JavaScript, not recognised by most browsers.

LiveWire : An early name for JavaScript, not recognised by most browsers, used as the name of Netscape’s server side JavaScript.

LiveScript : An early name for JavaScript, recognised by most browsers.

JavaScript : A collective name for all versions of JavaScript.

JavaScript1.0 : The first version of JavaScript to be released – Early ECMAscript + DOM level 0 without images.

JavaScript1.1 : Early ECMAscript + DOM level 0.

JavaScript1.2 : ECMAscript + DOM level 0 + layers or proprietary DOM.

JavaScript1.3 : More advanced ECMAscript + DOM level 0 + layers or proprietary DOM.

JavaScript1.4 : Server side JavaScript.

JavaScript1.5 : Even more advanced ECMAscript + DOM level 0 + W3C DOM.

JavaScript2.0 : JavaScript 1.5 with several extensions added by Mozilla – may become a future standard.

JScript : Microsoft’s JavaScript variations with extended core features.

Active scripting : Microsoft’s user friendly way of saying ‘JScript’.

JellyScript : WebTV’s interpretation of JavaScript.

InScript : iCab 3-‘s interpretation of JavaScript.

ECMAscript Mobile Profile : Parts of ECMAScript, basic JavaScript APIs, and DOM, all mixed together in a single specification. Incompatible in far too many ways with existing pages on the Web, current browsers, the ECMAScript pecification, the DOM specifications, the JavaScript documentation, and other well established practices. ECMAScript Mobile Profile should be ignored. It is harmful to the Web because of its incompatibilities.

 

  • Share/Save/Bookmark