Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

  • 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)
like image 209
ericbae Avatar asked Dec 23 '11 05:12

ericbae


People also ask

Can you call a JS function in HTML?

We can also call JavaScript functions using an external JavaScript file attached to our HTML document. To do this, first we have to create a JavaScript file and define our function in it and save itwith (. Js) extension. Once the JavaScript file is created, we need to create a simple HTML document.

How do I call a JavaScript script from HTML?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Can we call JavaScript function in href?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).

How do you call a function inside a div tag?

You can name each function according to the div 's id and call it dynamically using the object["methodName"]() syntax to call it.


1 Answers

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>
like image 195
Azade Avatar answered Oct 04 '22 04:10

Azade