call a function from javascript in jquery [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How do i call a function in jquery that i have written? The following code that I tried is not working.
<script>
$(function(){
function afunction() {
alert("me");
}
});
</script>
<script>
afunction();
</script>

jQuery is simply a JavaScript library. You can mix regular JavaScript in without requiring everything use the jQuery $(). Because of function scope, wrapping your function in the $(document).ready function will make it unavailable to be called outside of the ready function.
Try changing your code to this:
function afunction() {
alert("me");
}
If you need to define a function inside of a jQuery function or event handler, that's fine too. Although it's been pointed out that you can't call this function outside of the ready event handler, I would like to demonstrate that jQuery and JavaScript are not separate and can be mixed. For instance:
$(document).ready(function() {
function afunction() {
alert("me");
}
afunction();
});

Just to clarify, $(function() is another form of $(document).ready().
As Vedant mentioned, usually you cannot call a function (JS/jQuery) from outside the function in which it is defined.
You should probably declare function afunction() outside of $(function() method, alternatively you could declare it as
global function afunction() for universal access.

okay. Here is What I Meant.
You're Creating A function inside a self executing anonymus function ie. $(document).ready() or $(function()....
So your function is in local scope of that function. Simply Means You cant access that in outside of that function.
So to make it accessible just make it global.
In JavaScript window is global object. So to make your function global, use that object as follows:
$(document).ready(function() {
function afunction() {
alert("me");
}
window.afunction=afunction; //NOTE THIS, IT IS IMPORTANT.
});
Now you can access it elsewhere in your JS.
Here is working Fiddle
Hope it'll help you! cheers :)..

Related

Call a function inside DOM ready [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I Have a Javascript library and unfortunately i Shouldn't change it .
there is a DOM Ready function and i need to call a function inside it, codes as below:
function ready(fn){
if (document.readyState != 'loading'){
console.log('fn called');
fn();
}
else {
console.log('fn loaded');
document.addEventListener('DOMContentLoaded', fn);
}
}
ready(function(){
function hello() {
console.log("hello world!");
}
});
then i need to call hello from outside of this scope, from another function like this:
function btnstart(){
hello();
}
how i can do this?
This is an explanation of your problem in a bit more detail. It's not an answer and I don't expect it to be accepted. It's to help you understand why you can't do what you're asking, unless you can change the existing code.
The problem you are facing is that you create an anonymous function that contains hello() and then pass that to another function. Outside the scope of that anonymous function, hello() does not exist and is therefore not accessible.
Take this example...
function domReady(fn) {
fn.hello();
}
domReady(function() {
function hello() {
console.log("hello");
}
});
This creates an anonymous function and passes it to domReady(), which in turn references it as fn. However, this will also fail as fn does not have a function called hello(). That method would be created if you called fn(), but would still only exist inside that function.
What you really need to do is move hello() outside the scope of domReady() and just pass it as a reference, like this...
function domReady(fn) {
fn();
}
function hello() {
console.log("hello");
}
domReady(hello); // note there are no parenthesis () after hello, so it is a reference and not immediate executed
If you can change that then you can simply call hello() whenever you like (within the same scope). If you cannot change that then you cannot do what you are asking.

Not able to define function

I am writing something like
(function($){
function showAlert(){
alert('test');
}
})(jQuery);
and when I tried to run showAlert(), it's saying showAlert() is not defined.
Can anyone suggest why ?
The scope of a variable in javascript is either
the global scope
the function in which it is defined
showAlert is a variable. It's only available in the scope of the external function you wrote.
If you want to define a function for the external scope, define it in the external scope.
I suppose you're calling that function outside IEFE function.
Calling it outside won't work as it is not in global scope. The IEFE is creating a closure of which , showAlert becomes a part and not of global scope which is window
Do this:
(function($){
window.showAlert = function(){
alert('test');
}
})(jQuery);
It doesn't make sense to put a function declaration inside IEFE unless otherwise it is a jquery plugin. So, just remove it:
function showAlert(){
alert('test');
}
You're Creating A function inside a self executing anonymus function ie. $(document).ready() or $(function()....
So your function is in local scope of that function. Simply Means You cant access that in outside of that function.
So to make it accessible just make it global.
In JavaScript window is global object. So to make your function global, use that object as follows:
$(document).ready(function() {
function showAlert()() {
alert('test');
}
window.showAlert=showAlert(); //NOTE THIS, IT IS IMPORTANT.
});
Now you can access it elsewhere in your JS.
Here is working Fiddle
Hope it'll help you! cheers :)..
If you want to extend jQuery with your function just add function to jQuery object.
Like this:
(function ($) {
$.extend({
showAlert: function () {
alert('test');
}
});
}(jQuery));
Separate this code into file with name jquery.showAlert.js, include it after jquery library
and after this you can use function in this way:
$.showAlert()
Best regards.
This should work!
function showAlert(x) {
alert(x);
}
showAlert($('#anyElementId').val());
Assign the variable X for function and your alert. Then pass your element val into your function call.
Demo: http://jsfiddle.net/94ZtT/

function registering after document.ready [duplicate]

This question already has answers here:
Why can I not define functions in jQuery's document.ready()?
(6 answers)
Closed 8 years ago.
Im trying to understand how the browser works if it has 2 document.ready functions within it.
Sample code: Here printtest() module has a alert statement within my first document.ready function and its been called below but I don't see any action..
$(document).ready(function(){
function printtest(){
alert('Hi')
}
})
$(document).ready(function(){
printtest()
})
http://jsfiddle.net/7FuLc/1/
Since it has 2 document.ready function, how does the browser registers this function?
That code will not work because because javascript function creates a new scope variable every time it is declared. See the following:
$(document).ready(function(){
function printtest(){
alert('Hi')
}
})
$(document).ready(function(){
printtest() // ReferenceError, printtest undefined
})
compare this to
function printtest(){
alert('Hi')
}
$(document).ready(function(){
printtest() // alerts 'Hi'
})
$(document).ready(function(){
printtest() // alerts 'Hi'
})
This way, both $(document).ready(function(){}) understand what printtest is.
To solve your problem, here is the modified code,
var printtest;
$(document).ready(function(){
printtest = function (){
alert('Hi')
}
})
$(document).ready(function(){
printtest(); // alerts 'Hi'
})
Now this will work the way you intend it to be because you declare the variable outside the function. This is due to closure (closure is inner javascript function, meaning that any outside variable can be accessed inside the inner javascript function).
In conclusion, if you want a function that is accessible across different functions, declare it outside so that any other closure will be able to access it.

call inner function from global function to display alert in javascript

I have a javascript code and want to extend this code now. how can I write a makeAMessenger function in global scope so that it triggers when user clicks document and alert below message
THIS. IS. SPART.
currently I have following code.
CODE HERE
Do you mean this ?
function makeAMessenger(madness, sparta) {
return madness.bind(sparta);
}
have a solution here and you don't need to pass variable along, it can be accessed in function.
function makeAMessenger(madness) {
return madness;
}
You can use Function#apply() or Function#call() to bind this.
http://jsfiddle.net/QfNbp/

jQuery -- How did I get here? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I must have used someone's existing code as a framework, and I developed a jQuery/JavaScript application I now need to use. It works fine if invoked from within the following code but I need to pass values for nnn from elsewhere in the page. Because I don't understand jQuery structure well enough, my efforts so far have failed.
<script>
$(function() {
.
.
.
var BuildTree = function(centralID) {
...
}
BuildTree(nnn);
});
I want to do something like:
function BuildTree(...) {
...
}
Thanks!
You have a problem with scope, you're defining BuildTree inside the scope of the function you're passing to jQuery (or $ in this case).
This is a problem in terms of javascript and no jQuery, functions define a scope, what it means is that what you define inside a funcion lives inside of it.
function test() {
var variable = 2; //variable within the scope of test
}
variable //undefined
So, if you need to use it outside, you could define it outside the function and then use it inside or do something like:
$(function(){
...
window.BuildTree = BuildTree //global scope
...
});
Also be careful with the caps, it means you're defining a Constructor, by javascript standars
The scope of the BuildTree function is limited to the scope of the outermost function. You simply need to move the function definition outside of the $(function() { function.
var BuildTree = function(centralID) {
...
}
$(function() {
BuildTree(nnn);
});
BuildTree(nnn); // call it again.
There is no (major) difference between
var FunctionA = function () {
}
and
function FunctionA() {
}
Javascript has function scope, which means that variables defined inside of a function are not accessible outside of that function. Anything that is declared inside of the jQuery function will not be accessible outside of the function.
$(function() {
//anything defined in here will not be accessible outside of this jQuery function
var foo = 'bar';
var buildTree = function(centralId) {
};
});
//this will be undefined since it was declared inside of the jQuery function
buildTree(1);
//this will also be undefined
console.log(foo);
If you want to access the buildTree function, you need to do so inside of the jQuery function.
If BuildTree is just a function, you shouldn't need to put it inside $(function() {. You should just be able to do this:
<script>
function BuildTree(centralId) {
// do stuff
}
</script>
Now you should be able to call this function from anywhere in the page. If you want BuildTree to be invoked when the DOM finishes loading, just do this:
<script>
$(function() {
BuildTree(1234);
});
</script>

Categories

Resources