views:

1008

answers:

3

What is the best way to change the height and width of an ASP.NET control from a client-side Javascript function?

Thanks, Jeff

+1  A: 

You can use the controls .ClientID and some javascript and change it that way.

You can do it through CSS height/width or on some controls directly on the control itself.

CubanX
A: 

Because of the name mangling introduced by ASP.NET, I use the function at the bottom to find ASP controls. Once you have the control, you can set the height/width as needed.

example usage:

<input type='button' value='Expand' onclick='setSize("myDiv", 500, 500);' />

...

function setSize(ctlName, height, width ) {
    var ctl = asp$( ctlName, 'div' );
    if (ctl) {
       ctl.style.height = height + 'px';
       ctl.style.width = width + 'px';
    }
}


function asp$( id, tagName ) {
    var idRegexp = new RegExp( id + '$', 'i' );
    var tags = new Array();
    if (tagName) {
        tags = document.getElementsByTagName( tagName );
    }
    else {
        tags = document.getElementsByName( id );
    }
    var control = null;
    for (var i = 0; i < tags.length; ++i) {
       var ctl = tags[i];
       if (idRegexp.test(ctl.id)) {
          control = ctl;
          break;
       }
    }

    if (control) {
        return $(control.id);
    }
    else {
        return null;
    }
}
tvanfosson
+1  A: 

Hello,

Yes, it's possible. ASP Controls are rendered as HTML controls on the browser with some added attributes. If you gave your ASP.Net control an ID while you created it, it will show up as the ID of the HTML control too.

You should be able to access the controls using javascript's getElementById() function, and you should be able to modify the CSS attributes (style as specified in the message above this one).

If you use JQuery, selection and setting CSS styles can be easier, example

$("#myControl").css("width")== myNewValue;

Cheers

Cyril Gupta
Caveat: The ID of the ASP.NET control will only get to the client unmangled if the control is directly on an ASPX page that doesn't use a master page, otherwise it is altered by the time it gets to the client.
Jason Bunting
Example: If a button's ID is "Foobar" and it is within a user control with an ID of "UC" which is on a page using a master page which has a content place holder with an ID of "CPH", it can end up as something like "ctl00_CPH_UC_Foobar" on the client; just be aware of this.
Jason Bunting
Good point Jason.
Cyril Gupta
you can do this in that case $("#<% myControl.ClientID %>").css("width")== myNewValue;
Cyril Gupta