View Full Version : how to freeze a variable value in a function?

07-11-2009, 11:38 PM
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:


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:

<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.

07-12-2009, 06:03 AM
A closure (http://www.javascriptkit.com/javatutors/closures.shtml) is what you need... Note that this solution requires that you write unobtrusive JavaScript (http://javascript.wikia.com/wiki/Unobtrusive_JavaScript); I can't think of a way to avoid this, but it's a good thing to practice anyway.
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.