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 – and 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');
        window.onload = giveFocus;

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.

  1. Programming

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: