Skip to main content

Where to Declare Your jQuery Functions

By Sam Deering



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95


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:


  • “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?”


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:



jQuery functions need to be in scope:

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

function update() { 
    setTimeout(update, 1000);


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

function update() { 
  setTimeout('update()', 1000);

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

Related Articles

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn the basics of programming with the web's most popular language - JavaScript

A practical guide to leading radical innovation and growth.

Integromat Tower Ad