0

I have a asp.net button

I want to run a JavaScript function animation() along with the asp.net function Button1_Click when the user clicks on submit.

i have written the following code for the same but unable to get the desired result

protected void Button1_Click(object sender, EventArgs e)
    {
        Button1.Attributes.Add("onClick", "animation()");
    <Some Code Here>
     }
Sanchit Pruthi
  • 79
  • 1
  • 1
  • 8

3 Answers3

1

You must include your code outside of the click definition. you can include it on page_load event as..

 protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
             Button1.Attributes.Add("onclick", "animation()");

        }
    }
angfreak
  • 993
  • 2
  • 11
  • 27
0

You may also use a script manager to run your javascript functions from server side:
1) You must add a script manager to your page
eg: <asp:ScriptManager ID="scriptManager" runat="server" EnablePartialRendering="true" EnablePageMethods="true" AsyncPostBackTimeout="600" />

2) on your _Click function protected void Button1_Click(object sender, EventArgs e) { string script = "$(function(){animation();});"; ScriptManager.RegisterStartupScript(this, this.Page.GetType(), Guid.NewGuid().ToString(), script, true); }

there are two methods you may use with ScriptManager:
- RegisterStartupScript
- RegisterClientScriptBlock
here is a post that tells the difference between them

Community
  • 1
  • 1
Ricardo Appleton
  • 679
  • 10
  • 22
0

You can add the javascript function on OnClientClick attribute of the Button.

like

<asp:Button id="Button1" runat="server" OnClientClick="animation();" OnClick="Button1_Click" />

Bharadwaj
  • 2,535
  • 1
  • 22
  • 35