Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function defined inside $(document).ready()

In and external JS file I have

$(document).ready(function() {
    var example = function(){ alert("hello") }
});

and I want to call that function from my html, how would I do that?

<img src="..." ondblclick="example()" />

n.b. I'm aware of jquery dblclick() but curious about how to correctly do the above.

like image 414
ed209 Avatar asked Aug 19 '12 16:08

ed209


4 Answers

$(document).ready(function() {
    window.example = function() {
        alert("hello")
    }
});

Or define it outside, if possible. It doesn't look like it has to be defined inside document ready at all.

like image 98
Esailija Avatar answered Oct 04 '22 16:10

Esailija


The other solutions here will work, but structurally in your project, the best solution is to remove the event handling code from the HTML and hook up the event entirely via javascript (separate the HTML/JS). Since you already have jQuery in your project, this is very easy. To do that, all you need to do is to put some sort of identification on the image:

<img id="example" src="..." />

Then, in you can just hook up the event code in your ready() function like this

$(document).ready(function() {
    $("#example").dblclick(function() {
        alert("Hello");
    });
});

This has the following advantages:

  1. It creates no global variables - reducing the global namespace pollution.
  2. It separates the HTML from the javascript which keeps all code governing the behavior in one compact spot and is usually a good thing
  3. Using event listeners is a bit more scalable than using .ondblclick - allowing multiple different parts of code to use non-conflicting event handlers on the same object
like image 36
jfriend00 Avatar answered Oct 04 '22 17:10

jfriend00


Your function should be global (in fact, property of window object) if you want to access it from HTML. But best practice is to avoid global variables and functions, using namespace instead:

// let's publish our namespace to window object
if (!window.myNamespace){
    // creating an empty global object
    var myNamespace = {};
}

// and add our function to it
$(document).ready(function() {
    myNamespace.example = function(){ alert("hello"); }
});

We can use it in HTML like this:

<img src="..." ondblclick="myNamespace.example()" />
like image 42
Igor Zalutski Avatar answered Oct 04 '22 16:10

Igor Zalutski


The best option would be to simply define the function outside document.ready(). There is no reason defining the function within the $(document).ready() event is necessary, as if you call the function within the $(document).ready() function, the document is guarenteed to be ready.

However, you can also define the function on the global window object, like so:

$(document).ready(function() {
    window.example = function(){ alert("hello") }
});
like image 30
jeff Avatar answered Oct 04 '22 15:10

jeff