Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a function which is into another .js file?

Here is the simplified of my code:

// script1.js
$(document).ready(function(){
    .
    .
    function myfunc(){ ... }
    .
    .
});


// script2.js
$(document).ready(function(){
    .
    .
    //doesn't work
    $.getScript("./script1.js");
    // anyway I need to call myfunc() here ... how can I access it?
    .
    .
});

As you can see, I've used $.getScript() to require sccript1.js file, but still myfunc() is not defined there. How can I handle that?

like image 779
stack Avatar asked Dec 29 '25 00:12

stack


1 Answers

As you can see, I've used $.getScript() to require sccript1.js file, but still myfunc() is not defined there. How can I handle that?

myfunc is defined inside a document.ready event and is not exposed globally, hence you are not able to use the same in another function which is not inside this document ready event.

You need to either export this function globally or define it outside document.ready event.

Export function globally

$(document).ready(function(){
    .
    .
    function myfunc(){ ... }
    window.myfunc = myfunc; //this line added here
    .
    .
});

Or define it outside

$(document).ready(function(){
    .
    .

    .
    .
});
function myfunc(){ ... }
like image 177
gurvinder372 Avatar answered Dec 31 '25 13:12

gurvinder372



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!