6 of the Ajax Learning Series: Creating dom-based Web Applications

Source: Internet
Author: User

The previous article in this series examined the concepts involved in the Document Object Model (DOM) programming-How web browsers regard web pages as a tree. Now you should understand the programming structure used in Dom. In this tutorial, we will use this knowledge in practice to create a simple web page that contains some special effects. All of these are created using JavaScript to manipulate the Dom and do not need to reload or refresh the page.
The previous two articles have detailed the object model or DOM of the document. Readers should be clear about how Dom works. (For links to the first two Dom articles and earlier Ajax articles, see references .) In this tutorial, we will use this knowledge for practice. We will develop a simple web application whose user interface can be changed according to user actions. Of course, Dom should be used to handle interface changes. After reading this article, I have applied the technologies and concepts of Dom.

Assume that the reader has read the last two articles. If not, take a look at them first, grasp what Dom is and how the web browser converts the HTML and CSS provided to it into a tree structure that represents a single webpage. All the DOM principles I 've been discussing so far will be used in this tutorial to create a dom-based dynamic web page that can work (although a little simple. If you don't know anything, you can stop and review the previous two articles at any time before returning.

Starting with a sample application

Code Description

To focus on Dom and JavaScript code, I use inline styles (such as the align attribute of H1 and P elements) randomly when writing HTML ). Although this is acceptable for the experiment, it is recommended that all styles be placed in the external CSS style sheet for any product application developed.

First, we create a very simple application, and then add a little Dom magic. Remember, Dom can move anything in a Web page without submitting a form, so it is comparable to Ajax. We create a simple web page with only one normal old-style big hat on it, there is another one marked as hoocus poocus! (Guess what this is ?)

Initial html

Listing 1 shows the HTML of this webpage. In addition to the title and form, there is only one simple image and button that can be clicked.

Listing 1. html of the sample application

<HTML>
<Head>
<Title> magic hat </title>
</Head>

<Body>
<H1 align = "center"> welcome to the DOM magic shop! </H1>
<Form name = "magic-hat">
<P align = "center">

<Br/>
<Input type = "button" value = "Hocus Pocus! "/>
</P>
</Form>
</Body>
</Html>

You can find this section of HTML and the image used in this article in the download below. However, I strongly recommend that you only download the image, and then enter the code as the application is gradually established in this article. In this way, you can better understand the DOM code than reading this article and then directly opening the completed application.

View sample webpage

There are no special tips. You can view the results shown in Figure 1 when you open the webpage.

Figure 1. Ugly big hat

Supplementary instructions on html

It is important to note that the button type in Listing 1 and figure 1 is "button" rather than "submit button. If you use the submit button, clicking this button will cause the browser to submit the form. Of course, the form does not have the action attribute (this is entirely intended), which will lead to an infinite loop without any action. (Try it on your own to see what will happen .) By using a common input button instead of a submit button, you can connect the JavaScript function with it to interact with the browser without submitting a form.

Add elements to the sample application

Now you can dress up your webpage with JavaScript, Dom operations, and small image tricks.

Use the getelementbyid () function

Apparently, a magic hat has no eyes on it without rabbits. Here, we will first replace the original images on the page with the rabbit images (see Figure 1 again), as shown in figure 2.

Figure 2. Same hats, this time with rabbits

The first step to complete this Dom play method is to find the DOM node on the webpage that represents the IMG element. In general, the simplest way is to use the getelementbyid () method, which belongs to the document object representing the web page. You have seen this method as follows:

VaR elementnode = Document. getelementbyid ("ID-of-element ");

Add ID attribute for HTML

This is very simple JavaScript, but you need to modify HTML: add the ID attribute to the element to be accessed. That is, the IMG element that you want to replace (with a new image with a rabbit) is changed to the form of Listing 2.

Listing 2. Adding the ID attribute

<HTML>
<Head>
<Title> magic hat </title>
</Head>

<Body>
<H1 align = "center"> welcome to the DOM magic shop! </H1>
<Form name = "magic-hat">
<P align = "center">

<Br/>
<Input type = "button" value = "Hocus Pocus! "/>
</P>
</Form>
</Body>
</Html>

If you reload (or open) the page, you can see that there is no change. Adding the ID attribute does not affect the appearance of the page. However, this attribute helps JavaScript and Dom process elements more conveniently.

Capture IMG Elements

Now it is easy to use getelementbyid. With the ID of the required element, that is, tophat, you can save it in a new JavaScript variable. Add the code shown in listing 3 to the HTML page.

Listing 3. Accessing IMG Elements

<HTML>
<Head>
<Title> magic hat </title>
<Script language = "JavaScript">
Function showrabbit (){
VaR hatimage = Document. getelementbyid ("tophat ");
}
</SCRIPT>
</Head>

<Body>
<H1 align = "center"> welcome to the DOM magic shop! </H1>
<Form name = "magic-hat">
<P align = "center">

<Br/>
<Input type = "button" value = "Hocus Pocus! "/>
</P>
</Form>
</Body>
</Html>

It is no surprise to open or reload the webpage. Although the image can be accessed now, nothing is done for it.

How to modify Images

There are two ways to complete the modification: simple and troublesome. Like all good programmers, I also like simple methods. However, using a troublesome method is a good Dom exercise and it is worth your time. First, let's take a look at the troublesome way to change the image. Then we will analyze it again to see if there is any simpler way.

You can use a new photo with a rabbit to replace the original image as follows:

1. Create a New IMG element.
2. Access the parent element of the current IMG element, that is, its container.
3. Insert a new IMG element before the existing IMG element as the sub-level of the container.
4. Delete the original IMG element.
5. Combine them so that the user can click hoocus pocus! Call the newly created JavaScript function.

Create a new IMG element

In the last two articles, we should remember that the most important thing in Dom is the document object. It represents the entire web page, provides a powerful method such as getelementbyid (), and can create new nodes. What we need to use now is this final nature.

Specifically, you need to create a new IMG element. Remember that everything in the Dom is a node, but the node is further divided into three basic types:

1. Elements
2. Attributes
3. text nodes
There are other types, but these three types can meet the programming requirements of 99%. A new IMG element is required. The following JavaScript code is required:

VaR newimage = Document. createelement ("IMG ");

This line of code can create a new node of the element type, the element name is IMG. In HTML, basically:

Remember, Dom creates a well-structured HTML, that is, this currently empty element includes the start and end tags. The rest is to add content or attributes to the element and insert it into the webpage.

For content, IMG is an empty element. However, you need to add a property SRC that specifies the image to be loaded. You may think that you want to use methods such as addattribute (), but this is not the case. Developers of Dom standards think that programmers may like conciseness (indeed !), Therefore, they define a method to add new attributes and change the existing attribute values: setattribute ().

If you call setattribute () for an existing attribute, replace the original value with the specified value. However, if setattribute () is called and an existing attribute is specified, the DOM adds an attribute using the provided value. One method, two purposes! Therefore, add the following JavaScript code:

VaR newimage = Document. createelement ("IMG ");
Newimage. setattribute ("src", "rabbit-hat.gif ");

It creates an image element and sets the appropriate resource attributes. Now, HTML should be shown in Listing 4.

Listing 4. Use Dom to create a new image

<HTML>
<Head>
<Title> magic hat </title>
<Script language = "JavaScript">
Function showrabbit (){
VaR hatimage = Document. getelementbyid ("tophat ");
VaR newimage = Document. createelement ("IMG ");
Newimage. setattribute ("src", "rabbit-hat.gif ");
}
</SCRIPT>
</Head>

<Body>
<H1 align = "center"> welcome to the DOM magic shop! </H1>
<Form name = "magic-hat">
<P align = "center">

<Br/>
<Input type = "button" value = "Hocus Pocus! "/>
</P>
</Form>
</Body>
</Html>

You can load the page, but do not expect any changes, because the current changes have not actually affected the page. In addition, if you look at Step 1 in the task list, you will find that our JavaScript function has not been called!

Obtain the parent element of the original image.

Now you have the image you want to insert, you also need to find the place to insert. But you cannot insert it into an existing image. Instead, you need to insert it into an existing image before deleting the original image. Therefore, you need to know the parent element of an existing image. In fact, this is the real key to the insert and delete operations.

It should be noted that the previous article pointed out that Dom does regard web pages as a tree, that is, the hierarchy of nodes. Each node has a parent node (a higher level node in the tree, which is a child of it) and may have its own child nodes. For an image, it has no child level-remember that the image is a null element, but it must have a parent node. You do not even need to know what the parent node is, but need to access it.

Therefore, you only need to use the parentnode attribute that each Dom node has. For example:

VaR imgparent = hatimage. parentnode;

It's really simple! It is certain that this node has a subnode, because there is already an original image. In addition, there is no need to know that it is a DIV, P, or page body!

Insert new image

Now we get the parent node of the original image. You can insert a new image. Very simple. You can add subnodes in multiple ways:

1. insertbefore (newnode, oldnode)
2. appendchild (newnode)
Because you want to place the new image on the old image, you need to use the insertbefore () (The removechild () method will also be used later ). You can use the following JavaScript code to insert the new image element before the original image:

VaR imgparent = hatimage. parentnode;
Imgparent. insertbefore (newimage, hatimage );

Now the parent element of the original image has two child elements: the new image and the old image that follows the new image. It must be noted that the content surrounding these images has not changed, and the order of the content is exactly the same as before insertion. Only a subnode is added to the parent node, that is, the new image before the old image.

Delete old image

Now you only need to delete the old image, because only new images are needed on the webpage. It's easy, because the parent node of the old image element has been obtained. You only need to call removechild () and pass the node to be deleted to it:
VaR imgparent = hatimage. parentnode;
Imgparent. insertbefore (newimage, hatimage );
Imgparent. removechild (hatimage );

Now, the process of replacing the old image with a new image is almost complete. HTML should be shown in listing 5.

Listing 5. replacing old images with new ones

<HTML>
<Head>
<Title> magic hat </title>
<Script language = "JavaScript">
Function showrabbit (){
VaR hatimage = Document. getelementbyid ("tophat ");
VaR newimage = Document. createelement ("IMG ");
Newimage. setattribute ("src", "rabbit-hat.gif ");
VaR imgparent = hatimage. parentnode;
Imgparent. insertbefore (newimage, hatimage );
Imgparent. removechild (hatimage );
}
</SCRIPT>
</Head>

<Body>
<H1 align = "center"> welcome to the DOM magic shop! </H1>
<Form name = "magic-hat">
<P align = "center">

<Br/>
<Input type = "button" value = "Hocus Pocus! "/>
</P>
</Form>
</Body>
</Html>

Connect to Javascript

The last step, perhaps the simplest, is to connect the HTML form to the JavaScript function just compiled. Every time a user clicks hoocus pocus! Run the showrabbit () function. Therefore, you only need to add a simple onclick event handler to HTML.

<Input type = "button" value = "Hocus Pocus! "Onclick =" showrabbit (); "/>

This simple JavaScript programming should be very easy. Add it to the HTML page, save it, and open it in a web browser. The page should look the same as Figure 1 at the beginning, but click hoocus poocus! The result shown in Figure 3 is displayed.

Figure 3. Rabbit tricks

An easy way to replace Images

If you review the steps for replacing the image and look at the methods of the node, you may notice the method replacenode (). This method can be used to replace one node with another. Consider the previous steps:

1. Create a New IMG element.
2. Access the parent element of the current IMG element, that is, its container.
3. Insert a new IMG element before the existing IMG element as the sub-element of the container.
4. Delete the original IMG element.
5. Connect to the cluster so that users can click hoocus! Call the newly created JavaScript function.
Using replacenode () can reduce the number of required steps. You can combine steps 1 and 2:

1. Create a New IMG element.
2. Access the parent element of the current IMG element, that is, its container.
3. Replace the old IMG element with the new one.
4. Connect to the cluster so that users can click hoocus! Call the newly created JavaScript function.
This does not seem to be a big deal, but it can actually simplify the code. Listing 6 illustrates this change: The insertbefore () and removechild () methods are removed.

Listing 6. replacing the old image with a new image (one step)
<HTML>
<Head>
<Title> magic hat </title>
<Script language = "JavaScript">
Function showrabbit (){
VaR hatimage = Document. getelementbyid ("tophat ");
VaR newimage = Document. createelement ("IMG ");
Newimage. setattribute ("src", "rabbit-hat.gif ");
VaR imgparent = hatimage. parentnode;
Imgparent. replaceChild (newimage, hatimage );
}
</SCRIPT>
</Head>

<Body>
<H1 align = "center"> welcome to the DOM magic shop! </H1>
<Form name = "magic-hat">
<P align = "center">

<Br/>
<Input type = "button" value = "Hocus Pocus! "Onclick =" showrabbit (); "/>
</P>
</Form>
</Body>
</Html>

Of course, this is not a big change, but it illustrates a very important thing in Dom encoding: there are usually multiple methods to execute a task. If you carefully review the available DOM method to see if there is a simpler way to complete the task, you will often find that you can compress four or five steps into two or three steps.

A (real) simple way to replace Images

Since it has been pointed out that there is almost always a simpler way to execute a task, it is much easier to replace a hat image with a rabbit image. Have you thought of this method while reading this article? Note: It is related to attributes.

Remember that the image element is largely controlled by its src attribute and references a file somewhere (whether it is a local URI or an external URL ). So far, we have been replacing image nodes with new images, but it is much easier to directly modify the src attribute of existing images! This avoids creating new nodes, finding the parent node, and replacing the old node. You only need to do the following:

Hatimage. setattribute ("src", "rabbit-hat.gif ");

This is enough! Check out listing 7, which shows the solution, including the entire web page.

Listing 7. Modifying the src attribute

<HTML>
<Head>
<Title> magic hat </title>
<Script language = "JavaScript">
Function showrabbit (){
VaR hatimage = Document. getelementbyid ("tophat ");
Hatimage. setattribute ("src", "rabbit-hat.gif ");
}
</SCRIPT>
</Head>

<Body>
<H1 align = "center"> welcome to the DOM magic shop! </H1>
<Form name = "magic-hat">
<P align = "center">

<Br/>
<Input type = "button" value = "Hocus Pocus! "Onclick =" showrabbit (); "/>
</P>
</Form>
</Body>
</Html>

This is the best thing about Dom: When you update attributes, the webpage changes immediately. As long as the image points to a new file, the browser loads the file and the page is updated. No need to reload, or even create new image elements! The results are still the same as those in Figure 3, but the code is much simpler.

Hide the rabbit

The webpage looks pretty, but it is still a bit primitive. Although the rabbit jumped out of the hat, the buttons at the bottom of the screen still show hoocus! And showrabbit (). This means that if the rabbit still clicks the button after it comes out, it is a waste of processing time. More importantly, it is useless, and useless buttons are not good. Let's take a look at whether Dom can be used to make some modifications. This button can be used no matter whether the rabbit is in the hat or comes out.

Modify button label

The simplest is to change the label of a user after clicking the button. In this way, it will not look like there is any magic. The worst thing on the page is to imply that the user is wrong. You need to access the node before modifying the button label. Before that, you need to reference the button ID. This is the old rule. Listing 8 adds the ID attribute for the button.

Listing 8. Adding the ID attribute

<HTML>
<Head>
<Title> magic hat </title>
<Script language = "JavaScript">
Function showrabbit (){
VaR hatimage = Document. getelementbyid ("tophat ");
Hatimage. setattribute ("src", "rabbit-hat.gif ");
}
</SCRIPT>
</Head>

<Body>
<H1 align = "center"> welcome to the DOM magic shop! </H1>
<Form name = "magic-hat">
<P align = "center">

<Br/>
<Input type = "button" value = "Hocus Pocus! "Id =" hocuspocus"
Onclick = "showrabbit ();"/>
</P>
</Form>
</Body>
</Html>

Now it's easy to use the Javascript access button:

Function showrabbit (){
VaR hatimage = Document. getelementbyid ("tophat ");
Hatimage. setattribute ("src", "rabbit-hat.gif ");
VaR button = Document. getelementbyid ("hocuspocus ");
}

Of course, you may have entered the following line of JavaScript to change the tag value of the button. Setattribute () is used again here ():

Function showrabbit (){
VaR hatimage = Document. getelementbyid ("tophat ");
Hatimage. setattribute ("src", "rabbit-hat.gif ");
VaR button = Document. getelementbyid ("hocuspocus ");
Button. setattribute ("value", "get back in that hat! ");
}

Through this simple Dom operation, the button label will change immediately after the rabbit jumps out. Now, the HTML and finished showrabbit () functions are shown in listing 9.

Listing 9. Completed webpage

<HTML>
<Head>
<Title> magic hat </title>
<Script language = "JavaScript">
Function showrabbit (){
VaR hatimage = Document. getelementbyid ("tophat ");
Hatimage. setattribute ("src", "rabbit-hat.gif ");
Button. setattribute ("value", "get back in that hat! ");
}
</SCRIPT>
</Head>

<Body>
<H1 align = "center"> welcome to the DOM magic shop! </H1>
<Form name = "magic-hat">
<P align = "center">

<Br/>
<Input type = "button" value = "Hocus Pocus! "Id =" hocuspocus"
Onclick = "showrabbit ();"/>
</P>
</Form>
</Body>
</Html>

Reclaim the rabbit

As you may have guessed from the new button label, you need to remove the rabbit from the hat. Basically, the opposite is true for a rabbit: the src attribute of the image is changed back to the old image. Create a new JavaScript function to complete this task:

Function hiderabbit (){
VaR hatimage = Document. getelementbyid ("tophat ");
Hatimage. setattribute ("src", "tophat.gif ");
VaR button = Document. getelementbyid ("hocuspocus ");
Button. setattribute ("value", "hoocus poocus! ");
}

In fact, I simply flipped the showrabbit () function. Change the image to the original big gift hat without rabbits, capture the button, and change the label to hoocus poocus!

Event Handler

Now there is a big problem in this example application: although the button tag has changed, the action of clicking the button has not changed. Fortunately, when you click a button, you can use Dom to change events or actions. Therefore, if the "get back in that hat!" button is displayed !, You need to run hiderabbit () when clicking (). On the contrary, once the rabbit hides it, the button returns to run showrabbit ().

Avoid using addeventhandler ()

In addition to the onclick attribute, there is also a method that can be used to add Event Handlers such as onclick or onblur. It is not surprising that this method is called addeventhandler (). Unfortunately, Microsoft Internet Explorer does not support this method. If you use it in Javascript, millions of Internet Explorer users will not see anything on the webpage except errors (there may be complaints ). Without this method, the method described in this article can achieve the same effect, and it is also effective on Internet Explorer.

View the HTML and you will find that the event processed here is onclick. In JavaScript, you can use the onclick attribute of the button to reference this event. (Note: In HTML, this attribute is generally called onclick, where C is capitalized, while in Javascript it is called onclick, all in lower case .) Therefore, you can change the event triggered by the button as long as a new function is assigned to the onclick attribute.

But it is a bit subtle: The onclick attribute needs to provide function reference-not the string name of the function, but the reference of the function itself. In JavaScript, You can reference a function by name without parentheses. Therefore, you can modify the function executed when you click the button as follows:

Button. onclick = myfunction;

Therefore, it is easy to make such changes in HTML. Look at the function in listing 10, which is triggered by the switch button.

Listing 10. Changing the onclick function of a button

<HTML>
<Head>
<Title> magic hat </title>
<Script language = "JavaScript">
Function showrabbit (){
VaR hatimage = Document. getelementbyid ("tophat ");
Hatimage. setattribute ("src", "rabbit-hat.gif ");
VaR button = Document. getelementbyid ("hocuspocus ");
Button. setattribute ("value", "get back in that hat! ");
Button. onclick = hiderabbit;
}

Function hiderabbit (){
VaR hatimage = Document. getelementbyid ("tophat ");
Hatimage. setattribute ("src", "tophat.gif ");
VaR button = Document. getelementbyid ("hocuspocus ");
Button. setattribute ("value", "hoocus poocus! ");
Button. onclick = showrabbit;
}
</SCRIPT>
</Head>

<Body>
<H1 align = "center"> welcome to the DOM magic shop! </H1>
<Form name = "magic-hat">
<P align = "center">

<Br/>
<Input type = "button" value = "Hocus Pocus! "Id =" hocuspocus"
Onclick = "showrabbit ();"/>
</P>
</Form>
</Body>
</Html>

In this way, a complete and usable Dom application is obtained. Try it by yourself!

Conclusion

Now you should be very familiar with Dom. The previous article introduced the basic concepts involved in using Dom, discussed the API in detail, and now established a simple dom-based application. Take some time to read this article carefully and try it on your own.

Although this is the last part of a series of articles devoted to document object models, we will certainly see other articles about Dom. In fact, it would be hard to do much without using DOM in the Ajax and JavaScript worlds, at least to a certain extent. Dom provides a simple and easy-to-use way to access web pages, whether you want to create complex highlights, move effects, or simply process text blocks or images.

If you are still unsure about how to use Dom, spend some time reviewing these three articles. Other articles in this series will not explain more when using Dom, readers do not want to get lost in these details and ignore important information about other concepts, such as XML and JSON. To ensure that you can use the DOM skillfully, write several dom-based applications and try it. This makes it easy to understand some of the data formats that will be discussed later.

Complete examples, including HTML, graphics, and code downloads:

[Hide] [/hide]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.