If you like programing pure in client side to render every thing your self for more control , you should integrate your client side scripts with server side technology.
Some times what your server side code outputs restrict your client side scripting , user controls is one of this examples .
The problem is finding objects in each user control . if you use server controls like asp:textbox , asp.net change object id to keep it unique in host page (maybe use multiple instances of a user control in one page or host page have another object has same id ) . The problem is finding objects in client side .
Common solution is Injecting htmlControl.clientID from server side code into rendered html for accessing in client side . because clientID attribute gives you unique id that asp.net generated in host page . but its not a good idea and nobody like use that because it restricts your scripting.
Another solution is using css class instead of id.
but here is a problem ... css classes is unique in user control area but not unique in host page with multiple user control instances . I have a trick for you ...
First you should make user control boundary identifiable .
I use a div with class named controlContainer for my user control boundary.
Know but all of your objects inside this container . ok lets talk about finding each object of user control inside of user control boundary and do jobs with a unique object in a host page with multiple user control instances . for finding an object uniquely I should find user control boundary and search for object with specified css class inside this boundary .
using .parents('.controlContainer') to find user control boundary from inside , and using .find('.Text1') for reference to object with css class value of '.Text' .
lets have an example :
In this Example we develop an ASP.NET user control with a div and a button , when user click the button , div toggle hide and show .
First Create user control html ...
Lets see the Code behind ...
javascripts cannot write inside a user control and you should use Page.ClientScript.RegisterStartupScript to register client scripts on user control html output . ok make a draft of necessary script for showHide method . this method calls button click .
function showHide(obj){
var x=$(obj).parents('.controlContainer');
$(x).find('.Text1').toggle('slow');
}
Concat this script lines using stringBuilder class in .net and register it as I explained in page load event handler.
VB :
CS :
For Run and test , add more than one instance of this user control to an ASP.NET page and run .
the result show you despite having several objects on page with css class Text1 , a button on each user control hide and show just div inside same user control . yes , and now you can easy write your client side script on user controls without worry about unique id's that generates by ASP.NET .
Happy scripting ...