Beginning Javascript Tutorial | Javascript Hello World

1 - I can do better 2 - Jury's out 3 - Pretty darn good 4 - Splendiferous 5 - Awesometastic by 4 people | Log in to rate

Ranked #1,716 in Tech & Geek, #44,580 overall

Learning Javascript Tutorial

Javascript is a scripting language used in HTML files and executed by the browser to give web pages interactive abilities. It is an important component to website or web design and website programming.

Also I should mention Javascript is fun too. You can animate elements like having a paragraph or image fade into view for instance.

There are a number of Javascript libraries that you can add to your HTML. My current favorite is JQuery. These libraries allow you to do amazing things easily. Javascript is a prime component of AJAX the new buzz word on the block. Many social media sites use AJAX to make their use interface flexible.

Living Web Pages - Javascript for Beginners 

This article will take you from knowing nothing about Javascript to on your way to being a professional. This code was tested with the latest versions of Opera, FireFox and Internet Explorer (IE).

Javascript is a language all web browsers understand. This language tells the browser how the page should look and behave, when your customer comes to your site.

Requirements:

1 - A web browser - IE 7 will do...
2 - A text editor - notepad will do...

Recommendations:

1 - Use Firefox for developement and check results with IE.
2 - Add Firebug to Firefox. It's a debugging tool for Javascript (among other things)
3 - Find a more advanced text editor. There are many fine editors available for free. Search in Google for them. I've used PSPad and Notepad++ with good results. Also Kompozer which has a GUI interface for the HTML and a Javascript console. The Firebug Javascript debugger is better though it takes some getting use to.

I've put three html files out on a website for you to copy or test as well as the full version of this article. It can be slow at times, but what do you want for a free web host? Open any of the links in a browser, right click and view the source. From there you can select copy paste into any text editor like notepad.

Below is a video for those unfamiliar with HTML.

Video on HTML 

Takes you through the basics in 39 minutes! About all you need to know.

If you don't know HTML I recommend you watch this video for a quick introduction to the basics. It is well worth the 39 minutes. Jimmy Ruska has many beginning tutorial videos. There is a link at the bottom to his website.

Basic HTML and CSS Tutorial. Howto make website from scratch

powered by YouTube

Javascript Hello World 

A "Hello world" is the traditional starting point for all programmers learning a language.


It shows the basic structure for programs and gives some output. You'll need an HTML page (copy paste below into notepad and save as mytest.html)-


<html>
 <head>
  <title>Javascript hello world </title>
 </head>
 <body>
  <!-- Comment not viewable in a browser -->
 </body>
</html>


Then you need to tell the browser you are doing some scripting. You can put these tags anywhere in your HTML but I'll put them in the <head> section for this tutorial.

The tag used is <script>. By itself that is enough, as most browsers use Javascript as the default language. IE uses their own version of Javascript called Jscript as their default. Jscript and Javascript are enough alike to both work for this tutorial, I type my script language in the tag -


 <script type="text/javascript">
   //your code here
 </script>


Note that "//" in Javascript means 'what follows is a comment and not executable code.' It makes anything after it on that single line a comment.

Insert the following in the <head> section of your HTML page.


 <script type="text/javascript" rel="javascript">
   document.write("<h1>hello world.</h1>");
</script>


Save it and open the .HTML file in a browser.

In Javascript the 'document' refers to the webpage itself. It is a sub-object to it's parent object "window" - the area the HTML file opens in. So:


 <script type="text/javascript" rel="javascript">
    window.document.write("<h1>hello world.<h1>");
 </script>


will work the same as the program above.
Notice you can write the whole page using just Javascript. But there's more!

Turning on Javascript Debug Mode in Internet Explorer

In IE, if you want to use the browser debugger you can turn this on in Tools -> Internet Options -> Advanced. Go through the list until you see Javascript debugging. It's not very good but may help you with any problems during load time.

Trapping an Event - Mouse Clicks! 

Next we'll talk about and use events to change the page.

computer mouse in trap

I'll use the "onclick" event to change the text of the "Hello World". First we need to capture the event. Move the <h1> code to the body of the HTML and add some code for our event:




<script type="text/javascript" rel="javascript">
   function MyClickEvent(){
   alert("Something clicked!");
}
 </script>
 </head>
 <body>
   <!-- We add this line to demostrate onclick event. -->
   <h1 id='checkme' onclick='MyClickEvent()'>Hello world.<h1>



Open the new page in a browser and click on "Hello world." You should get a message box that reads "Something clicked!"



It's okay to cut and paste! Try changing text and commenting out or removing some of the code to see how it behaves. Warning - make only one change at a time! This will pay off as your skills grow! Experimentation is way cool!

In this code you added "onclick=MyClickEvent()" to the <h1> tag. This tells the browser to run 'MyClickEvent()' when someone clicks in the area between the <h1> tags. There are many events you can use. I'll put some reference sites at the end of this piece where you can learn more.

If in the <h1> you change your "MyClickEvent()" to "myClickEvent()" (lowercase 'm') your page won't work. Javascript is case sensitive so any difference in case is viewed as a new object, variable or function. When using a Javascript object, use only lowercase. "Document." is not "document." and your program will fail to run. If you leave off the "()" at the end, your page won't work. Depending on your browser and the settings there you may get an error message.

Semi-colons tells the browser interpreting the code that the line has ended. They are important.

If you have a Javascript error (unless you have a debugger like Firebug for Firefire), you'll see nothing, and you won't be able to trap errors in your code. It just won't run. To find errors you'll need to use something like the "alert();" function . Above we used "alert" to signal that the 'click' event and function "MyClickEvent" had fired. You can use "alert();" to find where your code failed. Just move it to different places in your code.

A function in Javascript must have "function" (lowercase) as the first word, your function name then "()". Parentheses would contain the values you want to pass to your function. We won't go into that here. After the parentheses we have enclosing "curly braces". Within the braces goes our code. Miss a "}" or the parens - our function won't run.

Again experiment with the code - change things, take things out - add things and play around with it. One change at a time!

Browser Madness 

Next example is on detecting brownsers.

Professionals need to be concerned about what the user has for a browser. I tested with Opera, Firefox and Internet Explorer. Why? They are the most used (see browser stats ). All browsers have quirks and idiosyncrasies in evaluating Javascript, HTML and CSS.

So far I haven't found a comprehensive list of these differences and what to do to avoid them. That may be another article.

In your HTML after the <script> tag add:


 document.write("<h1 id='checkme'>Hello world.<h1>");

   var idCheck =    document.getElementById("checkme");

 if (idCheck.addEventListener){
   alert("This is running in FireFox!");
   idCheck.addEventListener("click", MyClickEvent, false);
 }
 if (idCheck.attachEvent){
   alert("This is running in IE!");
   idCheck.attachEvent("onclick", MyClickEvent);
 }


Remove the <h1>...</h1> tag in the body section of your HTML file.

For Javascript - Browser's Differ!

Internet Explorer doesn't care about semi-colons as long as the line ends with a carriage return. Firefox must have a semi-colon at the end of each statement.

If it runs in IE and not in Firefox, that is most likely the reason. It runs well in both with the semi-colons in place.

 

Save and open in a browser - click on "Hello world." If you have copied the code correctly you should notice two things. First if you are running IE you should get a message "This is running IE!" If you run anything that is using the W3C standard for Javascript you'll get "This is running in FireFox!" Second if you click on the "Hello world." out friend, the alert box "Something clicked!" appears.

We have told the browser in code that the "" tag with the "id='checkme'" has an event we want to associate with our function "MyClickEvent".

We used the 'if ('- logical test here -')' statement. If the test fails the code in the "{}" braces doesn't run. In IE "addEventListener" doesn't exist. So the test fails for Internet Explorer browsers and the code marches on, unconcerned.

We want to have our tag respond to clicks in code (where we have more control) so we use "document.getElementById("checkme");" to grab any element (in this case the tag '') with the 'id' attribute set to "checkme". We assign it to a variable called 'idCheck' to keep the code short and to help readability.

The "false" in addEventListener will take room I don't have. Look it up! :)

Lets have it do something more interesting. Replace MyClickEvent with:


 function MyClickEvent(){
 //set var so we only need to change message in one place
   var newMessage = "Hello World! I've been clicked!";
   //Check for browser wierdness
   if (this.innerHTML==newMessage){
      alert("Already clicked!");
   return;
   }
   if (this.innerHTML){
      this.innerHTML=newMessage;
      return;
   }
   if (!this.innerHTML){
      //for IE!!!
      if (idCheck.innerHTML==newMessage){
      alert("Already clicked!");
   return true;}
   idCheck.innerHTML=newMessage;
   }
   return;
   }


Here I've introduce several new concepts. First the 'var' that contains a reference to a string of characters "Hello World!..." Change it here to change if for all instances of 'newMessage' in this function.

The "this" object is shorthand for the currently accessed object. In this case our tag is the object. IE has some problems with the 'this' object. In the "if" statement where I check, I have (!this.innerHTML). The "!" means "not" in Javascript. In IE "this.innerHTML" is a "null" or undefined object and therefore also "false". So "not false" will be "true" and the code after will run.

Also, I've used the 'innerHTML' property of the 'h1' tag to change the text in the tag.

Note that code after "return;" is executed is not run.

Save and run your script in a browser. Second time you click the tag, you'll get a message "Already clicked!"

We're done! Now you know some of what it takes to write Javascript for multiple browsers. Have fun!

Related Javascript Links for Beginners 

Jimmy Ruska's Video Tutorials - List of Video Tutorials
Tutorials on a wide range of subjects. Including computer and web related topics.
Online JavaScript Tutorial
Online JavaScript Tutorial from Web Developer Notes website.
Code_Punk - Beginning JavaScript Index
Free Web tutorials covering HTML, CSS, JavaScript, and DHTML from beginner to advanced. Free downloads and developer resources. Personalized help via email, form, and chat.
quirks mode
JavaScript - Table of contentsThe JavaScript part of my site contains all JavaScript pages.
It is by far the largest section of my site.I have created seven JavaScript categories that follow my book's subdivision:
General (chapters 1-4), Core (5), BOM (6), Events (7), DOM (8), CSS modification (9),
W3Schools Online Web Tutorials
HTML XHTML CSS JavaScript XML XSL ASP SQL ADO VBScript Tutorials References Examples

Javascript Tutorial for Beginners 

JavaScript Tutorial 1.1: The Very Basics

Runtime: 8:02
52941 views
10 Comments:

powered by YouTube

Javascript and web design titles 

Beginning JavaScript, 3rd Edition (Programmer to Programmer)

The WROX books always made sense to me with their very practical "how do you do it" approach.

Amazon Price: $26.90 (as of 07/11/2009) Buy Now

Professional JavaScript for Web Developers (Wrox Professional Guides)

Usually, I found that the Beginning Guide where too basic. Though the Professional Level guides are a struggle at first, they wind up answering your tougher if not toughest questions.

Amazon Price: $26.39 (as of 07/11/2009) Buy Now

JavaScript: The Definitive Guide

O'Reilly books are always handy and contain clear summaries. Good for those not working much in Javascript and need a refresher from time to time.

Amazon Price: $31.49 (as of 07/11/2009) Buy Now

jQuery in Action

JQuery is a Javascript library which allows you to do special effects (among other things) in your web pages.

Amazon Price: $26.39 (as of 07/11/2009) Buy Now

Tell me your interest in Javascript 

triathlontraining wrote...

This is a fantastic lens! Great job on the info. I look forward to more updates. :)
5*

ReplyPosted May 19, 2008

kiwisoutback wrote...

Great work, saw you on Lensroll.com. I'm no good at Java but this is a good start!

ReplyPosted May 03, 2008

Webcodes wrote...

Saw you over at the forums. As a developer, I enjoy this type of lens. Gave you 5 stars. Review some of my lenses if you can as well.

ReplyPosted April 25, 2008

adez7 wrote...

I have one word for you, EXCELLENT! I want more! :)

ReplyPosted April 25, 2008