Вы находитесь на странице: 1из 14

JavaScript

for Interactive Web Development

by Dileep Malayanur

First Edition

Copyright 2012 Dileep Malayanur. All rights reserved. No part of the book should be copied, reproduced, adapted, abridged, translated, stored in a retrieval system or transmitted in any form or by any means, without prior permission in writing from the author.

Now that we have looked into how various data types can exist in a typical program, we shall see at first how we can establish our code to make use of a data type to display values on web page. Before we proceed I would like to let you know that many major programs like Java, C, and C++ follow such a code where we would use different identifiers to represent different data types. But in case of scripting languages including JavaScript we have only one identifier to represent all the data types.

Step 1:- We shall see how we can display a text with a data type. Open notepad in your computer and type the following:-

<html> <head><title>My First JavaScript Program</title></head> <body> <script type=text/javascript> var myvariable = 3; alert(I have +myvariable+ apples in my hand); </script> </body> </html>
Step 2:- Save the file with name program2.html

Figure 2.1: Alert box showing the use of data type

Step 3:- Now open the file that you have saved in Step 2, you would see the alert message saying I have 3 apples in my hand.

As mentioned earlier and assuming you all know HTML quite well, we shall now look at the above program that has some tags that were not used earlier in HTML, which is script tag.

<script> tag is a special HTML tag that is used to enclose JavaScript or any other script for execution within HTML code. We can also notice an attribute called type, which has value text/javascript. Although having this attribute is optional, it explicitly tells the browser that the script code enclosed within script tag is a JavaScript or any other script!

For our better understanding we shall look out other kinds of data types as well.

<script type=text/javascript> var myname=Dileep; alert(My name is +myname); myname =Dileep Malayanur; alert(My full name is +myname); </script> or <script type=text/javascript> var alph1=A; alert(First letter of alphabet us +alph1); </script>
So we have seen how we may use different representations of data using only one identifier which is var. Caution It must be noted here that although we may use different data in same variable likewise var myname = 10; followed by myname = Dileep; we must be very cautious about data redundancy in complex code (i.e. you cannot say myname/5 as here myname has string not integer)

Operators
Operators as in any other programming languages are the special symbols used to perform some operations on the variables or values. These operations may include both mathematical and relational. Arithmetic operations include addition, subtraction, multiplication, division, modulus and assignment. These operations are represented using symbols +, -, *, % and / respectively. Again

these operators are combined to form new operators for performing other mathematical functions which are of more specific interest as described below. Increment and Decrement Operators

Increment and decrement operators are used to perform addition and subtraction of values by one count. Operator Name Increment Decrement Operator ++ -Value Before a=2 a=2 Operation a++ a-Value After a is 3 a is 1

Assignment Operators

For a program to be efficient a programmer must be able to perform more operations with less lines of code. This would not just help the performance but also for easier understandability of the code. Below table shows us the use of assignment operators as a replace of their traditional counterparts. Traditional Counterparts a = a+1; a = a-1; a = a*1; a = a/1; a = a%1; Assignment Operator a+=1; a-=1; a*=1; a/=1; a%=1;

Comparison Operators

While we are making use of few variables in our program, we may come across a situation where we need some comparisons between two values. In such cases we can make use of below mentioned comparison operators:Operator Name Equals/Comparison Not Equals Less than Greater than Less than or equal Greater than or equal Operator == != < > <= >= Usage var a=2; a==2 a!=2 a<2 a>2 a<=2 a>=2 Result True False False False True True

Logical Operators

Along with the above mentioned operators we may have to apply multiple conditions on some variables and/or values, for this purpose JavaScript provides us to use logical operators. These are listed in below table:Operator Name And Operator && Usage var a=2,b=3;
(a==2)&&(b==3)

Result True

Description Must satisfy both conditions

Switch Statement

A switch statement is a less commonly used but a very effective statement in JavaScript, as in many other programming languages like Java, C and C++. A switch statement as its name says is used to switch to a block of code based on the switch (a number or a character). Below is the syntax of switch statement:-

var switch_data = 1; switch(switch_data){ case 1: <block_of_code_for_case_1> break; case 2: <block_of_code_for_case_2> break; case 3: <block_of_code_for_case_3> break; default: <block_of_code_for_default_case> }
Or

var switch_data = a; switch(switch_data){ case a: <block_of_code_for_case_1> break; case b: <block_of_code_for_case_2> break; case c: <block_of_code_for_case_3> break; default: <block_of_code_for_default_case> }
As shown in above syntax switch statement accepts both numeric and alphabet for a switch. Based on the switch provided corresponding switch is executed, for example if switch is 1 then block of code under case 1 is executed. Default code block is executed when switch statement has no case matching switch provided.

Notice that there is a break statement used after each case, this ensures the flow will not continue to next case and so on. An example code snippet below illustrates the working of switch statement when one of the cases has no break statements.

Event Handling
Each and every HTML element is associated with many events most commonly used are onclick, onmouseover, onmouseout, onmouseup, ondbclick and onblur while there are many other events which are specific. All these events can be used in the form of an attribute to HTML element.

Below is the example of using few of the events in JavaScript associated to a button in HTML.

<html> <head> <title>Event Handling</title> </head> <body> <span onclick="javascript:this.innerHTML='You clicked me!!!'">Click me</span><br/><br/> </body> </html>

Figure 3.9: Above screenshot shows the extract of a web page before text is clicked

Figure 3.10: Above screenshot shows the extract of a web page after text is clicked

Caution Make sure you use double quotes for attributes and single quotes with in them. For example in above example we have used double quotes for attribute onclick and single quote to assign text via innerHTML property. This avoids possible JavaScript errors and adverse effect on other JavaScript statements in the web page.

Readers are advised to try more examples of event handling as these provide very good exercise to nurture the understanding of the interactivity of a web page, while throughout this book more such examples will be used which show the beauty of JavaScript.

function changeFont(eleid, font_ele){

document.getElementById(eleid).style.fontFamily=font_ele.value; } </script> </head> <body style="font-family:Tahoma;font-size:12px"> <span id="text1">This is a plain text that will be given CSS effects as chosen by you.</span><br/><br/> <button onclick="javascript:acFontColor('text1');">Apply/Clear Blue Color</button>&nbsp;&nbsp;&nbsp;<button onclick="javascript:decFontSize('text1');"></button>&nbsp;Font Size&nbsp;<button href="#" onclick="javascript:incFontSize('text1');">+</button> &nbsp;&nbsp;&nbsp;<select style="font-family:tahoma" onchange="changeFont('text1',this)"><option value="">-Choose Font--</option><option value="tahoma">Tahoma</option><option value="sansserif">Sans Serif</option><option value="verdana">Verdana</option><option value="courier">Courier</option></select> </body> </html>

Figure 4.5: Above screenshot shows the extract of a web page before clicking any button

Figure 4.6: Above screenshot shows the extract of a web page after applying color and a font

Figure 4.7: Above screenshot shows the extract of a web page after increasing font size By observing the above example we can see that how JavaScript can exploit CSS and other event handling options to make the web page more interactive. But in the above code there are few newer statements that are to be discussed. Let us for instance consider the definition of the function acFontColor and its call in the body of HTML document.

function acFontColor(eleid){ var ele = document.getElementById(eleid); if(ele.style.color.length==0){ ele.style.color = '#0000ff'; }else{ ele.style.color = ''; } }

<button onclick="javascript:acFontColor('text1');">Apply/Clear Blue Color</button>

Figure 4.8: Above screenshot shows the extract of a web page of font color button We see that the function acFontColor accepts one argument called eleid, which is the id of an HTML element, when an HTML element is assigned with an id it forms its unique identification in the web page in which it is present. The function of the implicit object of JavaScript called document, getElementById will return the reference to that HTML element. The reference of the element is nothing but a JavaScript object which has its associated functions. The function first tests if the SPAN element with id text1 has color assigned. If there is color assigned (if not assigned color will be empty and its length will be zero) then clears the same. Readers are suggested to analyze the code, understand the logic and write such new programs to gain expertise.

Figure 5.3: Above screenshot shows the extract of a web page after accepting new data

Figure 5.4: Above screenshot shows the extract of a web page after display of error for a wrong input A part of the exercise to check the different between the values of fields Sales (%) and Previous Sales (%) and assign the colors as needed is let to readers. An also users are suggested to practice more on such examples by using HTML, JavaScript and CSS while exploiting the even handling features.

Building Custom UI Elements


So far we have discussed with usage of Dynamic HTML how we can build more interactive web page, in this section we will discuss on how to build a few custom UI elements that help us to provide a more professional looking web page yet with very sophisticated UI (User Interface). Building custom UI elements ideally includes most famous HTML tag called DIV. DIV tag is a very flexible tag that helps web developers and plays a very vital role in building new UI elements and web page layouts. In our further examples let us make use of the DIV tags to build new UI elements. Developing Custom Submit Button

This example shows us how to build a custom button which can be used to submit forms. This button is based on CSS, an HTML anchor tag and JavaScript.

Observe the CSS class that is defined with various CSS attributes and assigned to an anchor tag, also a JavaScript function by name submitMyForm is assigned to an even onclick of the anchor tag. Although here the anchor tag is considered to be a replacement of a classical HTML submit button even SPAN tag can be used in the place of anchor tag.

Figure 5.5: Above screenshot shows the extract of a web page after display of custom button

Figure 5.6: Above screenshot shows the extract of a web page after mouse hovering on custom button

The search box is a plain text box where it only differs by its functionality that it offers a list of suggestions to choose when typed some of the words. The search box developed here uses more JavaScript than any other examples used in this book.

<style type="text/css" rel="stylesheet"> .suggest_list{ color:#000000; font-size:11px; font-family:Tahoma; width:270px; height:100px; z-index:100; border:1px #999999 solid; padding-top:5px; padding-left:5px; }

Figure 5.8: Above screenshot shows the extract of a web page after typing a phrase

Figure 5.9: Above screenshot shows the extract of a web page after selecting a suggestion

Note In reality suggestions are fetched from database server hosted as part of backend rather than a huge list of suggestion stored in one single JavaScript variable.

Readers are advised to re-work on this example and further improve this UI element which can append new values typed in the search box so that it can suggest user with the same next time and user do not have to type the same search text again.

Animating Web Contents


We have seen in the previous chapter how JavaScript can be exploited to develop a web-page with more interactivity and also how CSS and concepts such as Dynamic HTML help in achieving the same with much more presentation centric approach. Animating contents of a web-page is not a cutting edge technology nor is it a new invention. It is an advancement of DHTML. As days pass on demand for new trends and better experience with increasing performance rises in any service. In order to fulfill this, many of contemporary JavaScript frameworks employ DHTML to create custom UI elements such as date picker, notification pop-up and so on along with some cinch of animation in order to gain user attention and better appearance with improved look & feel.

Improving User Experience with Animation


Below examples show the differences in user experience with respect to those pages that use animated web content and those without.

Figure 8.1: Above screenshot shows an traditional JavaScript alert box

Figure 8.2: Above screenshot shows another custom DHTML notification before fadeout

All examples in this book are available @ Coders Yard websites eBook section

Please visit http://www.codersyard.com for more information

Email: author@codersyard.com
Buy EPUB, PDF and Paperback @ http://www.lulu.com/shop/search.ep?contributorId=1135198 Buy Kindle Version @ http://www.amazon.com/JavaScript-For-Interactive-Development-ebook/dp/B00A3Y9C2U Buy Amazon Paperback @ http://www.amazon.com/JavaScript-For-Interactive-Web-Development/dp/1480168467

Вам также может понравиться