This is my HTML page:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="myscript.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function closecontactform(){
alert("closing the form");
};
});
</script>
</head>
<body>
<p id="elementname">Click me to call function</p>
</body>
This is in the myscripts.js file:
$(document).ready(function() {
$('#elementname').click(function() {
alert("click detected");
closecontactform();
});
});
My actual pages are quite a bit more complicated than this and include a lot of jquery but this is the basic problem showing only the code necessary. I want to be able to call a function from a separate .js file, whereas the function is defined in the main page. In this basic simple version I tried removing the $(document).ready(function()... and in this simple example that helps however I require that line in my more complicated pages since removing it seems to break everything else I have going on.
You'll see the "click detected" gets called, but the "closing the form" does not.
Are you able to give me any pointers?
Thanks,
You can also solve it with: var $ = jQuery. noConflict(); $(document). ready(function(){ your code in here });
As long as both are referenced by the web page, yes. You simply call the functions as if they are in the same JS file.
jQuery is a JavaScript library, so it operates on top of JavaScript. It cannot exist on its own, so you can't use one over the other. You can use just JavaScript or JavaScript and jQuery. jQuery was introduced to make development with JavaScript easier.
You have a scope problem. You don't need to wrap named function in $(document).ready()
.
If wrapped within ready
it's scope is only available within that ready function due to closure within the function.
Example:
$(document).ready(function() {
function doAlert() {
alert('foo');
}
/* can call function since scope in same parent function*/
doAlert();
});
/* function not in scope, is undefined here*/
doAlert();
Refactor so function is globally available and will work if called from anywhere. Will work in both cases below:
function doAlert() {
alert('foo');
}
$(document).ready(function() {
doAlert();
});
doAlert();
Further note:
Many people worry that functions using jQuery selectors and methods must be wrapped in $(document).ready()
. Named functions outside of ready
can contain all jQuery code... but... they need to be called after DOM is ready to be sure html exists
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With