Using Dynamic HTML Methods to Update Part of a Page


In Ajax, you frequently want to update just part of a Web page, not the whole page. Two methods enable you to do this: the insertAdjacentHTML method, which lets you insert HTML next to an element that already exists, and the insertAdjacentText method, which lets you insert text in the same way. You can determine where the new text or HTML will go with respect to the already existing element by passing the constants BeforeBegin, AfterBegin, BeforeEnd, or AfterEnd to insertAdjacentHTML and insertAdjacentText.

The example insertAdjacent.html uses the insertAdjacentHTML method. This page starts with just a button, as shown in Figure 11.13. When you click the button, the code inserts a new text field into the Web page, as shown in Figure 11.14.

image from book
Figure 11.13: The insertAdjacent.html application

image from book
Figure 11.14: Inserting a new text field into a page

Here’s how it works: the application contains a <div> element with the ID div1:

 <body>     <center>         <h1>             Updating part of a page         </h1>     </center>     <div >     .     .     .     </div> </body>

and that <div> element contains the button, which is connected to a JavaScript function named

 update: <body>     <center>         <h1>            Updating part of a page          </h1>     </center>     <div >         <input type=button value="Click Me!"           onclick="update()">     </div> </body>

In the update function, you can call the <div> element’s insertAdjacentHTML method to insert the text field next to the <div> element:

 <head>     <title>         Updating part of a page     </title>     <script language="JavaScript">         function update()         {             div1.insertAdjacentHTML(...);         }     </script> </head>

Here’s how you insert the new text field after the end of the <div> element:

 <head>     <title>         Updating part of a page     </title>     <script language="JavaScript">         function update()         {             div1.insertAdjacentHTML("AfterEnd",             "<p>Here's A new text field: <input               type=text value='Hello!'></p>");         }     </script> </head>

Using insertAdjacentHTML and insertAdjacentText, you can insert HTML and text into a Web page, adjacent to another Web page item. In fact, there’s another way to insert text and HTML into a Web page besides using these methods: you can use dynamic HTML properties, which gives you even finer control than the insertAdjacentHTML and insertAdjacentText methods.



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

Similar book on Amazon
HTML, XHTML, and CSS Bible
HTML, XHTML, and CSS Bible
JavaScript Bible
JavaScript Bible
JavaScript Bible
JavaScript Bible
PHP and MySQL Web Development (4th Edition)
PHP and MySQL Web Development (4th Edition)

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net