Aruna Aruna - 3 months ago 36
ASP.NET (C#) Question

setTimeout is not working in JavaScript

I m using Javascript function to expand/collapse the gridview rows. Following is the script.

<script type="text/javascript">
function divexpandcollapse(divname) {
var div = document.getElementById(divname);
var img = document.getElementById('img' + divname);
if (div.style.display == "none") {
div.style.display = "inline";
img.src = "Img1/minus.gif";
} else {
div.style.display = "none";
img.src = "Img1/plus.gif";
}
}
</script>


In my gridview I m calling the javascript like this, its working fine but its expanding immediately. I want to expand the panel slowly. Is that any incorrect coding with the setTimeout function. Can anyone please help me...

<asp:TemplateField ItemStyle-Width="20px">
<ItemTemplate>
<a href="JavaScript:setTimeout(divexpandcollapse('div<%# Eval("ClaimMasterId") %>'),1000);">
<img id='imgdiv<%# Eval("ClaimMasterId") %>' width="9px" border="0" src="Img1/plus.gif"
alt="" /></a>
</ItemTemplate>
<ItemStyle Width="20px" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>

Amy Amy
Answer

It's because it's calling the function, taking the return value, and passing that to setTimeout, when what you're trying to do is call the method with setTimeout and pass in the arguments then. So use this overload instead:

window.setTimeout(func, [delay, param1, param2, ...]);

In your case, this would be:

setTimeout(divexpandcollapse ,1000, 'div<%# Eval("ClaimMasterId") %>')

See the difference? setTimeout will call your method and pass in the parameters when it does so.

If you don't want to use that overload of setTimeout, you can enclose your method call inside another function:

setTimeout(function() { divexpandcollapse('div<%# Eval("ClaimMasterId") %>') }, 1000);

However, I find the first one far easier to read (and shorter to type).

Comments