javascript - How can I call an external JS function from a jQuery script? -


back time using node.js, used use fs.readfilesync(filename) call external functions, filename name of file load. might weird using jquery, i'm kind of lost...

currently gathering 3 different files (one .html, 2 others .js), , here how :

here test.html

<body>     <button id="submitting_button">valider</button>      <!--//////////////////////-->     <!-- loads jquery library -->     <script src="jquery/jquery.js"></script>     <!-- loads jqry script -->     <script src="jquery/process.js"></script> </body> 

here process.js

$(document).ready(function(){     $('#submitting_button').click(function(){         $.getscript("./functions/my_function.js");         document.write(calculation());     }); }); 

and finally, here my_function.js

console.log("note : my_function.js has been reached"); function calculation(){     var result = 3+4;     return result; } 

so when click on « valider » button, nothing appens, except fact chrome console displays error, noticing me calculation not defined... guessing because using $.getscript() not thing, don't know other function load/read external function.

getscript() asynchronous, next line of code trying execute before operation completed. since operation isn't completed, function indeed doesn't exist yet.

(note in console error happening before log "my_function.js has been reached" console.)

instead of executing on next line of code, execute in callback getscript():

$.getscript("./functions/my_function.js", function () {     document.write(calculation()); }); 

that way it's invoked after asynchronous operation has completed.

side note: document.write() may or may not whatever expect here. i'm not sure in document value written @ point. it's better away document.write() , instead set value existing element in html. like:

$('#output').text(calculation()); 

where "output" id of element want write value:

<span id="output"></span> 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -