Java Reference
In-Depth Information
background-color: silver;
width: 150px;
height: 150px;
}
Aside from the position, you also specify the box to have a background color of silver, and set the height
and width to be 150 pixels each, to make it a square. At this size, however, the text boxes in the form
actually extend past the box's borders. In order to fi x this, set a rule for the <input/> element as well.
input
{
width: 100px;
}
By setting the <input/> elements to be 100 pixels wide, you can fi t everything nicely into the box. So at
this point, the HTML is primarily fi nished and it's styled. All that remains is to write the JavaScript to
retrieve the values from the form fi elds and move the box to the coordinates provided by the form.
The function responsible for this is called moveBox() , and it is the only function on this page.
function moveBox() {
var divBox = document.getElementById(“divBox”); //Get the box
var inputLeft = document.getElementById(“inputLeft”); //Get one form field
var inputTop = document.getElementById(“inputTop”); //Get the other one
The function starts by retrieving the HTML elements needed to move the box. First it gets the <div/>
element itself, followed by the text boxes for the left and top positions, and stores them in the
inputLeft and inputTop variables, respectively. With the needed elements selected, you can now
move the box.
divBox.style.left = parseInt(inputLeft.value) + “px”;
divBox.style.top = parseInt(inputTop.value) + “px”;
}
These two new lines to moveBox() do just that. In the fi rst line, you use the value property to retrieve
the value of the text box for the left position. You pass that value to the parseInt() function because
you want to make sure that value is an integer. Then append px to the number, making sure that all
browsers will position the box correctly. Now do the same thing for positioning the top: get the value
from the inputTop text box, pass it to parseInt() , and append px to it.
As you can see, moving an element around the page is quite simple and is a building block toward
another effect: animation.
Example: Animated Advertisement
Changing the appearance and position of an element are important patterns in DHTML, and they fi nd
their places in many DHTML scripts. Perhaps the most creative use of DHTML is in animating con-
tent on the page. You can perform a variety of animations with DHTML. You can fade text elements or
images in and out, give them a swipe animation (making it look like as if they are wiped onto the page),
and animate them to move around on the page.
Search WWH ::




Custom Search