Javascript Animation Problem

Ok, this is very simple. I am trying to use Javascript to change the CSS property fontSize to increase over a small amount of time. Here’s the code:


function iscalled(id)
{
	changesize(15,25,id)
}
function changesize(start,finish,obj)
{
	if(start<finish)
	{
		start++;
		setTimeout("setattr("+start+","+finish+","+obj+")",1000);
	}
}

function setattr(num,finish,obj)
{
	document.getElementById(obj).style.fontSize=num+"px";
	changesize(num,finish,obj);
}

I want to have the font size dynamically change, in the (id) object. I experimented with several versions of setTimeout, because it wasn’t delaying at all. This script will run through setattr() only twice and doesn’t modify the font size. What am I doing wrong?

I made a revision, iscalled(‘someid’) is being called by a button, but I found out it was being passed as an HTMLHeadingElement. This script runs through twice (I traced it with alert()s) but doesn’t call changesize() again.


//Javascript
function iscalled(id)
{
	changesize(15,25,id)
}
function changesize(start,finish,obj)
{
	//alert("start="+start+";finish="+finish+";obj="+obj);
	if(start<=finish)
	{
		start++;
		setTimeout("setattr("+start+","+finish+","+obj+")",1000);
	}
}

function setattr(num,finish,obj)
{
	//alert("num="+num+";finish="+finish+";obj="+obj);
	obj.style.fontSize=num+"px";
	changesize(num,finish,obj);
}
//HTML
<h1 id="someid">ThisHeading</h1>
<input type="button" onclick="iscalled('someid')" value="+" />

The id variable in your code is a string, but you treat it as if it were a dom element object
obj.style.fontSize=num+“px”;

You could use


document.getElementById(id).style.fontSize=num+"px";

You would also need some single quotes here


setTimeout("setattr("+start+","+finish+",'" + obj + "')",1000);

Another way, mainly so you don’t need to muck around trying to create a string that resembles calling a function with arguments. Notice I’m able to pass the actual dom element as an argument now, which wasn’t previously possible when passing a string to setTimeout().


function iscalled(id)
{
    changesize(15, 25, document.getElementById(id));
}
function changesize(start, finish, obj)
{
    if (start <= finish)
    {
        setFontSize(obj, start);
        start++;
        var func = function() {
            changesize(start, finish, obj);
        }
        setTimeout(func, 1000);
    }
}

function setFontSize(obj, num)
{
    obj.style.fontSize = num + "px";
}

If you want to learn more about what I did, you can search for stuff like
anonymous function
lambda
closure

Thanks a lot!