Using a JavaScript onLoad event with an ASP.NET Master Page

My site uses a Master Page, and I wanted to run a JavaScript function when my page loaded from one of my content pages. But, as you may have noticed, there is no body tag, so there is no place to put the onLoad property.

After some research, I found two links that looked promising – http://geekswithblogs.net/AzamSharp/archive/2006/04/25/76390.aspx and http://forums.asp.net/p/1310519/2584110.aspx. Both seemed like they would do the job.

But, neither one would actually fire my JS function when the page loaded. Both solutions would work if I hit F5 to refresh the browser, but that was not what I wanted. What to do?

Instead, I found this very simple solution. In the content page, I added this code in the header area,

    <script type="text/javascript">
        function giveFocus() {
            var firstField = document.getElementById('ContentPlaceHolder1_txtUserName');
            firstField.focus();
        }
        window.onload = giveFocus;
    </script>

That was it. I’m not sure why the other two solutions didn’t work, so if anyone has insight, I would like to know.

Advertisements
  1. Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: