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?
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()".
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.
jQuery stop() Method The stop() method stops the currently running animation for the selected elements.
Answer: Use the syntax $. fn. myFunction=function(){} The syntax for defining a function in jQuery is little bit different from the JavaScript.
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
.
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!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With