Which jQuery event handler works for page load?
Asked Answered
M

3

5

I have a simple page, just trying to attach a load event to the document. I am not sure which event handler to use in jQuery to do this with. I tried $() and $(document).ready and .load but neither seem to run the code at the right time. Should I be using .on, .live? Or is there something I am doing wrong. Here is a sample:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
    $(document).ready(
        showWidth()
    );
    function showWidth() {
        alert($('#textTitle').width());
    }
</script>
</head>
<body>
<div class="page">
        <div id="title">
            <h1 id="textTitle">yo</h1>
        </div>
</div>
</body>
</html>

When I run this the alert displays null.

Medarda answered 26/4, 2012 at 7:8 Comment(0)
S
6

You forgot to write your code into function.

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

Or just simply

    $(function() {
        showWidth();
    });
Splutter answered 26/4, 2012 at 7:9 Comment(2)
Interesting. I thought that since it was just a one liner I wouldn't need the closure in there.Medarda
it's not a closure it's a call back. What you type was goind to run the function and try to assign the return as an argument. Which would return undefined and this is why your alert was popping before the DOM was ready. If you leave the () out then you assign the function reference and don't execute it.Sabinasabine
F
1

Try this http://jsfiddle.net/vdCwE/

Also, are you sure you are including jQuery in your page? I didn't see it in your code.

Fragonard answered 26/4, 2012 at 7:14 Comment(0)
Q
1

There are two states of loading. One is "DOM ready" which can be asked by just using

// the long way
$(document).ready(function() { console.log("dom ready"); });
// the short way
$(function() { console.log("dom ready"); });

Or you want to wait for the "load" of the actual page (images, iFrames and so on) then you could use

$(window).load(function() { console.log("everything should be loaded"); });
Quinton answered 26/4, 2012 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.