ericbae
ericbae

Reputation: 9644

Calling javascript function inside HTML tag

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?

Upvotes: 17

Views: 95095

Answers (4)

Azadeh Radkianpour
Azadeh Radkianpour

Reputation: 971

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>

Upvotes: 24

Ayman Safadi
Ayman Safadi

Reputation: 11552

  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>

Upvotes: 1

Frank Rosario
Frank Rosario

Reputation: 2661

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.

Upvotes: 1

jfriend00
jfriend00

Reputation: 707148

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');
  }
});

Upvotes: 17

Related Questions