Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call jQuery function from JavaScript [closed]

I have some jQuery code:

$(function(){ 
function someFunc(){
    /*do something*/
};
.............   
});

And now I want call someFunc from JavaScript like below:

function test(){    
$.fn.someFunc();
}

But it doesn't work! I've seen an article how to call function in jquery from javascript. Is it possible?

like image 238
Nolesh Avatar asked Mar 20 '12 22:03

Nolesh


People also ask

Can we call jQuery function in JavaScript?

You can directly write your jQuery code within a JavaScript function. See below code. I have placed a button on my page which makes a call to a Javascript function "Test()".

Why do we prevent any jQuery code from running before the document is finished loading?

This is to prevent any jQuery code from running before the document is finished loading (is ready). It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.

How do you stop a function call in jQuery?

jQuery stop() Method The stop() method stops the currently running animation for the selected elements.

How to write jQuery functions?

Answer: Use the syntax $. fn. myFunction=function(){} The syntax for defining a function in jQuery is little bit different from the JavaScript.


2 Answers

Just defining a function within the closure (function) you pass into $() doesn't do anything to put it on the jQuery fn object. To do that, you have to do it explicitly:

$.fn.someFunc = someFunc;

Typically, you wouldn't do this within a callback on $(), you'd do it earlier. Plug-ins do this to add functionality, which should already be present prior to DOM ready.

By way of example, here's a silly little plug-in that turns text green:

(function($) {
  $.fn.green = green;
  function green() {
    return this.css("color", "green");
  }
})(jQuery);

...which you might use from DOM ready:

jQuery(function($) {

  $(".foo").green();

});

Live example | Live source

Note that the call to it is from a jQuery instance, not directly from $.fn.

like image 151
T.J. Crowder Avatar answered Oct 13 '22 06:10

T.J. Crowder


You function someFunc is not a "jQuery function", it is a function defined inside a (jQuery) DOMContentLoaded event handler.

You can't access it from outside because it is out of scope. Just declare it outside the load handler, and it will be accessible:

$(function(){ 
    // nothing here , but you can call someFunc() if you want
});

function someFunc(){
    /*do something*/
};

function test(){    
    someFunc(); // works!
}
like image 28
bfavaretto Avatar answered Oct 13 '22 07:10

bfavaretto