0

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?

1
  • Scoping (or rather, your understanding of it) is wrong. Commented Jan 22, 2011 at 18:36

4 Answers 4

3

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));
Sign up to request clarification or add additional context in comments.

3 Comments

Can I not have the hello() in the #hitme?
@Jean: yes, of course you can :) I edited the post, just forgot to put it in there.
It's a little more complicated than that. What if I want to increment and decrement the value of a variable when a particular trigger is triggered.
0

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

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.