Saturday, April 30, 2011

JavaScript If Statements - XI

When you write code, you will often need to use conditional statements.

A conditional statement refers to a piece of code that does one thing based on one condition, and another based on another condition. In fact, you could have as many conditions as you like.

JavaScript If statements are an example of conditional statements. With If statements, you can tell the browser to execute a piece of code only if a given condition is true.

JavaScript Events - X


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 link 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 specific event occurs.
For example, you could attach JavaScript's onMouseover event handler to a button and specify some JavaScript to run whenever this event occurs against that button.

JavaScript Functions - IX


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 depending on the context in which the function is being called.

JavaScript Variables - VIII


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 users 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 personalised welcome message back to the user for example. By using a variable to store the user's first name, you can write one piece of code for all your users.

Declaring JavaScript variables

JavaScript Operators - VII


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 whenever you need to.

Artithmetic Operators

External JavaScript File - VI


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 to 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

JavaScript and HTML - V


In previous lessons, we've learned about the syntax of JavaScript, but we haven't yet learned how to "attach" the JavaScript to our 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.

JavaScript Popup Boxes - IV


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.

Types 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:
Screenshot of a JavaScript alert box

Confirm

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

Prompt

Prompts the user for information. Example:
Screenshot of a JavaScript prompt box

Popup Code

Here's the syntax for specifying popup boxes, along with some examples.
Type of PopupSyntaxExample Code
Alertalert("Message");alert("Hey, remember to tell your friends about onlinetaleem.blogspot.com!");
Confirmconfirm("Message");confirm("Are you sure you want to delete the Internet?");
Promptprompt("Message","Default response");prompt('Please enter your favorite website', 'onlinetaleem.blogspot.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.
The following lesson explains this in more detail.

JavaScript Syntax - III


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 sub-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 variablesfunctionsstatementsoperatorsdata typesobjectsetc.
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.

Example code

How to enable JavaScript - II


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 options. This will depend on the browser you're using. Instructions for some of the more common browsers are below:

Internet Explorer (6.0):

Introduction to JavaScript - I


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 time and cover off a little bit each day. Don't worry if it takes 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?


Friday, April 29, 2011

HTML Scripts - XVIII


script is a small, embedded program that can add interactivity to your website. For example, a script could generate a pop-up alert box message, or provide a dropdown menu.
Because HTML doesn't actually have scripting capability, you need to use the <script> tag to generate a script, using a scripting language.
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.

Adding a Script

You can specify whether to make a script run automatically (as soon as the page loads), or after the user has done something (like click on a link).
In either case, a generally accepted convention is to place your scripts between the <head></head> tags. This ensures that the script is ready to run when it is called.
HTML Code:

<script type="text/javascript">
 alert("I am a script. I ran first!")
</script>

Triggering a Script

In many cases, you won't want the script to run automatically. You might only want the script to run if the user does something (like hover over a link), or once the page has finished loading.
These actions are called intrinsic events (events for short). There are 18 pre-defined intrinsic events that can trigger a script to run. You use event handlers to tell the browser which event should trigger which script. These are specified as an attribute within the HTML tag.
Lets say you want a message to display in the status bar whenever the user hovers over a link. The act of hovering over the link is an event which is handled by the onmouseover event handler. You add the onmouseover attribute to the HTML tag to tell the browser what to do next.
HTML Code:
Treat yourself to a <a href="http://www.great-workout.com/killer-ab-workout.cfm"onMouseover="window.status='Go on, you know you want to'; return true">Killer Ab Workout</a>
This results in:
Treat yourself to a Killer Ab Workout
Status bar messages aren't supported by all browsers. If you see no change to the status bar, it's likely that your browser doesn't support this piece of JavaScript.
Before we move on, check out the list of intrinsic events as specified by HTML 4.01

Calling an External Script

You can also place your scripts into their own file, then call that file from your HTML document. This is useful if you want the same scripts available to multiple HTML documents - it saves you from having to "copy and paste" the scripts into each HTML document. This makes it much easier to maintain your website.
HTML Code:
<script type="text/javascript" src="external_scripts.js"></script>

Hide Scripts from Older Browsers

Athough most (if not all) browsers these days support scripts, some older browsers don't. If a browser doesn't support JavaScript, instead of running your script, it would display the code to the user. To prevent this from happening, you can simply place HTML comments around the script. Older browsers will ignore the script, while newer browsers will run it.
HTML Code:

<script type="text/javascript">
   <-- Hide from older browsers
    alert("I am a script. I ran first!")
    Unhide -->
</script>

Alternate Information for Older Browsers

You can also provide alternative info for users whose browsers don't support scripts (and for users who have disabled scripts). You do this using the <noscript> tag.
HTML Code:

<script type="text/javascript">
   <-- Hide from older browsers
    alert("I am a script. I ran first!")
    Unhide -->
</script>

<noscript>
You need JavaScript enabled to view this page.
</noscript>

Set a Default Scripting Language

You can specify a default scripting language for all your script tags to use. This saves you from having to specify the language everytime you use a script tag within the page.
HTML Code:

<meta http-equiv="Content-Script-Type" content="text/JavaScript" />
Note that you can still override the default by specifying a language within the script tag.

HTML Styles - XVII


HTML is quite limited when it comes to the appearance of its elements. This is not so good if you're trying to give a website a unique look and feel, or you're trying to adhere to a corporate identity.
But, never fear - CSS is here!
CSS stands for Cascading Style Sheets, and its purpose is to enable web authors/designers to apply styles across their websites. With CSS, you can specify a number of style properties for a given HTML element. Each property has a name and a value, separated by a colon (:). Each property declaration is separated by a semi-colon (;).

Example of Style Sheet Usage

HTML Code:
<p style="color:olive;font-size:24px;">HTML Styles with CSS</p>

This results in:
HTML Styles with CSS
The above code is an example of inline styles. It is called inline because we declared the styles within the HTML tag itself. We could also use embedded styles or even external styles.
Embedded styles refers to declaring all styles in one place (usually the head of the document). Each element then knows to use the style that was previously declared.
External styles refers to creating a separate file that contains all style information. This file is then linked to from as many HTML pages as you like - even the whole site.

HTML Layouts - XVI


You may have noticed that many websites have multiple columns in their layout - they are formatted like a magazine or newspaper. Many websites achieved this HTML layout using tables.

HTML layout with tables

Tables have been a popular method for achieving advanced layouts in HTML. Generally, this involves putting the whole web page inside a big table. This table has a different column or row for each main section.
For example, the following HTML layout example is achieved using a table with 3 rows and 2 columns - but the header and footer column spans both columns (using the colspan attribute):
This HTML code...

<table width="400px" border="0">
  <tr>
    <td colspan="2" style="background-color:yellow;">
      Header
    </td>
  </tr>
  <tr>
    <td style="background-color:orange;width:100px;text-align:top;">
      Left menu<br />
      Item 1<br />
      Item 2<br />
      Item 3...
    </td>
    <td style="background-color:#eeeeee;height:200px;width:300px;text-align:top;">
      Main body
    </td>
  </tr>
  <tr>
    <td colspan="2" style="background-color:yellow;">
      Footer
    </td>
  </tr>
</table>
produces this layout...
Header
Left menu
Item 1
Item 2
Item 3...
Main body
Footer

HTML layout with DIV, SPAN and CSS

Although we can achieve pretty nice layouts with HTML tables, tables weren't really designed as a layout tool. Tables are more suited to presenting tabular data.
The div element is a block level element used for grouping HTML elements. Once grouped, formatting can be applied to the div element and everything contained within it. While the div tag is a block-level element, the HTML span element is used for grouping elements at an inline level.
Using our previous HTML layout, we can use DIV and CSS to achieve a similar effect. The following code...

<div style="width:400px">
  <div style="background-color:yellow">
    Header
  </div>
  <div style="background-color:orange;height:200px;width:100px;float:left;">
    Left menu<br />
    Item 1<br />
    Item 2<br />
    Item 3...
  </div>
  <div style="background-color:#eeeeee;height:200px;width:300px;float:right;">
    Main body
  </div>
  <div style="background-color:yellow;clear:both">
    Footer
  </div>
</div>
produces this layout...
Header
Left menu
Item 1
Item 2
Item 3...
Main body
Footer
One change to this that I'd recommend is that you place the CSS into an external style sheet.
One major benefit of using CSS is that, if you place your CSS in a separate location (i.e. an external style sheet), your site becomes much easier to maintain.

Advanced Layouts

As you build more websites you'll be able to develop more advanced layouts.
Because advanced layouts take time to create, a quicker option is to use a template. Web templates are basically a pre-built website that enables you to customize as required.

HTML Entities - XV


HTML entities (also known as character entity references) enable you to use characters that aren't supported by the document's character encoding or your keyboard. For example, you can type &copy; to output a copyright symbol.
You can also use numeric character references. Numeric character references can be defined with either a decimal or hexadecimal value (although decimal is more common). The numeric character reference for the copyright symbol is &#169; (decimal) and&#xA9; (hexadecimal).
A key benefit that numeric character references have over entities is that they can be used to specify any unicode character, whereas entities can only specify some.

Entity Example

Many web developers use entities for outputing HTML code to the browser (or at least, outputing one of the characters used by the HTML language).
Lets say you have a website about web design. And lets say you want to display the tag required for creating a horizontal rule 20% wide. Well, if you type the tag (<hr width="20%" />) into your code, the browser is simply going to render it as it should be (rather than output the actual code example). Like this...

... you see, instead of displaying the code, the browser rendered the code.
What you should have typed in is this:
&lt;hr width="50%" /&gt;
The &lt; replaces the < and the &gt; replaces the >.