1.11M Members

Calling Javascript from ImageButton


Hi guys,

how would I translate the functionality of this anchor:

<a style="font-size: small;" href="javascript:void(0)" onclick="document.getElementById('info').style.display='block';document.getElementById('fade').style.display='block';return false;">Blahblah</a>

To an asp.net imagebutton control?

This is what I have come up with:

<asp:ImageButton ID="ImgBtn" runat="server" ImageUrl="~Images/Go.gif" 
                OnClientClick="<script type='text/javascript'>document.getElementById('info').style.display='block';document.getElementById('fade').style.display='block';return false;</script>" />

But its not coming out the same way. Can anyone help me out?


But its not coming out the same way.

What is different?


Looks like the asp.net engine doesnt care for the JavaScript syntax written in that manner. If you look at the HTML produced for the ImageButton it is rendered as such:

<input type="image" name="ImgBtn" id="ImgBtn" src="Images/Go.gif" onclick="&lt;script type=&#39;text/javascript&#39;>document.getElementById(&#39;info&#39;).style.display=&#39;block&#39;;document.getElementById(&#39;fade&#39;).style.display=&#39;block&#39;;return false;&lt;/script>;" />

Why dont you add a JavaScript block and just call the function?

    <a style="font-size: small;" href="javascript:void(0)" onclick="myscript()">Blahblah</a>
    <asp:ImageButton ID="ImgBtn" runat="server" ImageUrl="~Images/Go.gif" OnClientClick="myscript()" />
        function myscript() {
            document.getElementById('info').style.display = 'block';
            document.getElementById('fade').style.display = 'block';
            return false;

Hi Jorge,

I tried it as suggested and it works, but to a certain extent. When I click the ImageButton the blocks only appear for a split second. How should I fix this issue? When the blocks are displayed, there is a button where the user can close the window, so the blocks should not disappear on their own. Is this because I am calling it from an 'OnClientClick' property?

Thanks again


Nevermind, I actually got it working as desired. I just used the <input> tag and used the image property to make it appear as an image button. I also called my javascript function with the 'onclick' event. The syntax was as follows:

onclick='return myscript();

thanks again guys for your help. It is very much appreciated.

Question Answered as of 1 Year Ago by pritaeas and JorgeM

ok not a problem. with regard to

When I click the ImageButton the blocks only appear for a split second..

I suspect that the issue you had is that the image button, since rendered as a input button will post back when clicked. You would have to modify that behavior.

Just wanted to provide this info for the benefit of anyone else that may come accross this thread.

This question has already been solved: Start a new discussion instead
Start New Discussion
Tags Related to this Article