17

I have the following.

<a href="#" onclick="hello()">click me</a>

And I have a Javascript file

$(document).ready(function() {
 function hello() {
 alert('hi');
 }
});

But when I click on "click me", the alert is not being fired. It says "hello" is not defined. I remove document.ready, and it works.

Is this because "hello" is not being defined until the entire document is ready, but when the above "anchor" tag is being rendered, it can't find the function?

Is there any way I can get this to work?

  • I have to call javascript function from the html tag via ugly "onclick"
  • I need to keep my JS inside document.ready (there are other parts I need)
pizza247
3,9077 gold badges35 silver badges47 bronze badges
asked Dec 23, 2011 at 5:29

4 Answers 4

24

You can also use the HREF attribute with javascript: keyword in Anchor Tag to call a JavaScript function:

<a href="javascript:hello()">click me</a>
answered Dec 19, 2012 at 6:23
Sign up to request clarification or add additional context in comments.

1 Comment

This is an actually interesting and creative solution to this problem.
17

Your hello() function declaration is not in the global scope so the call from the HTML which is trying to call it at the global scope can't find it. You can either fix it by moving your hello() function into the global scope:

function hello() {
 alert('hi');
}
$(document).ready(function() {
});

or by declaring it at the global scope:

$(document).ready(function() {
 window.hello = function() {
 alert('hi');
 }
});
answered Dec 23, 2011 at 5:31

Comments

1

The reason hello is undefined is because Hello() only exists in the context of the DomReady callback. You need to define Hello() in the global context.

answered Dec 23, 2011 at 5:31

Comments

1
  1. Remove "hello()" from $(document).ready() callback.
  2. Call the "hello()" in a "click" event callback.
<a href="#" id="say_hello">click me</a>
<script type="text/javascript">
$(document).ready(function() {
 $('#say_hello').click(function() {
 hello();
 });
});
function hello() {
 alert('hi');
}
</script>
answered Dec 23, 2011 at 5:32

1 Comment

You shouldn't be using inline JS in the first place. Everything the people above have mentioned is correct.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.