JD Isaacks
JD Isaacks

Reputation: 57974

JS: body tag onload equivalent?

I need to basically add this to my page:

<body onload="document.getElementById('WeddingBandBuilder').focus()">

However due to my template I cannot change the tag. So is there a way to do the equivalent with a script in the < head > tag or something?

Thanks!

Upvotes: 3

Views: 4195

Answers (4)

JerSchneid
JerSchneid

Reputation: 5917

I might check if that page has already included jQuery? If so, you can do something like this:

$(document).ready(function() {
    $('#WeddingBandBuilder').focus();
});

Upvotes: -2

Grant Wagner
Grant Wagner

Reputation: 25931

You should always be careful there isn't already a window.onload defined. I've been burned a number of times by assuming I would be the only one attaching things to <body onload="..."> or window.onload.

See this answer and comments for a solution to this issue.

Upvotes: 0

SpliFF
SpliFF

Reputation: 38966

<script>
window.onload = function() {document.getElementById('WeddingBandBuilder').focus()};
</script>

Upvotes: 8

pilsetnieks
pilsetnieks

Reputation: 10420

Use a JS library like jQuery or Prototype and create an external script file with something like this:

for jQuery:

$(function() { $('#WeddingBandBuilder').focus(); });

for Prototype:

Event.observe(window, 'load', function() { $('WeddingBandBuilder').focus(); });

Upvotes: -1

Related Questions