Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which jQuery event handler works for page load?

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.

like image 501
Travis J Avatar asked Apr 26 '12 07:04

Travis J


People also ask

What is the page load event in jQuery?

The load event occurs when a specified element has been loaded. This event works with elements associated with a URL (image, script, frame, iframe), and the window object. Depending on the browser, the load event may not trigger if the image is cached (Firefox and IE).

How can call Click event on page load in jQuery?

$("document"). ready(function() { setTimeout(function() { $("ul. galleria li:first-child img"). trigger('click'); },10); });

How can we call a method on page load using jQuery?

$( document ). ready() ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ). on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready. // A $( document ).

What is a load event handler?

The load event occurs when the document has been completely loaded, including dependent resources like JavaScript files, CSS files, and images. The <img> and <script> elements also support the load event. Use the addEventListener() method to register an onload event handler.


2 Answers

You forgot to write your code into function.

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

Or just simply

    $(function() {
        showWidth();
    });
like image 116
Chuck Norris Avatar answered Sep 28 '22 04:09

Chuck Norris


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.

like image 21
sjmdev Avatar answered Sep 28 '22 02:09

sjmdev