here is the problem.. i have a javascript file which is named javascript.js like this
$(document).ready(function(){
function init()
{
//code goes here
}
}
now the index.html file has a command button which should call the init() function.
<html>
<head><script src=javascript.js ....></script>
<body><button type="button" onclick="init()">Call Init!</button></body>
</html>
But it doesn't call it. Nothing happens as expected. Please suggest a solution.
4 Answers 4
You should define your function outside $(document).ready() scope.
8 Comments
$(document).ready() You won't lose any functionality and will gain yourself the ability to use the method like you are eluding to in your question. The exception to this is if you have multiple objects that need to have the same method names in which case you would want the methods inside of the object for scope reasons.The onclick attribute will be executed in a global context. Your init function is scoped to the anonymous function which you pass to jQuery. Three solutions:
- Move the
initfunction outside of the ready function, into the global scope - export the
initfunction by making it a property of the global object:window.init = function() {...}; - as you use jQuery, you should not need to define any handlers in attributes. Instead use (inside the ready function):
$("button").click(function init() {...});Even better use anidto reference the button.
Comments
Try viewing the page in chrome. Hit F12 to view the console. You'll be able to quickly debug the issue. At first glance, however, I do see that your $(document).ready function is not closed properly. Add ');' at the end of the code you included. Also, add quotes around javascript.js in your script tag. See if that helps.
1 Comment
Why don't you use
function init()
{
$(document).ready(function() {
//code goes here
});
}
You can use flag too in order to keep track if the "//code goes here" proceeded or not. So in case of document not ready yet, you can use while loop with setTimeOut function for some pause interval "In order to not hang the client browser".
</head>?, what is....?), no homework (any error messages in the javascript console?). Actually after seeing so much sloppiness I didn't even pay attention to the content. I bet the same happened to many other viewers.