What is the proper way of defining javascript functions, inside
$(document).ready(function () {
});
or just outside.
What I have is this :
$(function() {
var html = '<div class ="new1" ><img id = "new2" onclick = "showPage(' + id +
');" class = "' + id +
'" src="@Url.Content("~/Images/blankpageQ.jpg")" />' +
i + '</div>');
$(".pageListQuiz")
.children('div')
.eq(numOfPages - 1)
.append(html);
function showPage() {
//some actions
}
});
and clicking on the appended image throws an exception :
Unhandled exception at line 3, column 1 in script block
0x800a1391 - JavaScript runtime error: 'showPage' is undefined
If there is a handler for this exception, the program may be safely continued.
(The js code is embedded from my c# code.).
Everything works fine if I place showPage() outside anyway. I just wonder why its not working when I put it inside because I also have functions placed inside that are just working fine.
ready. If some code that depends on the DOM, it should be wrapped inready(), other code can be move outside ofready. Also, if the JS is included at the end of<body>there's no need ofready.$(document).readyis irrelevant if you're not using jQuery.ready()callback, it will not be accessible from outside of theready()callback. If you want to call this from HTML or other places(outside ofready), move it out ofready().newImageand have code$(document).on("click", ".newImage", function(event){ // Do your stuff here }).