Five ‘s Weblog

October 17, 2007

Two useful javascript methods!

Filed under: Five's thought — by powerdream5 @ 9:53 pm
Tags: ,

       Recently, I help one of my friends do some javasript stuff. I found two useful methods and want to share them with you.

       Firstly, please open this web link and see the effect of the example. Perhaps there are two highlight attracting you, the transparent background and the size of the frame changing dynamically. (If you think it does not interest you, I am sorry to waste your time). Now, I am going to explain how can I realize the two functions. It is pretty easy.

Using the method setInterval()
The setInterval method calls a function at specified intervals. It has two required parameters. The first parameter is a pointer to a function, and the second parameter is the number of milliseconds. It is easy to create some animation effect by using this method, for example, moving some elements and changing the size of some elements. There is an example about changing the size of a “div”.

//get the reference of the “div” of which you want to change the size
var div = document.getElementById(“divId”);
//set the initial width and height of the “div” to 0
div.style.width= 0 + “px”;
div.style.height = 0 + “px”;
var width = 0;
var height = 0;
//the changeSize() method will be called every 10 millionseconds
var interval = setInterval(“changeSize()”,10);
function changeSize(){
        width += 10;
        height + 10;

       div.style.width = width + “px”;
       div.style.height = heigjt + “px”;
       if(width >= 500)
      {
             //clearInterval() method will stop the call to the changeSize() method
             clearInterval(interval);
       }
}

Using the method createElement()
The createElement() method creates an element node. In the example you saw at the beginning of this article, I firstly created a “div” node, and setted the style of this node, then append it to the html body.

var tbody = document.getElementsByTagName(“body”)[0];
//create a “div” node, you can also create “table”, “tr”,etc.
var tnode = document.createElement(“div”);

//set the style
tnode.style.position = “absolute”;
tnode.style.top = “0px”;
tnode.style.left = “0px”;
tnode.style.overflow = “hidden”;
//set the id of the new “div”
tnode.id = “darkScreenDiv”;

//to make it transparent  
tnode.style.opacity = 0.7;
tnode.style.MozOpacity = 0.7;
tnode.style.filter = “alpha(opacity=”+70+”)”;
//set the depth, to make sure it is over the other elements of this web page.
//the biggerthe value is, the topper the element is
tnode.style.zIndex = 100;

//set the width and height of this “div” node
tnode.style.width = document.documentElement.clientWidth + “px”;
tnode.style.height = document.documentElement.clientHeight + “px”;
tnode.style.display = “block”;

//append it to the html body
tbody.appendChild(tnode);

10_17_1_2007.jpg

Create a free website or blog at WordPress.com.