JavaScript:Getting Started

From virtualMV2015wiki
Jump to: navigation, search
 Home  JavaScript <

Introduction

Overview

JavaScript allows us to dynamically change the HTML code on a Web page as the Browser renders it, or if the users action triggers it (like a mouse rollover). Before you attempt to understand my JavaScript notes you will need to have a good understanding of HTML (XHTML) and Cascading Styles Sheets (CSS).

Icon Objectives.png

Objectives : JavaScript - Getting started

By the end of this page you will be able to:

  1. Create your first XHTML/JavaScript web page

First JavaScript

In this example we will create a Web page that includes JavaScript to display Hello world.. JavasScript rulz!. Just to show how HTML and JavaScript integrate I have included a div tag that changes the text colour to blue and in the JavaScript told the text to display as h1 (heading 1).

JavaScript (js1_01)

<html>
<head></head>
<body>
<div style="color: #0000FF">
<script type="text/javascript"><!-- document.write('<h1>Hello world.. JavaScript rulz!</h1>');//--></script></div>
</body>
</html>

Example :Click here to run js1_01. The diagram following shows the result in Google's chrome.

JavaScript: Hello World (in Google's Chrome Web Browser)

Code placement

  • JavaScript can be inserted into the HEAD or BODY section of a document.
  • If code is to be reused within a page then it is better to place the code in the HEAD section.
  • Code in the HEAD section is loaded before the page is built and any referrals within a page are already in memory.
  • Code within the page must be loaded into memory before execution.

Browser Handling

  • Older style browsers may not handle JavaScript
  • Browsers such as Internet Explorer warn you that running scripts from your local hard drive is a security risk
JavaScript security warning in Internet Explorer
  • To trick the browser we enclose the JavaScript code between a <!-- and //-->
<script type="text/javascript">
<!--     JavaScript code  
//--></script>
  • The older browser then ignores all code between the start and end tags
  • You may come across JavaScripts inserted as
  <script language="JavaScript"> 
  </script>

This has now be deprecated and the following format should be used:

  <script type="text/javascript">
  </script>


JavaScript (js1_02)

<html>
<head>
  <script type="text/javascript">
    <!-- hide from old browsers     
    document.write("<p>This is code in the HEAD!!!</p>"); 
    // -->  
  </script>
</head>
<body>
  <p>This is a normal HTML code in the BODY section.<br />  
  <script type="text/javascript">
    <!-- hide from old browsers     
    document.write("This is JavaScript in the BODY!!!");  
    // -->  
  </script>
  <br />
  Back to normal HTML again.</p>
</body>
</html>

Example :Click here to run js1_02.

JavaScript: Order of execution

JavaScript layout and syntax (rules)

  • Ending Statements with a Semicolon?
    • Semi-colons are used to separate pieces of code.
    • Some languages like C++ and PHP require semi-colons, others (like JavaScript) are flexible - using a new line as an alternative. They are an important part in some statements (like it..then..else, and switch), and can be used to put multiple statements per line. Strict JavaScript requires semicolons. It is probably a good idea to get used to using them particularly if you want to progress to other languages.
  • JavaScript is Case Sensitive
    • This creates heaps of problems when you first start!!!
  • White Space doesn't count!
    • - but really useful to make your code readible.
  • To Break a line of Code in the middle of a string use \, (Note next line has to start at column 1) for example:
document.write("Hello \
World!");
  • Alternatively you could concatenate (join) the string
document.write("Hello " +
"World!");
  • Inserting special characters (use \)
document.write ("You \& I sing \"Happy Birthday\".");
  • Comments
intSum = intA + intB;  //calculating the sum
/* This is a comment block. It contains several lines*/
  • Alertbox
alert("This is a message")

External Script (js1_03)

<html>
  <head></head>
  <body>
    <script type="text/javascript" src="js1_03.js"></script>  </body>
</html>

js1_03.js contains

document.write("This script is external");

Example :Click here to run js1_03.

Variables

Rules for Variable names:

  • Variable names are case sensitive
  • They must begin with a letter or the underscore character
  • Creating variables
var strName = "some text"; 
strName1 = "some text"; 
var intTotal = 400;
  • using var is optional (it is good practice to use var)
  • When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables.
  • If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.
  • If you redeclare a variable it loses its initial value.

Prompt (JavaScript 1_04)

  • The prompt object is a way that user input can be obtained and assigned to a variable... well almost! Microsoft in Internet Explorer (from version 7) have disabled this functionality, when the prompt command is called from a page on the Internet (Hunlock, 2007).[1]

A Prompt example

(Works in most Internet browsers. Does not work in Internet Explorer 7.x)

<html>
<head>
  <title>Hello</title>
  <script type="text/javascript" >
    <!--
    var strName=prompt("Enter your name","");
    document.write("Hello " +strName +" welcome to the world \
       of JavaScript");
    //-->
  </script>
</head>
<body>
</body>
</html>

Example :Click here to run js1_04.

JavaScript: Prompt

Operators

Arithmetic operators

Operator Description Example Result
+ Addition var intNum = 2+2; 4
- Subtraction var intNum = 5-2; 3
* Multiplication var intNum = 4*5; 20
/ Division var intNum=15/5;
var
3
% Modulus (remainder after division) var intNum = 5%2;
var intNum = 10%8;
1
2
++ Increment var intX=5;
intX++;
intX=6
-- Decrement intX=3;
intX--;
intX=2

Comparison Operators

Operator Description Example
== is equal to 4==8 returns false
!= is not equal 4!=8 returns true
> is greater than 4>8 returns false
< is less than 4<8 returns true
>= is greater than or equal to 4>=8 returns false
<= is less than or equal to 4<=8 returns true

Logical Operators

Operator Description Example
&& and

x=5;
y=4;
(x<10 &&y>1) returns true

|| or x=6;
y=3;
(x==5|| y==7) returns false
! not x=6;
y=4;
x != y returns true;

Conditional Operators

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. JavaScript Comparison and Logical Operators (W3Schools)

Examples

var greeting=(visitor=="PRES")?"Dear President ":"Dear ";
 
var date = new Date();
var d  = date.getDate();
var day = (parseInt(d) < 10) ? '0' + d : d;
  1. First example, if the visitor = PRES then put Dear President otherwise just Dear
  2. Here id d is < 10 then a zero is added to the front else just leave d as is.

Example (js1_05)

<html>
<body>
<script type="text/javascript">
  var intA = 3;
  var intB = 5;
  var intSum = intA + intB;
  var intProd = intA * intB;
  document.write("The sum of 3 and 5 is " + intSum +"<br />");
  document.write("The product of 3 and 5 is " + intProd);
</script>
<p>This example declares some variables, assigns values to them,
performs a calculation and then displays the results.</p>
</body>
</html>

Example :Click here to run js1_05.

Note that in the example the variables are assigned numbers. If you accept values from a prompt or a text box (from a form) the "numbers" are actually text so need to be converted if you want to do arithmetic operations on them.

Working with Strings

String concatenation(js1_06)

A string is most often text, for example "Hello World!". To stick two or more string variables together (concatenate), use the + operator

<html>
<body>
<script type="text/javascript">
var strFname = "Stephen";
var strMname = "ScriptGuru";
var strLname = "Corich";
document.write(strFname,strMname,strLname);
document.write("<h1>Hello " +strFname+ " "+strMname+ " "+strLname+ ". "+
               "Nice to meet you</h1>");
</script>
<p>This example declares some variables, assigns values to them,</p>
<p> and then displays the variables, with an without headings.</p>
</body>
</html>

Example :Click here to run js1_06.

User Input

Prompting for numbers (js1_07)

(As this uses the prompt command will not work if downloaded from the Internet in IE 7+)

When you use the prompt (or input box) to get a user to submit a number of things can go wrong!

<html>
<head>
<title>Hello</title>
</head>
<script type="text/javascript">
<!--
  vntNum1=prompt("Enter a two digit number", "");
  vntNum2=prompt("Enter another two digit number", "");
  document.write("The sum of the numbers is " +vntNum1 + vntNum2);
//-->
</script>
<body>
</html>

Example :Click here to run js1_07.

Alternative example for IE 7+ (js1_07a)

To show how this works in IE 7 we will assign the number "10" to num1 and "25" num2

<html>
<head>
<title>Hello</title>
</head>
<script type="text/javascript">
<!--
  vntNum1="10";
  vntNum2="25";
  document.write("The sum of the numbers is " +vntNum1 + vntNum2);
//-->
</script>
<body>
</html>

Example :Click here to run js1_07a.

Converting text to numbers

One of the things you need to be very careful with in JavaScript is that adding two strings together is quite different than adding two numbers. So

  • Adding "12" + "34" will give "1234" whereas
  • Adding numbers 12 + 34 gives 46

When you get user input via a textbox (notice it is called a TEXT box) numbers are captured as strings, so before you can add them they need to be converted to numbers. You can force a number conversion by simply adding a number to the text value e.g.

var intCalc = "12" + 0;
var intCalc = "12" * 1;

Or you can use number conversion functions such as;

  • parseFloat - for conversion to a floating-point number or
  • parseInt - for string-to-integer conversion.
  • eval(string) - where the string is evaluated.
var intCalc1 = parseInt(txtA) + parseInt(txtB);
var intCalc2 = parseFloat("12.23") + parseFloat(txtC);
 
eval("x=10;y=20;document.write(x*y)");
document.write("<br />" + eval("2+2"));
document.write("<br />" + eval(x+17));

Refs: Javascript Type-Conversion (n.d.)[2], JavaScript eval() Function (Refsnes Data, 2011)[3]

Converting text to numbers (js1_08)

(Contains prompt will work in most browsers and IE 7+ offline)

To convert an input string to number we need to use parseInt() or parseFloat()

<html>
<head>
<title>Hello</title>
</head>
<script type="text/javascript">
<!--
  vntNum1=prompt("Enter a two digit number", "");
  vntNum2=prompt("Enter another two digit number", "");
  document.write("The sum of the numbers is "  +(parseInt(vntNum1) + parseInt(vntNum2)));
//-->
</script>
<body>
</html>

Example :Click here to run js1_08.

Controlling the flow - making decisions

Javascript decision functions are very similar to those used in C++

The three comonly used decision functions are:

  • if {…..}
  • if {……} else {…..}
  • switch

if

if (condition){
   code to be executed if condition is true
}

if .... else

if (condition){
  code to be executed if condition is true
}
else {
  code to be executed if condition is false
}

Example (js1_09)

<html>
<body>
<script type="text/javascript">
var datDate = new Date();
var vntTime = datDate.getHours();
if (vntTime < 12) {
  document.write("Time =" + vntTime + " <b>Good morning</b>")
  }
else {
  document.write("Time =" + vntTime + " <b>Good afternoon</b>")};  
</script>
<p>This example demonstrates the If statement.</p>
<p>If the time on your browser is less than 12, you will get a "Good morning" greeting.</p>
<p> otherwise you will get a good afternoon</p>
</body>
</html>

Example :Click here to run js1_09.


switch

switch(n){
  case 1:
    execute code block 1
    break; // prevents code running into the next case
  case 2:
    execute code block 2    
    break; 
  default:
    code to be executed if n is different from case 1 and 2 
}

Example (js1_10)

<script type="text/javascript">
/* You will receive a different greeting based on
   what day it is. Note that Sunday=0, Monday=1,
   Tuesday=2, etc.*/
  var datDate=new Date();
  datDay=datDate.getDay();
  switch (datDay){
    case 1:
      document.write("Drat it’s Monday");
      break;  
    case 2:
      document.write("Only Tuesday");
      break; 
      // remainder of the code
    default:  document.write("I'm looking forward to this \
            weekend!")};
</script>

Example :Click here to run js1_10.

Functions

To create a function you define its name, any values ("arguments"), and some statements:

function fnFunction(argument1,argument2,etc) {
    some statements
} 
// no arguments, still requires parenthesis
function fnFunction() {
   some statements
} 
// functions can return a result
   function fnResult(a,b) {
   c=a+b;   
   return c;
}

Calling a function

fnFunction(argument1,argument2,etc)


Example 1: (js1_11)

<html>
<head>
<script type="text/javascript">
  function fnHello() {
    alert("HELLO");
  }
</script>
</head>
<body>
  <form>
    <input type="button" onclick="fnHello()" value="Call function" />
  </form>
  <p>By pressing the button, a function will be called. The function will alert a message.</p>
</body>
</html>
JavaScript: Button

Example :Click here to run js1_11.

Example 2: (js1_13)

<html>
<head>
<script type="text/javascript">
function fnAlert(txtMessage) {
    alert(txtMessage);
}
</script>
</head>
<body>
  <form>
    <input type="button" onclick="fnAlert('Good Morning!')" value="In the Morning">
    <input type="button" onclick="fnAlert('Good Evening!')" value="In the Evening">
  </form>
</body>
</html>
JavaScript: Function

Example :Click here to run js1_13.

Example 3: (js1_14)

<html>
<head>
<script type="text/javascript">
  function fnTotal(intA,intB) {
    return intA + intB;
  }
</script>
</head>
<body>
  <script type="text/javascript">
    document.write(fnTotal(2,3));
  </script>
  <p>The script in the body section calls a function with two arguments, 2 and 3.</p>
  <p>The function returns the sum of these two arguments.</p>
</body>
</html>

Example :Click here to run js1_14.

Icon References.png References

  1. Hunlock, P. (2007) Working around IE7s prompt bug, er feature. Retrieved April 3, 2009 from http://www.hunlock.com/blogs/Working_around_IE7s_prompt_bug,_er_feature
  2. Javascript Type-Conversion (n.d.). Retrieved from http://www.jibbering.com/faq/notes/type-conversion/
  3. (Refsnes Data, 2011) JavaScript eval() Function, w3schools Retrieved from http://www.w3schools.com/jsref/jsref_eval.asp

JavaScript:Getting Started. (2017). In virtualMV's ( Michael Verhaart ) wiki. Retrieved December 12, 2017, from http://www.virtualmv.com/wiki/index.php?title=JavaScript%3AGetting_Started    (zotero)