Where to Declare Your jQuery Functions

Sam Deering
Tweet

qanda

We get asked this question alot so I thought we would clarify it for all those jQuery beginners out there. The questions I will provide answers for:

Questions

  • “This may sound like a really dumb question but where do I declare my jQuery functions?”
  • “Does jQuery code work outside the document ready function?”
  • “Why is my jQuery function is not working?”
  • “Do I put the change/click event in jQuery or HTML element?”

Answers

A simple solution for anyone learning jQuery is to always declare your jQuery code inside the document ready function. This is to ensure that all of the html page elements also known as the DOM (Document Object Model) have loaded before any jQuery code is run.

As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events as soon as the DOM is ready.

$(document).ready(function() {
  // do stuff when DOM is ready
});

See the Different Types of Document Ready for help with this. These can help avoid conflicts with other jQuery frameworks.

Inside html events

I recommend using jQuery to manage the events on DOM. For one it keeps the html clean and second you can disable the events as easily as attaching them.

Another Advantage: Using jQuery to attach events (rather than in the HTML markup) you will never see all those “javascript:void()” messages in the status bar when you hover over a link.

For example creating a click event in jQuery:

  $(document).ready(function() {
     $("a").click(function() {
         alert("Hello world!");
     });
 });

This is the same as putting it in the html code:

 <a href="" onclick="alert('Hello world')">Link</a>

Scope

jQuery functions need to be in scope:

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

function update() { 
    $("#board").append(".");
    setTimeout(update, 1000);
}

or

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

function update() { 
  $("#board").append(".");
  setTimeout('update()', 1000);
}

The second works because the update() within the code block is within scope now.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments