views:

74

answers:

3

I have a control that on 1 page is initially shown, but on another page is initially hidden.

For the page that initially shows the control, the javascript in the control works fine, but for the page that initially hides the control, the javascript doesn't work.

I've ended up registering the javascript in the code behind using:

this.Page.ClientScript.RegisterClientScriptBlock(...);

It works fine, but it gets ugly with large javascript blocks. Plus it I want to change it, I have to rebuild the solution, which I'd rather not have to do.

Is there another way to register javascript using markup if it isn't sent to the browser when the page is loaded? I'm trying to keep network traffic slim by only sending what I need to the browser when the page loads.

thanks,

Mark

+1  A: 

I assume you're getting the control by using document.getElementById, if that is the case, you can check if it is null before using it:

var ctrl = document.getElementById("someID");
if (ctrl) {
    do something here...
}
Jimmie R. Houts
A: 

If your control is hidden by setting its server side property 'Visible' to false, then the browser can't attach the js to anything because ASP.NET doesn't render the control. You could try setting the CSS property 'display' to 'none'.

Rob Decker
+2  A: 

The issue is not making the button invisible, but having an invisible button that one can click on from javascript, and having the button call it's event handler.

ex:

   <asp:button id="button1" runat="server" style="display:none">

is something you should use or you can setting up a css class with display:none in it instead and then assign that to your control.

TStamper