Search code examples
asp.nethtmlservercontrol

Javascript won't work on Html server control?


I am writing a website with ASP.Net.

I will have lots of html generic controls like <div> <span> and so on..

I have some onclick javascript functions, onmouseover javascript functions..

They are working fine..

Then I need to control them on the server side.

So, I add runat="server"..

After that, all the javascripts aren't working anymore..

I understand they aren't working coz all the events are now going back to server side.

So, is there anyway to make them work??

For eg,

<div id="myDiv1" onclick="myfunction(para1)"><img src="..." /></div>

the above code is working..

<div id="myDiv1" runat="server" onclick="myfunction(para1)"><img src="..." /></div>

the above code is not working...

I can make it work, probably by

<div id="externalDiv1" onclick="myfunction(para1)"><div id="myDiv1" runat="server" ><img src="..." /></div></div>

Is there any other way?


Solution

  • Server-side or client-side controls makes no difference as far as javascript is concerned. ALL server-side controls end up being rendered as normal HTML controls. If your javascript functions are not working might be because you are accessing them by the wrong id since by making them server-side controls they can now have ids that follow a pattern like <parent_id>_<control_id>.

    For example, a span element declared like this:

    <span id="mylabel" runat="server"> testing</span>
    

    may end up being rendered as:

    <span id="MainContent_mylabel"> testing</span>
    

    ASP.NET 4.0 has a feature called CliendIDMode which can be set to static, meaning, that your ids on the markup will stay unchanged after the page is rendered.