Maureen Maureen - 6 months ago 15
Javascript Question

Calling a jquery function in main page from a separate .js file.

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,

Answer

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

Comments