views:

245

answers:

2

This maybe a very basic question but for the life of me I cannot figure it out. So I have a user control that gets loaded on a page. Well, in this user control, I'm wanting to include a js file for some functions that are only specific to that user control. Inside this js file let's say I have a function called 'MyFunction'. In the onclick event of a div I'm wanting to call that function and I am unable to. Any help would be greatly appreciated.

I'm using the ClientScriptManager of the page object and I'm supposedly successfully including the file on the page using the following call:

page.ClientScript.RegisterClientScriptInclude(scriptTitle,
    page.ResolveUrl(scriptUrl))

Now, after this, I'm wondering, is there anything special I need to do to be able to call a function that's in the include file? like in my div:

<div class="someClass" onclick="MyFunction();">Click Me</div>
A: 

i use the scriptmanager/scriptmanagerproxy

<asp:ScriptManager runat="server">
  <Scripts>
     <asp:ScriptReference Path="~/js/myscript.js" />
  </Scripts>
</asp:ScriptManager>
Al W
Ok, I need to be a little more clear. So I'm using the ClientScriptManager of the page object and I'm supposedly successfully including the file on the page using the following call:page.ClientScript.RegisterClientScriptInclude(scriptTitle, page.ResolveUrl(scriptUrl))Now, after this, I'm wondering, is there anything special I need to do to be able to call a function that's in the include file? like in my div:<div class="someClass" onclick="MyFunction();">Click Me</div>
Keith
As long as everything you mentioned above is not happening in an async postback ala updatepanels then it should work. If you are using update panels then the ScriptManager has some static methods that you can use instead of the Page.ClientScript.
Al W
Yeah not using ScriptManager. But, I did notice that since I'm registering the js include using the clientscriptmanager in the page_load and the script is not included in the head of the page, it's a little further down. This shouldn't make a difference because I'm also doing jQuery the same way and it works fine. So, I'm totally stuck as far as figuring this out.
Keith
A: 

So at the top of your page (in the head tag of your HTML), output the script tag that references your javascript file with your functions. Al W's method above is neat. You can then after the DOM is loaded assign the functions to the controls. For example with jQuery you use:

<script type="text/javascript">
    $(document).ready(function(){
        $('#elementID').click(function(){
            // do stuff in here
        });
    });
</script>
Ambrosia
<script src="/Scripts/Includes.js" type="text/javascript"></script>
Keith