0

When ever I add listeners to things like drop down options so e.g.

$("select").change(function () {

or when I want something done as soon as the page is loaded e.g.

$(".filter").each(function () {

(where "filter" is just the class name that certain elements have)

I tend to put in $(document).ready(function () {

is there a better way (in terms of design) to do things like this, I am just trying to get into better habits, or can anyone refer me to articles where topics like this one are discussed at in length. Just to better myself.

AstroCB
  • 12,337
  • 20
  • 57
  • 73
user2405469
  • 1,953
  • 2
  • 22
  • 43
  • What do you mean "I tend to put in"? Put in where? Show a complete code snippet. – Jon Apr 10 '14 at 12:15
  • possible duplicate of [Different ways of saying document ready in jQuery?](http://stackoverflow.com/questions/6969245/different-ways-of-saying-document-ready-in-jquery) – Ivanka Todorova Apr 10 '14 at 12:17
  • @Jon sorry if I wasn't clear, what I mean is I tend to put the first two examples in two the document ready function. so the first listener and the second "each" function, I would put into the document ready function which I wrote, in not a very clear way – user2405469 Apr 10 '14 at 12:18

2 Answers2

2

You can use,

$(function () { }); 

as an alternate one for document ready.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • Isn't this just an alias ? – Benjamin Toueg Apr 10 '14 at 12:17
  • This is also what I use. I believe its classified as an anonymous function. More information here: http://stackoverflow.com/questions/10371539/why-define-anonymous-function-and-pass-it-jquery-as-the-argument – wrxsti Apr 10 '14 at 12:17
2

is there a better way (in terms of design) to do things like this?

In terms of efficiency and keeping the scope of the local JavaScript, there are other ways in terms of design.

IIFE (Immediately Invoked Function Expression) based on Greg Franko "jQuery Best Practices"

// IIFE - Immediately Invoked Function Expression

  (function(yourcode) {

    // The global jQuery object is passed as a parameter
    yourcode(window.jQuery, window, document);

  }(function($, window, document) {

    // The $ is now locally scoped 

   // Listen for the jQuery ready event on the document
   $(function() {

     // The DOM is ready!

   });

Read more here and this SO answer: https://stackoverflow.com/a/18315393/2777098

Community
  • 1
  • 1
display name
  • 4,165
  • 2
  • 27
  • 52
  • 1
    A good side of `$(document).ready(function () {...});` is, that it's very clear, it implements exactly what is going on in the code... How about the IIFE, does it wait for DOM to be ready? – Teemu Apr 10 '14 at 12:24