Saturday, October 17, 2009

Reposition a DOM element using Ajax


For handling the DOM elements, Microsoft Ajax library has a Class named DomElement in the Sys.UI namespace. The DomElement class has 2 methods as follows:

a) getLocation(element-name): returns the (x,y) coordinate of the DOM element.
b) setLocation(element, x-pos, y-pos): sets the DOM element to (x,y) position.

Here is a simple example on repositioning a DOM element using the Ajax library;

[Ajax Script]

   1: <script type="text/javascript">
   2:         //Page Load
   3:         function pageLoad() {
   4:             var btnGet = $get("btnGetPos");
   5:             var btnSet = $get("btnSetPos");
   6:  
   7:             $addHandler(btnGet, "click", getXYLocation);
   8:             $addHandler(btnSet, "click", setXYLocation);
   9:             
  10:             
  11:         }
  12:  
  13:         // Get (X,Y) Location
  14:         function getXYLocation() {
  15:             var location = Sys.UI.DomElement.getLocation(div1);
  16:  
  17:             var tbX = $get("tbXpos");
  18:             var tbY = $get("tbYpos");
  19:  
  20:             tbX.value = location.x;
  21:             tbY.value = location.y;
  22:         }
  23:         
  24:         // Set (X,Y) Location
  25:         function setXYLocation() {
  26:             var tbX = $get("tbXpos").value;
  27:             var tbY = $get("tbYpos").value;
  28:  
  29:             alert(tbX + tbY);
  30:  
  31:             Sys.UI.DomElement.setLocation(div1, parseInt(tbX), parseInt(tbY));
  32:         }
  33:  
  34:         // Unload Page
  35:         function pageUnload() {
  36:             var btnGet = $get("btnGetPos");
  37:             var btnSet = $get("btnSetPos");
  38:  
  39:             $removeHandler(btnGet, "click", getXYLocation);
  40:             $removeHandler(btnSet, "click", setXYLocation);
  41:         }
  42:     </script>

[HTML-Script]


   1: <form id="form1" runat="server">
   2:     <asp:ScriptManager ID="ScriptManager1" runat="server">
   3:     </asp:ScriptManager>
   4:     <div id="div1" style="border: ridge 1px Black; width: 250px; text-align: justify;">
   5:     This is a sample text inside an HTML for demonstrating CSS Positioning using ASP.NET Ajax Library.
   6:     </div>
   7:     <br />
   8:     <div>
   9:     X-Coord: <input id="tbXpos" type="text" /><br />
  10:     Y-Coord: <input id="tbYpos" type="text" /><br />
  11:         <input id="btnGetPos" type="button" value="Get (X,Y) Location" />&nbsp;&nbsp;&nbsp;
  12:         <input id="btnSetPos" type="button" value="Set (X,Y) Location" />
  13:     </div>
  14:     </form>

Thanks.

No comments:

 
Best viewed in Internet Explorer 8.