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 this function from my html, how would I do it?

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

nb I know jquery dblclick () , but you are wondering how to do it right.

+5
source share
6 answers
$(document).ready(function() {
    window.example = function() {
        alert("hello")
    }
});

Or define it outside if possible. It does not look like it should be defined inside a document that is ready at all.

+13
source

A better option would be to simply define a function outside document.ready(). There is no reason for defining a function in an event $(document).ready(), as if you were calling a function in a function $(document).ready(), the document should be ready for work.

, :

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

, , - HTML javascript ( HTML/JS). jQuery , . :

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

() ,

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

:

  • - .
  • HTML javascript, , , .
  • , . ondblclick -
+3

( , window), HTML. , :

// let 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"); }
});

HTML :

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

@Esailija , , var .

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

If you do not set var, the variable / function / object will become global. Using var, you set your context in the function document.ready.

+1
source

You can either move the function declaration outside the DOM-ready handler:

function example(){ alert("hello") }

$(document).ready(function() {
    // code
});

But the best solution is to save JavaScript in your .js files and to exclude built-in event handlers. Give the element an identifier and enter it:

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

$(document).ready(function() {
    document.getElementById("imgid").ondblclick = function(){ alert("hello") }
});
+1
source

All Articles