indofraiser
indofraiser

Reputation: 1024

Trigger OnLoad Javascript in .Net on content page

Issue: Load Javascript on load on a 'content page'.

I have some test Javascript code that I launch with

<body onload="javascript:SomeFunction()"> 

(Code specific is <body onload="GetMap(); ClickGeocode()">)

However I now want to put the code into a .Net page which has a masterpage. What I do not want to do is to have the Javascript loading on the masterpage as that would mean it loads on every page when I want it only on one page.

I have tried on here and Google to find a solution but am not sure on the terminology! I have looked at How do I call a JavaScript function on page load? as an example of research.

Code in full:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.3"></script>

<script type="text/javascript">

    var map = null;

    function GetMap() {
        map = new VEMap('myMap');
        map.LoadMap();

    }

    function ClickGeocode() {

        map.Geocode(document.getElementById('<%= txtQuery.ClientID %>').value, findCallback);
    }

    function findCallback(layer, findResults, placeResults, moreResults, error) {
        var s = '';
        if (placeResults) {
            for (var i = 0; i < placeResults.length; ++i) {
                s += 'Name: ' + placeResults[i].Name + '\n';
                s += 'LatLong: ' + placeResults[i].LatLong + '\n';
                s += 'MatchCode: ' + placeResults[i].MatchCode + '\n';
                s += 'MatchConfidence: ' + placeResults[i].MatchConfidence + '\n';
                s += '\n\n';
            }
        }
        else {
            // Code was an error! 
            // Do something else!
         //   console.log(error);
        }

    }
 </script>
   </head>
   <body onload="GetMap(); ClickGeocode()">

      <div id='myMap' style="position:relative; width:400px; height:400px;"></div>      

     <form runat="server"> 
       <asp:TextBox ID="txtQuery" runat="server" text="Postcode Here" />

       </form>
   </body>
</html>

Upvotes: 0

Views: 571

Answers (1)

Daniel B
Daniel B

Reputation: 457

Use proper events or call your code where required elements are already available.

Add the following to the bottom of the document (inside <body> of course):

<script type="text/javascript">
  myFunction();
</script>

Using events, possible in both <head> and <body>:

<script type="text/javascript">
  document.addEventListener("DOMContentLoaded", myFunction, false);
</script>

Upvotes: 2

Related Questions