Gotcha of inline Document Ready function for JQuery

Posted by Brett Veenstra

I’ve had some reasons to use JQuery this week, and you should believe whatever good rumors and hype you’ve heard about this library. It’s amazing.

There are many benefits to a Javascript framework, particularly JQuery. Take this example that I put inside my <head> element:

<script type="text/javascript">
    $(document).ready(function(){

        $('#deliciouslogin').submit(function(){
            alert("This to authenticate with Delicious and start retrieving Bookmarks into Google Gears  database");
        })

    });
</script>

This is the “Document Ready” function. This solves the problem of running your Javascript code before your page is done rendering on the browser. Also note how easy it is to hookup an “onsubmit” event handler. You use CSS-selectors to identify what HTML element(s) to apply to, and JQuery does the rest, figuring out the best way to accomplish that regardless of your browser. Great fun.

My elation quickly disappeared when I fired this sample up in FireFox 3, nothing happened when my <form>’s submit button was triggered. Frustrated, I quickly tried it in Safari (Mac), it worked fine. I switched to the PC and grumpy IE6, and again, no luck. So what’s going on?

It turns out that the inline JavaScript will be ignored if you close the element just prior in your <head> section with the shorthand closetag “/>”.

This doesn’t work:

<script type="text/javascript" src="lib/jquery/jquery.js" />
<script type="text/javascript">
    $(document).ready(function(){
        // blah
        })
    });
</script>    

This does work:

<script type="text/javascript" src="lib/jquery/jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        // blah
        })
    });
</script>    

Hopefully I will remember this in the future, as this is now the second time in two days I’ve wasted an hour or more wondering why my Javascript wasn’t activated.


PhotoWalking - Metro Detroit - September 21

Posted by Brett Veenstra

Mark your calendars for Sunday, September 21 from 4:00 - 8:00pm. We’ll be meeting in Ann Arbor at “The QuadDiag”. The QuadDiag is the large walk area just in front of the main library. Grab parking where you can find it and meet up with us. We’ll start walking at 4:15, and we should have a sunset around 7:00pm.

I’ve posted a central page with full details here.

UPDATE: Ashamed as a U of M Alumn that I mixed up my Quad and Diag terms. We’re meeting in the Diag (don’t step on the M!).