1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Web Programming with HTML, XHTML, and CSS Second Edition- P11 docx

50 546 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Working With Javascript
Trường học Wrox Press
Chuyên ngành Web Programming
Thể loại sách
Năm xuất bản 2008
Thành phố Birmingham
Định dạng
Số trang 50
Dung lượng 0,94 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

For example, ifone of the controls on a form is to provide a date of birth in MM/DD/YYYY format, then you can movefocus between the three boxes as soon as the user enters a month, and th

Trang 1

To give focus to the first text input on a form, simply add an onloadevent handler to the <body>element

of the document This handler selects the form control that you want to highlight and uses the focus()method of that control to give it focus, as follows (ch12_eg10.html):

Auto-Tabbing Between Fields

The focus()method can also be used to pass the focus of one control to another control For example, ifone of the controls on a form is to provide a date of birth in MM/DD/YYYY format, then you can movefocus between the three boxes as soon as the user enters a month, and then again once the user has entered

a day (ch12_eg11.html):

<form name=”frmDOB”>

Enter your date of birth:<br />

<input name=”txtMonth” id=”txtMonth” size=”3” maxlength=”2”

onkeyup=”if(this.value.length>=2)this.form.txtDay.focus();”/>

<input name=”txtDay” id=”txtDay” size=”3” maxlength=”2”

onkeyup=”if(this.value.length>=2)this.form.txtYear.focus();” />

<input name=”txtYear” id=”txtYear” size=”5” maxlength=”4”

onkeyup=”if(this.value.length>=4)this.form.submit.focus();” />

<input type=”submit” name=”submit” value=”Send” />

</form>

This example uses the onkeyupevent handler to check that the length of the text the user has entered isequal to or greater than the required number of characters for that field If the user has entered the requirednumber of characters, the focus is moved to the next box

Note how the length of the text input is discovered using this.value.length The thiskeyword cates the current form control, whereas the valueproperty indicates the value entered for the control

Trang 2

indi-Then the lengthproperty returns the length of the value entered for the control This is a quicker way

of determining the length of the value in the current form control than the full path, which would be, asfollows:

document.fromDOB.txtMonth.value.length

The other advantage of using the thiskeyword rather than the full path is that the code would work if you copied and pasted these controls into a different form, as you have not hard-coded the name of the form in.

You can see this example in Figure 12-11; the user has entered an appropriate number of digits in onefield so the focus is moved on to the next

Figure 12-11

You might have noticed that the value of the sizeattribute is also one digit larger than the maximumlength of the field to ensure that there is enough space for all of the characters (usually the width of thecontrol will be slightly too small to see all of the characters at once)

I have seen this technique used to allow users to enter their credit card details using four blocks of four codes While 16 digits is the most common length for a credit card number, and they are often printed in blocks of four digits, some Visa cards, for example, contain 13 digits and some American Express cards use 15 digits.

Disabling a Text Input

Sometimes you will want to disable a text input until a certain condition has been met — just as theSubmit button was disabled until the user clicked the checkbox to agree to terms and conditions inFigure 12-9

This example features a form that asks users how they heard about the site; radio buttons are used forseveral options such as Friend, TV ad, magazine ad, and then an option of Other If the user selects theOther option, the text input next to that option allows the user to indicate how they heard about the site.You can see the form in Figure 12-12

In this example, it’s not just a case of enabling the text box when the user selects the other radio button;you really need to check the value of each radio button as it is selected — after all, if the user selects Other

as his or her first choice, but then changes her mind and selects TV or one of the other options, you willwant to disable the text input and change its value again Therefore, each time the user selects a radio but-ton, a function in the head of the document is called that is responsible for enabling and disabling the con-trol and setting values

Trang 3

Figure 12-12

First, here is the form that gives users the options (ch12_eg12.html) Note how the text input is abled using the onloadevent handler of the <body>element and that the text input does not use thedisabledattribute (this is the same as the earlier example with the Submit button)

dis-<body onload=”document.frmReferrer.txtOther.disabled=true;

document.frmReferrer.txtOther.value=’not applicable’ “>

<h2>How did you hear about us?</h2>

<form name=”frmReferrer”>

<input type=”radio” name=”radHear” value=”1”

onclick=”handleOther(this.value);” />From a friend<br />

<input type=”radio” name=”radHear” value=”2”

onclick=”handleOther(this.value);” />TV Ad<br />

<input type=”radio” name=”radHear” value=”3”

onclick=”handleOther(this.value);” />Magazine Ad<br />

<input type=”radio” name=”radHear” value=”4”

onclick=”handleOther(this.value);” />Newspaper Ad<br />

<input type=”radio” name=”radHear” value=”5”

onclick=”handleOther(this.value);” />Internet<br />

<input type=”radio” name=”radHear” value=”other”

onclick=”handleOther(this.value);” />Other Please specify:

<input type=”text” name=”txtOther” />

</form>

As you can see from this form, every time the user selects one of the options on this form, the onclickevent calls a function called handleOther() This function is passed the value of the form control as aparameter

Looking at the function, you can see that it checks whether the value of the form control is equal to thetext other(remember that checking whether one value is equal to another value uses two equal signsbecause the single equal sign is used to set a variable)

function handleOther(strRadio) {

if (strRadio == “other”) {document.frmReferrer.txtOther.disabled = false;

document.frmReferrer.txtOther.value = “;

}else {

Trang 4

document.frmReferrer.txtOther.disabled = true;

document.frmReferrer.txtOther.value = ‘not applicable’;

}}

Here you can see a simple if elsestatement that looks at the value of the radio button, which has beenpassed in as an argument If the value is other, the control is enabled, and the value set to nothing — other-wise it is disabled and the value is not applicable

Case Conversion

There are times when it is helpful to change the case of text a user has entered to make it all uppercase orall lowercase — in particular because JavaScript is case-sensitive To change the case of text, there aretwo built-in methods of JavaScript’s String object:

as you use it can appear a little odd to users.

Trimming Spaces from Beginning and End of Fields

You might want to remove spaces (white space) from the beginning or end of a form field for many sons, even simply because the user did not intend to enter it there The technique I will demonstrate hereuses the substring()method of the String object, whose syntax is:

be called upon twice

First you can use the substring()method to retrieve the value the user has entered into a text controland just return the first character You check if this first character returned is a space:

this.value.substring(0,1) == ‘ ‘

Trang 5

If this character is a space, you call the substring()method a second time to remove the space This time

it selects the value of the control from the second character to the end of the string (ignoring the first acter) This is set to be the new value for the form control; so you have removed the first character, whichwas a space

char-this.value = char-this.value.substring(1, char-this.value.length);

This whole process of checking whether the first character is a blank, and then removing it if it is, will

be called using the onblurevent handler; so when focus moves away from the form control the processstarts You can see here that the process uses a whileloop to indicate that for as long as the first character

is a blank then it should be removed using the second call to the substring()method This loop makessure that the first character is removed if it is a blank until the substring no longer returns a blank as thefirst character (ch12_eg14.html)

<form>

<input type=”text” name=”txtName” size=”100”

value=” Enter text leaving whitespace at start Then change focus.”

onblur=”while (this.value.substring(0,1) == ‘ ‘)this.value = this.value.substring(1, this.value.length);” /><br />

</form>

To trim any trailing spaces the process is similar but reversed The first substring()method collects thelast character of the string, and if it is blank removes it, as follows:

<form>

<input type=”text” name=”txtName” size=”100”

value=”Enter text leaving whitespace at end Then change focus “onblur=”while (this.value.substring

(this.value.length-1,this.value.length) == ‘ ‘)this.value = this.value.substring(0, this.value.length-1);” /><br />

</form>

As long as you are not targeting browsers as old as Netscape 4 and IE4, you can alternatively use aRegular Expression to trim the spaces, as follows:

<form>

<input type=”text” name=”removeLeadingAndTrailingSpace” size=”100”

value=” Enter text with white space, then change focus “onblur = “this.value = this.value.replace(/^\ \s+/, “).replace(/\s+$/, “);”/><br />

</form>

This removes both trailing and leading spaces

Regular Expressions are quite a large topic in themselves If you want to learn more about them, then you

can refer to Beginning JavaScript 2nd Edition by Paul Wilton (Wrox, 2000).

Selecting All the Content of a Text Area

If you want to allow users to select the entire contents of a text area (so they don’t have to manually selectall the text with the mouse), you can use the focus()and select()methods

Trang 6

In this example, the selectAll()function takes one parameter, the form control that you want to selectthe content of (ch12_eg15.html):

<html>

<head><title>Select whole text area</title>

<script language=”JavaScript”>

function selectAll(strControl) {strControl.focus();

<textarea name=”myTextArea” rows=”5” cols=”20”>This is some text</textarea>

<input type=”button” name=”btnSelectAll” value=”Select all”

Check and Uncheck All Checkboxes

If there are several checkboxes in a group of checkboxes, it can be helpful to allow users to select or lect a whole group of checkboxes at once The following are two functions that allow precisely this:function check(field) {

dese-for (var i = 0; i < field.length; i++) {field[i].checked = true;}

}function uncheck(field) {for (var i = 0; i < field.length; i++) {field[i].checked = false; }

}

In order for these functions to work, more than one checkbox must be in the group You then add twobuttons that call the check or uncheck functions, passing in the array of checkbox elements that share the same name such as the following (ch12_eg16.html):

<form name=”frmSnacks” action=””>

Your basket order<br />

Trang 7

<input type=”checkbox” name=”basketItem” value=”1” />Chocolatecookies<br />

<input type=”checkbox” name=”basketItem” value=”2” />Potato chips<br />

<input type=”checkbox” name=”basketItem” value=”3” />Cola<br />

<input type=”checkbox” name=”basketItem” value=”4” />Cheese<br />

<input type=”checkbox” name=”basketItem” value=”5” />Candy bar<br /><br />

<input type=”button” value=”Select All”

for(z=0; z<theForm.length;z++){

if(theForm[z].type == ‘checkbox’ && theForm[z].name != ‘checkall’){

theForm[z].checked = field.checked;

}}}

Try It Out An E-mail Form

In this exercise you are going to create an e-mail form that has a few interesting features It uses a RegularExpression to check the structure of an e-mail address and also checks that all fields have an entry of somekind The form includes a quick address book that contains addresses of potential recipients of the e-mail.Figure 12-14 shows you what the form is going to look like; it also shows the message that appears whenthe user tries to submit the e-mail without entering a message

Trang 8

Figure 12-14

1. First create a skeleton XHTML document with <head>, <title>, and <body>elements

2. In the body of the document, add the <form>element and two <div>elements The first <div>holds the To, CC, and Subject fields, while the second holds the quick address

<form name=”frmEmail” onsubmit=”return validate(this)” action=”sendMail.aspx”method =”post”>

<div id=”toCCsubject”>

<div class=”label”>Send to:</div>

<div class=”input”><input type=”text” size=”70” name=”txtTo” /></div>

Trang 9

field and one to add addresses to the txtCCfield Both of these buttons call the add()functionwhen clicked:

Quick address book:<br />

<select size=”4” name=”selectList1” style=”width:150px”>

<textarea name=”message” rows=”20” cols=”115”></textarea><br />

<input type=”submit” value=”Send E-mail” />

5. Now you need to add the validation function and the add()function First, here is the add()function that adds e-mail addresses from the address book to the To or CC fields (if there isalready an address in there, the semicolon is added to separate out multiple addresses):

function add(objInput, objList){\{}

var strGroup = objList.options[objList.selectedIndex].value;

if (objInput.value == “”){

objInput.value = strGroup}

else{objInput.value += (‘; ‘ + strGroup)}

}

6. Here is the validate()function, which you can see is quite long:

function validate(form) {var returnValue = true;

var sendTo = form.txtTo.value;

var cc = form.txtCC.value;

var subject = form.txtSubject.value;

var message = form.txtMessage.value;

if (sendTo == ""){

returnValue = false;

alert("There are no email addresses in the To field");

form.txtTo.focus();

}

Trang 10

if (subject == ""){

returnValue = false;

alert("There is no message to this e-mail");

form.txtMessage.focus();

}var arrTo = sendTo.split("; ");

var rxEmail=/\^\w(\.?[\w-])*@\w(\.?[\w-])*\.[a-z]{2,6}(\.[a-z]{2})?$/i;for (var i=0; i<(arrTo.length); i++) {

if (!rxEmail.test(arrTo[i])){

returnValue = false;

alert("The e-mail address "+ arrTo[i] +" does not appear to be valid");}

}var arrCC = cc.split("; ");

for (var i=0; i<(arrCC.length); i++) {

if (!rxEmail.test(arrCC[i])){

returnValue = false;

alert("The e-mail address "+ arrCC[i] +" does not appear to be valid");}

}return returnValue;

❑ objInput: The field that the selected address is being sent to

❑ objList: The select list that contains the e-mail addressesThis function starts by collecting the value of the selected item, using the selectedIndexproperty of theselect list and placing it in a variable called strGroup Next it checks whether the form field the address isbeing added to is empty; if it is, the e-mail address stored in the strGroupattribute is added to the field

If the Toor CCfield is not empty, a semicolon and a space will be added before the e-mail address becausethis is the usual delimiter for multiple e-mail addresses:

function add(objInput, objList){

var strGroup = objList.options[objList.selectedIndex].value;

if (objInput.value == “”){

Trang 11

objInput.value = strGroup}

else{objInput.value += (‘; ‘ + strGroup)}

}

The validate()function is slightly more complex, starting off by setting a returnValuevariable totrueand collecting the form’s values into variables

function validate(form) {var returnValue = true;

var sendTo = form.txtTo.value;

var cc = form.txtCC.value;

var subject = form.txtSubject.value;

var message = form.txtMessage.value;

It checks to see if the To, Subject line, and Message body fields are empty, and if so sets the returnValueattribute to false, and indicates to the user that something must be added for that field using an alertbox — this is very similar to the examples you saw earlier in the chapter:

if (sendTo == “”){

var arrTo = sendTo.split(“; “);

Imagine having the following e-mail addresses (note that this is just to illustrate the split()method; it

is not part of the code):

sales@example.com; accounts@example.com; marketing@example.com

These would be split into the following array (again, this is not part of the code from the example):arrTo[0] = “sales@example.com”

arrTo[1] = “accounts@example.com”

arrTo[2] = “marketing@example.com”

Trang 12

So now there has to be a forloop in the code that will go through each e-mail address in the array andcheck that it follows the pattern described in the Regular Expression The forloop has three parame-ters; the first sets a counter called ito be 0, checks that the counter is less than the number of items inthe array, and finally increments the counter Inside the loop is an ifstatement that checks whether thee-mail address matches the Regular Expression using the test()method; if it does not, it will set thereturnValueto falseand alert the user that the value does not seem to be a valid e-mail address:for (var i=0; i<(arrTo.length); i++) {

if (!rxEmail.test(arrTo[i])){

returnValue = false;

alert(“The email address “+ arrTo[i] +” does not appear to be valid”);

}}

After this you can see a similar setup for the CC field

var arrCC = cc.split(“; “);

for (var i=0; i<(arrCC.length); i++) {

if (!rxEmail.test(arrCC[i])){

returnValue = false;

alert(“The e-mail address “+ arrCC[i] +” does not appear to be valid”);

}}return returnValue;

}

Now you have an example of a form that has more than one function It uses JavaScript to create a quickaddress book and validates the entries to stop the user from trying to send an e-mail address that is notvalid

Image Rollover sYou met a simple example of an image rollover in the last chapter, but in this chapter you will meet afunction that allows you to change several images on the same page This function can then be used with all pages rather than repeating the same script in several pages

To create a rollover image you need two different versions of an image:

❑ The normal image that the user sees when the mouse is not hovering over the image

❑ The other image that appears when the user rolls the mouse over the image

In the last chapter, you saw a very simple image rollover script that was added to an <a>element thatcontained the image When the user rolls the mouse over the link (containing the image) an onmouseoverevent fires and the srcproperty of the image object is changed to the mouseover image When the mousemoves off the image the onmouseoutevent changes the image’s srcproperty back to the original image

Trang 13

(If only one of these events were monitored, the image would simply change, not go back to its initialstate, so it’s important to monitor both.)

You can see that this image’s nameattribute has a value of button, which is used to identify the image

in the event handler:

When creating rollover images that contain text, you should generally use the same size and weight of text on both images Text that suddenly appears larger or bold can be hard to read Changing the back- ground color slightly tends to be a better option.

Creating an image rollover function is the logical next step when you want to use the same rolloverimages on several pages — for example if you are creating a navigation bar that changes color as usersmove their mouse over each item Figure 12-15 shows you a navigation bar that does just that

Figure 12-15

Each image in this navigation bar is contained in a link, and each image must have a different name Aswith the last example, it is the <a>element that carries the event handlers When the user places themouse over the link, an onmouseoverevent calls the changeImages()function, and when the mousemoves off the link an onmouseoutevent calls the same function but passes in values to indicate that theoriginal image should be shown again

The changeImages()function has two arguments — the first is the name of the image, the second is thename of a variable that holds the URL of the image that will replace the current one Note how the value

of the image’s nameattribute corresponds with the parameters being passed when the onmouseoverandonmouseoutevents fire (ch12_eg17.html):

Trang 14

This script that does the real work lives in the scriptsfolder and is in a file called rollover.js Thisscript can be included in any page that is going to include a rollover.

Remember that there are two images for each rollover — when the mouse is over the image it is “on,”and when the mouse is off the image it is “off.”

Each image is assigned two variables, one for when the mouse is over it and one for when it is off it Thevariables hold an image object whose srcproperty is the URL for the image First you see the imagesused when there are rollovers and then the images used in the normal state:

if (document.images) {image1on = new Image();

eval(changeImages.arguments[i+1] + “.src”);

}}}

The lines that are doing the real work here are the ones in the middle If the user has moved his or hermouse over the first image, the function will be called like this:

onsubmit=”changeImages(image1, image1on)”

The first value being passed in is the value of the nameproperty on the image So the following line in thefunction tells the browser to take the first argument of the changeImages()function (which is image1)and change the srcproperty of this element:

document[changeImages.arguments[i]].src =

Trang 15

The last thing on this line is the equal (=) sign This property still has to be set, and the code on the nextline is the code that actually provides the value This next line is saying the property should be given thevalue of the second argument in the function:

eval(changeImages.arguments[i+1] + “.src”);

You may remember from the last chapter that the forloop takes the following three arguments:

❑ The first argument runs only once and in this case sets the value of the counter to be 0 (i-0)

❑ The second argument indicates whether the loop should run again In this case, if the counter isless than the number of arguments passed to the changeImages()function, it should run again

❑ The third argument increments the counter by two

This means that the changeImages()function can be used to change more than one image, because youcan call the function with different sets of parameters

Random Script GeneratorThere are times when it is helpful to use a script to select a random value The following script can beused to select a random piece of content from a predefined array You might like to use it to add ran-dom quotes or tips, or you could use it to rotate advertisements or images The script contains a func-tion called randomContent()that includes the content that will be selected at random

The content is added to an array called arrContentand the array contains the data you want to appearrandomly:

<script language=”JavaScript”>

function randomContent(){

var arrContent=new Array()arrContent[0]=’This is the first message.’

arrContent[1]=’This is the second message.’

arrContent[2]=’This is the third message.’

arrContent[3]=’This is the fourth message.’

arrContent[4]=’This is the fifth message.’

A variable called iis then set to a random value between 0and the number of items in the array In order

to generate this random number, you need to call two methods of the Math object The random()methodgenerates a random number between 0 and 1 and this is multiplied by the number of elements in the array.The number is then rounded to the nearest integer (whole number) equal to or less than the number gener-ated using the floor()method

The floor()method is used rather than the round()method because you could end up with a numberhigher than the number of items in the array if you used the round()method

var i=Math.floor(Math.random()*arrContent.length)document.write(arrContent[i])

}

</script>

Trang 16

Wherever you want to include the random content, you just call that function:

a site load, and they often feature advertisements or unwanted information There are, however, somevery legitimate uses for pop-up windows For example, you might just want to keep users on the currentpage while allowing them to provide some other information in a pop-up, or you might want to opensomething from your site (such as an image) in a new window without the user losing his or her place

Of course, you can create a normal link and make the page open in a new window by adding the target=

”_new”attribute, but when you create a pop-up in JavaScript you can control the dimensions of the dow, indicate whether it can be resized or not, and whether it has scrollbars (ch12_eg19.html)

win-<ahref=”http://google.com/”

Trang 17

You can list several features after the window name, and the following table shows you those available.

As you can see, they allow you to control several properties of the window including size and positionand whether the screen has scrollbars or not — but remember that users with different resolution mightrequire scrollbars even if you do not

You should be aware that some pop-up blocking software might prevent functions like this from ing You should also avoid using words such as “pop-up” (or “popup”) in your filenames even whencreating pop-up windows because some pop-up window blockers look for words like these in your file-names and will not open files containing them

work-You can create pop-up windows in JavaScript in several ways, but I strongly recommend that you use this approach if you choose to create them with JavaScript because many other methods prevent a user from right-clicking the link and opening it in a new window themselves More experienced web browsers often enable you to open a link in a new window with the right mouse button, and some methods of creat- ing pop-ups mean that users who take this approach (choosing to open the link in a new window them- selves) will just get a blank window This approach solves the problem.

JavaScript LibrariesThe examples you have seen so far in this chapter have been designed to give you a better understanding

of how JavaScript works with your XHTML documents Now you are going to take a look at some ples that work with some of the popular free JavaScript libraries that you can download via the Web

exam-Feature Value Sets

width Number The width of the new window in pixelsheight Number The height of the new window in pixelsleft Number The location where the left side of the window should appeartop Number The location where the top of the window should appearlocation yes/no Controls whether the browser should display the browser location

toolbarmenubar yes/no Controls whether the browser should display the menu barresizable yes/no Allows the user to resize the browser window

scrollbars yes/no Controls whether horizontal or vertical scrollbars are shownstatus yes/no Controls the display of the status bar (the area at the bottom of the

browser)toolbar yes/no Controls whether the browser should display the buttons toolbar

Trang 18

JavaScript libraries are simply JavaScript files that contain code that helps programmers perform taskscommonly used in web pages with just a few lines of code You will be looking at examples that allowyou to do the following:

❑ Create animated effects, such as fading out text, or shrinking boxes

❑ Re-order items in a bulleted list

Animated Effects using Scriptaculous

Scriptaculous can help you with many kinds of tasks: animation, drag-and-drop functionality, editing tools,and autocompleting of text inputs, as well as utilities to help create DOM fragments In this section, youlook at some of the animation effects

As I’ve already mentioned, Scriptaculous was built on top of another JavaScript library called Prototype

I have included a copy of Scriptaculous 1.8.0 and Prototype 1.6.0 with the code download for this ter; however, you can check for more recent versions and download your own copy of these files fromhttp://script.aculo.us/

chap-Scriptaculous contains functions that help you create several different types of animations this example

is going to demonstrate just four of the animated effects you can achieve with Scriptaculous, but this will

be enough to demonstrate the flexibility of these effects, and how easily you can integrate them into yourpages You can see what this page will look like in Figure 12-17, although you really need to try the exam-ple out to see the animation effects in ch12_eg20.html

In order to use the Scriptaculous library, you need to create references to both prototype.jslibrary,which is in the lib folder inside the scriptaculous folder, and the scriptaculous.jslibrary, which is inthe src folder inside the scriptaculous folder (if you look in the src folder there are several other scriptsthat this JavaScript file loads)

<script src=”scripts/scriptaculous/lib/prototype.js”

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

<script src=”scripts/scriptaculous/src/scriptaculous.js”

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

Trang 20

<div class=”demo” id=”demo-effect-fade” onclick=”new Effect.Fade(this);

window.setTimeout(‘Effect.Appear(\’demo-effect-fade\’, {duration:.3})’,2500);”>Effect.Fade

</div>

</div>

You do not need to know how the Script creates these effects; all you need to know is that to access the effects

you create an Effect object (using new Effect), and then the syntax of the method that calls each effect Let’s start by looking at the first box, which uses a shake effect to move it left and right:

You might have noticed that the next three elements contain a second line after the effect has been called.This is because each of the other effects makes the box disappear So the Appear()method is called after

a fixed duration so you can try the example again (and it is the Appear()method that is using the value

of the idattribute to indicate which element needs to re-appear); but the other effects are still called usingEffect.methodname(this)

<div class=”container”>

<div class=”demo” id=”demo-effect-shrink” onclick=”new Effect.Shrink(this);

window.setTimeout(‘Effect.Appear(\’demo-effect-shrink\’,{duration:.3})’,2500);”>

Effect.Shrink

</div>

</div>

As you can see, this is a very simple way of creating animated effects using JavaScript

Drag-and-Drop Sortable Lists Using Scriptaculous

The second of the two tasks you will look at using Scriptaculous is creating drag-and-drop lists You mayhave seen some sites where you can re-order lists (such as to do lists or top 10 lists) just by dragging anddropping the elements

Trang 21

You can see the example you are going to build in Figure 12-18; when the page loaded, the boxes were innumerical order However, they have now been dragged and dropped to a different order

Figure 12-18

In this example (ch12_eg21.html), you need to include the Scriptaculous and Prototype libraries again.Then you have a simple unordered list (there are some CSS rules in the head of the document that controlthe presentation of the list to make it appear like boxes)

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

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

<style type=”text/css”>

li {border;1px solid #000000; padding:10px; margin-top:10px;

font-family:arial, verdana, sans-serif;background-color:#d6d6d6;

<li id=”item_1”>Item 1</li>

<li id=”item_2”>Item 2</li>

<li id=”item_3”>Item 3</li>

<li id=”item_4”>Item 4</li>

</ul>

Then you just need to add one <script>element after the list so that it can be re-ordered:

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

Trang 22

❑ The second are options that describe how the sortable list should work The first is dropOnEmptywith a value of trueto indicate that element should only be dropped between elements, not ontop of another one, and the constraintproperty which is set to false(if this were left off ortrue, it would only allow items to be moved along a vertical axis)

In order for this kind of drag-and-drop list to be of use to people, such lists are often tied into some codethat will update a database, such as ASP.Net, PHP, JSP, or Ruby on Rails code However, this exampledoes demonstrate something that is achieved very easily with just a few lines of code, thanks to theScriptaculous library

Sortable Tables with MochiKit

In this example, you are going to look at another JavaScript library — MochiKit By looking at a few ferent examples, you can see how easy different libraries (which offer different functionality) are to pluginto your pages You can download the latest version of MochiKit from www.mochikit.com/, although Ihave included version 1.3.1 with the download code for this chapter

dif-In this example you will create a table, whereby you can sort the contents of the table by clicking on theheader of any of the columns of the table in order to sort the data by that column You can see in Figure 12-19how the table heading Date Started has an up arrow next to it, indicating that the table’s contents are beingordered by the date the employee started (in ascending order)

Figure 12-19

In order to create a sortable table, you again need to include two scripts; the first is for the MochiKit.jsJavaScript library, and the second is for the sortable_tables.jsfile that comes with the MochiKitdownload (ch12_eg22.html)

Trang 23

The interesting part for you is the table, and how you make that integrate with the MochiKit scripts Threeparts of the page need to be identified to work with the scripts:

The <table>element needs an idattribute whose value is sortable_table

The <th>(table heading) elements need to have an attribute called mochi:sortcolumn, whose value is

a unique id for that column, followed by a space, followed by the datatype for that column (which can

be a strfor a string or isoDatefor a date in the format shown)

The first row of <td>elements needs to have mochi:contentattributes whose value is the keyworditem, followed by a period, followed by the unique id for the column that was specified in themochi:sortcolumnattribute in the corresponding header

<table id=”sortable_table” class=”datagrid”>

<thead>

<tr>

<th mochi:sortcolumn=”name str”>Name</th>

<th mochi:sortcolumn=”department str”>Department</th>

<th mochi:sortcolumn=”datestarted isoDate”>Date started</th>

<th mochi:sortcolumn=”extension str”>Employee ID</th>

Trang 24

Creating Calendars with YUI

The third and final JavaScript library you will be looking at is the Yahoo User Interface library This iscreated by Yahoo, and is the largest of the three libraries, with all kinds of functionality I have includedversion 2.4.0 with the code download for this chapter; however, you can download the latest examplefrom http://developer.yahoo.com/yui/

You will start by looking at how you can easily drop a calendar onto a web page using this framework Youcan see what the calendar will look like in Figure 12-20

For this example, you will also include a couple of CSS files that are included with the YUI download:

<link rel=”stylesheet” type=”text/css”

Trang 25

YAHOO.example.calendar.cal1 = new YAHOO.widget.Calendar(“cal1”,”cal1Container”);YAHOO.example.calendar.cal1.render();

}YAHOO.util.Event.onDOMReady(YAHOO.example.calendar.init);

</script>

Rather like some of the other examples in this section, this is likely to be tied into some other kind offunctionality, such as a holiday booking form where you are specifying dates you want to travel or anevents list where you are looking at what is happening on a particular date But this does demonstratehow libraries can be used to add significant functionality to your pages with ease

Auto-Completing Text Inputs with YUI

The final example you will look at in this section is the ability to create text inputs where you make gestions as to what the users are trying to type The example allows you to enter the name of a U.S state,and will make suggestions as to which state you are trying to enter

sug-You can see what the input will look like in Figure 12-21

Ngày đăng: 14/12/2013, 21:16