Tuesday, September 15, 2015

Introduction to Javascript

Javascript

 

If you’re new to programming/scripting, JavaScript is a good place to start. Having said that, it’s still quite different to HTML so I recommend you take your take your time and cover off a little bit each day. Don’t worry if it tales you several days to complete – it’s better to fully understand everything than to brush over it and not fully comprehend it.

 

I suggest you bookmark this tutorial now, then continue on.

 

What is JavaScript?

 

JavaScript is a scripting language that enables web developers/designers to build more functional and interactive websites.

Common uses of JavaScript include:

 

  • Alert messages

 

  • Popup windows

 

  • Dynamic dropdown menus

 

  • Form validation

 

  • Displaying date/time

 

JavaScript usually runs on the client-side (the browser’s side), as opposed to server-side (on the web server). One benefit of doing this is performance. On the client side, JavaScript is loaded into the browser and can run as soon as it is called. Without running on the client side, the page would need to refresh each time you needed a script to run.

 

What do I need to create JavaScript?

 

You can create JavaScript using the same equipment you use when creating HTML. That is:

 

  • Computer

 

  • Text editor. For example, Notepad (for windows), Pico (for Linux , or Simpletext (Mac). You could use a HTML editor if you like it’s not needed.

 

  • Web Browser. For example, Internet Explorer or Firefox. You will need to ensure JavaScript is enabled within your browser’s setting  (this is normally enabled by default).

 

The next lesson will show you how to enable/disable JavaScript in your browser.

 

How to enable JavaScript

 

To view webpages with javascript, you need to ensure your browser has JavaScript enabled. Generally speaking, you can still view the webpage without JavaScript, but you will not be able to take advantage of the JavaScript functionality.

 

How do I check if my browser has JavaScript enabled?

 

You normally do this by checking your browser’s option. This will depend on the browser you’re using. Instructions for some of the more common browsers are below:

 

Internet Explorer (6.0):

 

  1. Go to Tools from the top menu
  2. Select Internet Options
  3. Click on the Security tab
  4. Click Custom Level
  5. Scroll down until you see the Scripting section
  6. Ensure that the Active Scripting option is set at Enabled
  7. Click OK

 

How do I disable JavaScript?

 

You simply to through the steps above the JavaScript options are not checked/selected.

 

If you’re developing web pages with JavaScript, it’s good practice to view your website with JavaScript disabled. This will show you what your website will look like to users who choose to disable JavaScript.

 

Other browsers?

 

Most (if not all browsers) give you the option to enable/disable JavaScript. If your browser is not listed above, the steps above will give you some idea of how to find it. Just look for something called tools, options, preferences or something similar.

 

Warning

 

Java and JavaScript are two different things – make sure you’re enabling/disabling the right option!

 

JavaScript Syntax

 

What does JavaScript syntax mean? JavaScript syntax refers to a set of rules that determine how the language will be written (by the programmer) and interpreted (by the browser).

 

The JavaScript syntax is loosely based on the Java syntax. Java is a full blown programming environment and JavaScript could be seen as a sup-set of the Java syntax. Having said this,  that is where the similarities end – Java and JavaScript are two totally different things.

 

In learning JavaScript you will become familiar with terms such as variables, functions, statements, operators, data types, objects etc.

It will take most of this tutorial to show you the complete JavaScript syntax. For now, I’ll give you a quick intro by showing you an example and explanation.

 

Explanation code

 

<script type=”text/javascript”>

<!–

Document.write(“JavaScript is not Java”);

— >

</script>

This results in:

JavaScript is not Java

 

The above example is how you write text to a web page using JavaScript.

 

Explanation of code

 

  • The <script> tags tell the browser to; expect a script in between them. You specify the language using the type attribute. The most popular scripting language on the web is JavaScript .

 

  • The bits that look like HTML comments tag (<– — >) are just that- HTML comment tags. These are optional but recommended. They tell browsers that don’t support JavaScript (or with JavaScript disabled ) to ignore the code in between. This prevents the code from being written out to your website users.

 

  • The part that writes the actual text is only 1 line (document.write(“JavaScript is not Java”);). This is how you write text to a web page in JavaScript. This is an example of using a JavaScript function (also known as method).

 

Where to put your scripts?

 

You can place your scripts in any of the following locations:

  • Between the HTML document’s head tags.
  • Within the HTML documents body (I.e. between the body tags).
  • In an external file (and link to it from your HTML document).

 

 JavaScript Popup Boxes

 

You’ve probably encountered JavaScript popup boxes many times while visiting websites. Now, I don’t mean “popup windows” – we’ll cover that later. What I mean is, a popup box that displays a message, along with an “OK” button. Depending on the popup box, it might also have a “Cancel” button, and you might also be prompted to enter some text. These are all built into JavaScript and are what I call “JavaScript popup boxes”. They can also referred to as “dialog boxes”, “JavaScript dialogs”, “popup dialog” etc.

 

Type of Popups

 

JavaScript has three different types of popup box available for you to use. Here they are:

 

Alert

 

Displays a message to the user. Example:

 

Confirm

 

Asks the user to confirm something. Often, this is conjunction with another (potentially significant) action that the user is attempting to perform. Example:

 

Prompt

 

Prompt the user for information. Example:

 

Popup code

 

Here’s the syntax for specifying popup boxes, along with some examples.

 

 

Type of popup

 

syntaxExample codeExample display
AlertAlert(“message”);Alert (“Hey, remember to tell

your friends about Quackit.

com!”);

 
ConfirmConfirm (“message”);

 

Confirm (“Are you sure you

want to delete the internet?”)

 
PromptPrompt (“message”);

 

Prompt (‘please enter your

favorite website’, ‘Quackit.

com’);

 

 

Note that the user’s browser determines what the popup box actually looks like. This is because our popup code is simply telling the browser to “display this type of popup with this message”. It is up to the browser to render the correct type of popup with the specified message.

 

Integating JavaScript with HTML

 

You will have noticed that the (above) example popups didn’t appear as soon as you loaded  this page. They only appeared after you clicked the relevant button. This is because I placed code into each HTML button, so that when it was clicked, it triggered off our JavaScript.

 

This is a very common way of using JavaScript on the web. By “attaching” JavaScript to our HTML elements, we can make our pages much more responsive to our users’ actions.

 

JavaScript and HTML

In previous lessons. We’ve learned about the syntax of JavaScript, but we haven’t yet learned how to “attach” the JavaScript to out HTML elements. That’s what I’ll show you in this lesson.

 

Standalone JavaScript

 

First, let’s look at what a standalone piece of JavaScript looks like.

<script type =”text/javascript>

<!–

alert(‘Hey, remember to tell your friends about Yahoo.com!’);

–>

</script>

 

If we place the above JavaScript between the ‘head’ tags (or ‘body’ tags), it will run as soon as we load the page.

 

Now this is fine – as long as you want it to run as soon as the page loads!

 

But, what if you don’t want it to run as soon as the page loads? What if you only want it to run when a user clicks on a button?

 

Easy! This is where you need to use an “event handle”.

 

What’s an Event Handler?

 

In JavaScript/HTML, an event handler allows you to attach your  JavaScript to you HTML elements.

 

Events handlers allow your web page to detect when a given “event” has occurred, so that it can run some JavaScript code. An example of an “event” could be say, a click on an HTML element.

 

In your code, an event handler is simply a special attribute that you add to your HTML element. For example, to run some JavaScript when the user clicks on an element, you add the onClick attribute to the element.

 

The examples below demonstrate this for you.

 

Adding JavaScript to an HTML Element

 

Here’s a basic example of adding JavaScript to an HTML element. In this case, when the user clicks on our button, a JavaScript alert box is displayed. This is done by adding an onClick attribute and placing the JavaScript alert box code into it.

 

When you use JavaScript like this, you don’t need to use script tags (like we did above). Simply palace your JavaScript within the event handler and it will work.

 

Code:

 

<input type=”button” onClick=”alert(Hey, remember to tell your friends about Yahoo.com!’);”value=”Click Me!”/>

 

Result:

 

JavaScript “On Double Click”

 

You could just have easily used another event to trigger the same JavaScript. For example, you could run JavaScript only when the double clicks the HTML element. We can do this using the onDb1Click event handler.

 

Code:

 

<input type=”button” onDb1Click=”alert(Hey, remember to tell your friends about Yahoo.com!’);”value=”Click Me!”/>

 

Result:

 

There are plenty of other event handlers you can use within your JavaScript/HTML code. In total, there are 18 event handlers (as listed by the W3C).

 

Complex Code

 

Once you become well versed in JavaScript, you’ll be able to write some complex programs using lots of code. When this happens, you’ll want to place your cede into a “function”. Here we call total, there are 18 event handlers (as listed by the W3C).

 

External JavaScript File

 

You can place all your scripts into an external file (with a .js extension), then link to that file from within your HTML document. This is handy if you need to use the same scripts across multiple HTML pages, or a whole website.

To link too an external JavaScript file, you add a src attribute to your HTML script tag and specify the location of the external JavaScript file.

 

Linking to an external JavaScript file

 

<script type=”text/javascript” src=”external_javascript.js”> </script>

 

Contents of your external JavaScript file

 

The code in your .js file should be no different to the code you would normally have placed in between the script tags. But remember, you don’t need to create to script tag again – it is already on the HTML page calling the external file!

 

JavaScript Operators

 

JavaScript operators are used to perform an operation. There are different types of operators for different uses.

 

Below is a listing of JavaScript operators and a brief description of them. Don’t worry if you don’t understand all of them at this stage – just bookmark this page for reference and return when ever you need to.

 

Arithmetic Operators

 

 

OperatorDescription
+Addition
Subtraction
*Multiplication
/Division
%Modulus (remainder of a division)
++Increment
Decrement

 

 

 

Assignment Operators

 

Operator                  Description 
=                                       Assign
+=                                     Add and assign. For example, x+=y is the

same as x=x+y.

– =                                     Subtract and assign. For example, x-=y is

the same as x=x*-y.

* =                                      Multiply and assign. For example, x*=y

is the same as x=x*y.

/ =                                       Divide and assign. For example, x/=y is

the same as x=x/y.

% =                                     Modulus and assign. For example,

X%=y  is the same as x=%y.

 

 

Comparison Operators

 

 

OperatorDescription
= =Is equal to
= = =Is identical (is equal to and is of the same type)
!=Is not equal to
!= =Is nor identical
>Greater than
>=Greater than or equal to
<Less than
<=Less than or equal to

 

Logical /Boolean Operators

 

 

OperatorDescription
&&and
||or
!not

 

 

 

 

 

 

 

 

 

String Operator

OperatorDescription
=Assignment
+Concatenate (join two string together)
+=Concatenate and assign

 

 

 

 

You will learn how to use some of the most common of these JavaScript operators in the following pages.

 

JavaScript Variables

 

Like other programming languages, JavaScript variables are a container that contains a value – a value that can be changed as required.

For example, you could prompt your website user for their first name. when they enter their first name you could store it in a variable called say, firstName. Now that you have the user’s first name assigned to a variable, you could do all sorts of things with it like display a personalized welcome message back to the user for example. By using a variable to store the user’s first name, you can writer one piece of code for all your users.

 

Declaring JavaScript variables

 

First, you need to declare your variables. You do this using the var keyword. You can declare one variable at a time or more than one. You can also assign values to the variables at the time you declare them.

 

Different methods of declaring JavaScript variables

 

//declaring one javascript variable

Var firstName;

//declaring multiple javascript variables

Var firstName, lastname;

//declaring and assigning one javascript variable

Var firstName = ‘Homer’;

//declaring and assigning multiple javascript variables

Var firstName = ‘Homer’, lastname = ‘Simpson’;

 

Using JavaScript variables

Although there are many user for JavaScript variable, here is a quick and dirty example:

</script language=”javascript” type=”text/javascript”>

<!–hide me

Var firstName = prompt(“what’s your first name?”,””);

// end  hide– >

<!– hide me

Document.write(firstName);

//end hide– >

</script>

 

The above example opens a JavaScript prompt, prompting the user for their first name. It will then write the name to the page (in practice, you would output the name somewhere between the <body></body>tags).

 

I suspect you can find a much better use for your javascript variables but this simply to demonstrate how easily you can store data inside a variable – data that could change at any moment.

 

Rules for JavaScript Variables

 

  • Can contain any letter of the alphabet, digits 0-9, and the underscore character.
  • No spaces
  • No punctuation characters (eg comma, full stop, etc)
  • The first character of a variable name cannot be a digit.
  • JavaScript variables’ names are case-sensitive. For example firstName and firstName are two different variables.

 

JavaScript functions

 

in JavaScript, you will use functions a lot. A function (also known as a method) is a self-contained piece of code that performs a particular “function”. You can recognise a function by its format- it’s a piece of descriptive text, followed by open and close  brackets.

 

Sometimes there will be text in between the brackets. This text is known as an argument. An argument is passed to the function to provide it with further info that it needs to process. This info could be different defending on the context in which the function is being called.

 

Arguments can be extremely handy, such as allowing your users to provide information (say via a form) that is passed to a function to process. For example, your users could enter their name into a form, and the function would take that name, do some processing, then present them with a personalized message that includes their name.

 

A function doesn’t actually do anything until it is called. Once it is called, it takes any arguments, then performs it’s function (whatever that may be).

 

Writing a function in JavaScript

 

It’s not that hard to write a function in java script. Here’s an example of a JavaScript function.

 

Writhe the function:

<script type=”text/javascript”>

<!–

Function display Message(firstName) {

Alert(“Hello “ + firstName + “, hope you like JavaScript function!”)

}

//–>

</script>

Call the function:

<form>

First name:

<input type=”input” name=”yourName”/>

<input

Type=”button”

OnClick=”displayMessage(from.yourName.value)”

Value=”Display Message”/>

</from>

This should work like this:

First name:

 

Explanation of code

 

Writing the function:

  1. We started by using the function keyword. This tells the browser that a function is about to be defined.
  2. Then we gave the function a name, so we made up out own name called “displayMessage”. We specified the name of an argument (“firstName”) that will be passed in to this function.
  3. After the function name came a curly bracket {. This opens the function. There is also a closing bracket later, to close the function.
  4. In between the curly brackets we write all our code for the function. In this case, we use JavaScript’s built in alert() function to pop up a message for the user.

 

Calling the function:

 

  1. We created an  HTML from with an input field and submit  button

 

  1. We assigned a name (“yourName”) to the input field

 

  1. We added the onClick event handler to the button. This event handler is called when the user clicks on the button. This is where we call our JavaScript function from. We pass it the value from the form’s input field. We can reference this value by using “from.yourName.value”.

 

JavaScript Events

 

In the previous lesson, we used an event handler to trigger off a call to our function. There are 18 event handlers that you can use to like your HTML elements to a piece of JavaScript.

 

When you write a JavaScript function, you will need to determine when it will run. Often, this will be when a user does something like click or hover over something, submit a form, double clicks on something etc.

 

These are examples of events.

 

Using JavaScript, you can respond to an event using event handlers. You can attach an event handler to the HTML element for which you want to respond to when a specify event occurs.

 

For example, you could attach JavaScript’s on Mouse over event handler to a button and specify some JavaScript to run whenever

 

This event occurs against that button.

 

The HTML 4 specification refers to these as intrinsic events and  defines 18 as listed below:

 

 

Event HandlerEvent that it  handles
onBlurUser has left the focus of the on object. For

example, they clicked away from a text field

that was previously selected.

onchangeUser has changed the object, then attempts to

leave that field (i.e. clicked elsewhere).

onClickUser clicked on the object.
ondblclickUser clicked twice on the object
onfocusUser brought the focus to the object (i.e.

clicked on it/tabbed  to it)

onkeydownA key was pressed over an element.
onkeyupA key was released over an element.
onkeypressA key was pressed over an element then

released.

onloadThe object has loaded.
onMousedownThe cursor moved over the object and mouse

/pointing device was

 

The events in the above table provide you with many opportunities to trigger some JavaScript from within your HTML code.

Class 12 Computer Science MCQ set

  Class 12 Computer Science MCQ set According to the new curriculum and grid of NEB, there is an abrupt change in question pattern. Computer...