X10nD
X10nD

Reputation: 22050

Call function in jQuery

I have created a function inside a .click

$('#BeforeFunction').click(function(){

//something is entered here then the function below is called
Hello();

});

$('#HitMe').click(function(){
//something here.....
function Hello(){
alert ('Hit button is pressed');
}

});

But the function when called causes an error, the message being Hello is not defined.

What is wrong exactly?

Upvotes: 0

Views: 5595

Answers (4)

jAndy
jAndy

Reputation: 236152

ECMA-/Javascript has a function scope (also called, lexical scope). That means, everything you define within a function is only visible within the scope/context of this function. Hence, Hello is only known within the context of the event-handler function from HitMe.

Probably the best way to create such a function, is NOT to clobber the global namespace (putting it into the window object), but to define your own namespace / scope.

(function($) {
    function hello() {
        alert ('Hit button is pressed');
    }

    $('#BeforeFunction').click(function(){
         //something is entered here then the function below is called
         Hello();
    });

    $('#HitMe').click(function(){
         Hello();
    });


}(jQuery));

Upvotes: 3

James Long
James Long

Reputation: 4736

Each of those click event handlers has its own scope. Anything that you create inside them can't be seen from anywhere else. The reason you're getting that error is that the first click handler doesn't know what Hello is. To get around, that, define your Hello function before your click handlers

function Hello() {
    alert ('Hit button is pressed');
}

$('#BeforeFunction').click(function(){
    //something is entered here then the function below is called
    Hello();
});

$('#HitMe').click(function(){
    //something here.....
});

If you want to understand the concept of JavaScript scope any better, there's a pretty good explanation on Digital Web

Upvotes: 0

Neo
Neo

Reputation: 13901

The curly braces define a scope and limit the definition of Hello function to that scope of "HitMe" function. Define your Hello function outside of the "Hitme" function, preferably before calling it. And you should be fine.

Upvotes: 0

Julio Santos
Julio Santos

Reputation: 3895

You have to define function Hello() outside the click scope.

Upvotes: 0

Related Questions