user3601206
user3601206

Reputation: 26

Function does not work in Javascript

i have this function in jQuery:

$(document).ready(function(){ function MyFunction() {alert('Hello!');} });

(For example only)

but, i'm want call this function with regular Javscript this way:

if(x == y){MyFunction();}

(For example only)

and i'ts not work.

However, When i try it:

function MyFunction(){alert('Hello!');} if(x == y){MyFunction();}

(Without jQuery function)

it's work.

Why?

Upvotes: -1

Views: 76

Answers (4)

David Atchley
David Atchley

Reputation: 1204

Lesonchi has it right. The issue is 'scope'.

The $(document).ready(...) call takes a function which is it's own scope (Javascript only has function scoping). So, anything defined inside the function you are passing to that call is ONLY available inside that function.

Based on your question, I assume you wanted to be able to call that MyFunction method elsewhere in the code and not just in the $(document).ready() - so, defining it outside the that call would give it 'global' scope, and hence could be used elsewhere in your code:

function MyFunction(){ /* do something */ }

$(document).ready(function(){
  MyFunction();    // call it in this scope
});

// call it in 'global' scope
if (x == y) {
  MyFunction();
}

See Also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74410

I understand your issue like this {but not really clear what you are looking for imho}

Define function:

function MyFunction(){alert('Hello!');}

Call it on document ready:

$(MyFunction);

Now whenever you want, you could use:

if(x == y){MyFunction();}

Upvotes: 1

Lesonschi
Lesonschi

Reputation: 74

if you put the function outside of the .ready() and call it in the ready function it will work, if you put it in the ready() and call it outside of ready it will give you an error you may have a function declared outside of ready state using jQuery code and call it inside.

    function MyFunction(){
    alert("hello!!");
    }
    //on ready
   $(document).ready(function(){
   if(x==y)
    MyFunction();
   });

Upvotes: 2

Tomer
Tomer

Reputation: 17940

this line:

if(x == y){MyFunction();}

should also be in the document.ready statement.

if you call it outside it will run before the function was actually defined and thus it will fail.

Upvotes: 0

Related Questions