0

Not very fluent in JavaScript or jQuery for front-end dev. Let's say I have this code:

$("#foo").click(function (event) {
    console.log("single click");
    return false;
});

$("#foo").dblclick(function (event) {
    console.log("double click");
    bar();
    return false;
});

function bar() { //do stuff };

But I've also seen it wrapped within a function:

$(function() {
    $("#foo").click(function (event) {
        console.log("single click");
        return false;
    });

    $("#foo").dblclick(function (event) {
        console.log("double click");
        return false;
    });

    function bar() { //do stuff };
});

Prototyping it, both seem to work. I guess that if they are wrapped within a function, it provides closure and may change things for scope a bit... However for a relative newb, are there pratical reasons why I might want (or not want) to systematically do one or the others? Is there a "better way" or is it rather "it depends", and if it depends... on what?

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
logicOnAbstractions
  • 2,178
  • 4
  • 25
  • 37
  • 1
    The latter waits for DOM ready. – Dave Newton May 18 '21 at 16:38
  • 1
    Not clear from the linked answers: this is called the doc.ready - yes, it does *scope* the variables and any `function bar()` so these won't be accessible outside the doc.ready. Normally you would define your functions outside this (eg `bar()`) then put only your "startup" code such as wiring events inside the doc.ready. Anything that requires the DOM to be ready (all the HTML loaded) - if you always put your code at the end of body, just before `

    ` you don't need doc.ready - sometimes it's best just to add it anyway for startup/events in case it moves in the future.

    – freedomn-m May 18 '21 at 16:56
  • @freedomn-m okay makes sense. Yes I do load the JS only at the bottom of all my files (I did pick that up somewhere). But yes smart to wrap the wiring events. And probably smart as well to not have the functions themselves declared within it. – logicOnAbstractions May 18 '21 at 18:45
  • Anything more than a couple of functions, you probably want to consider namespacing anyway. – freedomn-m May 19 '21 at 08:20

0 Answers0