Results 1 to 2 of 2

Thread: how to freeze a variable value in a function?

  1. #1
    Join Date
    Jul 2009
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Angry how to freeze a variable value in a function?

    Hello guys,
    so i have this script that will resize an html element, i use DOM to get the original element size but when i run the function for the second time to restore the element original size; the variables that had the original element size are been overwritten by the new element size. So where and how can i store the original size of the element to avoid overlapping of this value.

    Here is the code portion of how i get this value:

    Code:
    Code:
    function animate(mode,id){
    	
    		 var obj=document.getElementById(id);
    	var wv= parseInt(obj.style.width);
    	var wv= parseInt(obj.style.height);
    .......
    the rest of the animate function is not relevant.

    Here is an html example:
    Code:
    Code:
    <a href="" onclick="animate('both','ex2')">Toggle</a>
     
     
      <div id="ex2" style="height:300px; width:500px;"></div>
    when the link is first clicked it will get the div element size which is 500x300 and shrink it to 0x0. The problem comes when the link is clicked again (is suppose to restore the element to its original size), the size values gathered in the first click will be overlapped with 0x0 but i want the first value 500x300 to be there everytime the animate() function is called.

    In other words the variables hs and ws gather dynamic data and i want then to keep the first value they gathered no matter how many times the function is called nor to what size the element morph to. Hope is possible thank you... Any comments will be appreciated.

  2. #2
    Join Date
    Jul 2006
    Posts
    497
    Thanks
    8
    Thanked 70 Times in 70 Posts

    Default

    A closure is what you need... Note that this solution requires that you write unobtrusive JavaScript; I can't think of a way to avoid this, but it's a good thing to practice anyway.
    Code:
    link.onclick = makeAnimater('both', 'ex2');
    function makeAnimater(mode, id){
    	var obj=document.getElementById(id);
    	var wv= parseInt(obj.style.width);
    	var wv= parseInt(obj.style.height);
    	return function (){
    		/* We can access those variables from inside here;
    		 * just don't change them and they'll say the same
    		 * across calls to the returned function.
    		 */
    	};
    }
    -- Chris
    informal JavaScript student of Douglas Crockford
    I like wikis - a lot.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •