Reputation: 82297
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
.
Upvotes: 5
Views: 7247
Reputation: 3942
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"); });
Upvotes: 1
Reputation: 159
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.
Upvotes: 1
Reputation: 15200
You forgot to write your code into function.
$(document).ready(function() {
showWidth();
});
Or just simply
$(function() {
showWidth();
});
Upvotes: 6