0

I have the code that I have posted below in my webpage. As you can see it uses the body onload function to launch the script. Is there any way of making this script work without this and in JavaScript instead?

<!doctype html>
<html>
<head>

<script type="text/javascript">
function box(query){
return document.getElementById(query)
}
</script>

</head>
<body onload="box('query').focus();">

<input id="query" type="text">

</body>
</html>

Thanks in advance, Callum

Josh Darnell
  • 11,304
  • 9
  • 38
  • 66
Callum Whyte
  • 2,379
  • 11
  • 36
  • 55
  • what are you trying to achieve actually – Anupam May 01 '11 at 21:09
  • 1
    You're already using JavaScript. And how would you do something onload if not on the onload event? Your question makes no sense in it's current form. – no.good.at.coding May 01 '11 at 21:14
  • i just cant understand y do u want to do that but if u dislike the onload function you can use document.ready function of jquery but again,it makes no sense to avoid onload in the first place – Anupam May 01 '11 at 21:20
  • Since the onLoad function is provided by JavaScript, you have already solved your problem. – Zian Choy May 01 '11 at 21:08

4 Answers4

1

This might what you're looking for: Attach a body onload event with JS

I'd suggest using jQuery or some other JavaScript framework unless you're exploring JS or have some stringent restrictions on using libraries and frameworks.

Community
  • 1
  • 1
no.good.at.coding
  • 20,221
  • 2
  • 60
  • 51
0
the following code helpful for you
this is jquery:

$(document).ready(function(){
              function name();
});

or

$(window).load(function(){
function name();
});
0
the following answers using javascript:
<html>
<head>
    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript">
    function load() {
        alert('function loaded');
    }
    window.onload = load;
    </script>
</head>
<body>
</body>
</html


----------

<html>
<head>
    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript">
    function load() {
        alert('function loaded');
    }
     </script>
</head>
<body onload="load();">

</body>
</html
-1

if you are talking about catching the onload event with writting any javascript in your html you can use this function:

// Add event
var addEvent = function (obj, evType, fn){
        if (obj.addEventListener){
                obj.addEventListener(evType, fn, false);
                return true;
        }else if (obj.attachEvent){
                var r = obj.attachEvent("on"+evType, fn);
                return r;
        } else {
                return false;
        }
};

Now you can run all the functions you need in your onload event.

addEvent(window,'load',function () {
   box('query').focus();
   // or
   document.getElementById('query').focus();
});
Ibu
  • 42,752
  • 13
  • 76
  • 103