Carlos
Carlos

Reputation: 377

Call JavaScript function from codebehind(c#) is not working

I am trying to call a Javascript from the codebehind but form some reason it is not working. Let me explain what i am trying to accomplish: when the page loads the system needs to check if this is the first time the user visit this page. if so a lightbox will open. So I created a javascript function in the page the onPageLoad i would like to call this function if it is necesary. This is what I have so far, looks pretty straight forward but it is not working. I will appreciate any help.

Here is the

html:

  <form id="form1" runat="server">
  <div>

  <a id="OpenTutorial"  href="../lightwindow/step1.html" params="lightwindow_width=450,lightwindow_height=470" class="lightwindow page-options">Open Tutorial</a>


  </div>


  <script>
    function OpenTutorial() { $("#OpenTutorial").click() }
   </script>

  </form>

Code behind:

    protected void Page_Load(object sender, EventArgs e)
    {

  //code to check if this is the first time
  ..... 
  // it this is the first time, call this function 
   Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "OpenTutorial()", true);

    }

Upvotes: 0

Views: 2194

Answers (3)

Aswin Ramakrishnan
Aswin Ramakrishnan

Reputation: 3213

How about refactoring your javascript function as follows?

<form id="form1" runat="server">
<div>

<a id="OpenTutorial"  href="../lightwindow/step1.html" params="lightwindow_width=450,lightwindow_height=470" class="lightwindow page-options">Open Tutorial</a>

</div>


<script>
  // Function that Opens the Tutorial
  function OpenTutorial() { 
      // Using colorbox for an example, but you can start the lightbox through the function
      $('#OpenTutorial').colorbox(); 
  }

  $("#OpenTutorial").click(function(){ OpenTutorial() });
 </script>

</form>

Code Behind:

protected void Page_Load(object sender, EventArgs e)
{
   //code to check if this is the first time
   ..... 
   // it this is the first time, call this function 
   Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "OpenTutorial()", true);
}

EDIT: Updating the OpenTutorial function to start a lightbox as opposed to opening the link

Upvotes: 1

epascarello
epascarello

Reputation: 207557

Change the id or the name of the function so they are different, they are clashing in the global namespace.

<a id="anc_OpenTutorial" />

<script>
    function OpenTutorial() { $("#anc_OpenTutorial").click() }
</script>

OR just call clicking the link with the code instead of calling the function.

TO follow the link change it to access the DOM element

$("#anc_OpenTutorial")[0].click() 

or

$("#anc_OpenTutorial").get(0).click() 

Upvotes: 1

mark879
mark879

Reputation: 87

Maybe try using jQuery's trigger function, ie:

function OpenTutorial() { $("#OpenTutorial").trigger('click'); }

Upvotes: 1

Related Questions