Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
195
rated 0 times [  200] [ 5]  / answers: 1 / hits: 94395  / 13 Years ago, fri, december 23, 2011, 12:00:00

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)


More From » html

 Answers
37

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

[#88409] Wednesday, December 21, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lailab

Total Points: 706
Total Questions: 102
Total Answers: 95

Location: Falkland Islands
Member since Mon, Jul 13, 2020
4 Years ago
;