1

i am writing a jQuery file using onClick() to be an event for a button. But i want to load another js function from an external js file. How can i do that ? i have been trying but no result

This is my main.js

$(document).ready(function(){
    $("#dashboard").on("click", function(event){
        event.preventDefault();
        $('#content').html(dashboardTemplate);
        // I want another js external file will be loaded here

    });
});

This is my external js file: The element #btnAddGroup is inside dashboardTemplate which is just a html file

    $("#btnAddGroup").on("click", function (event) {
        event.preventDefault();
        alert('test');
    });

Thank you


Edit : Based on your suggestion

external.js

function addGroup(){
    $("#btnAddGroup").on("click", function (event) {
        event.preventDefault();
        alert('test');
    });
}

main.js

$(document).ready(function(){
    $("#dashboard").on("click", function(event){
        event.preventDefault();
        $('#content').html(dashboardTemplate);
         $.getScript('external.js', function() {
            addGroup();
        });

    });

});

Its still not working. I am trying troubleshoot. thanks again

daniel8x
  • 645
  • 1
  • 9
  • 24

2 Answers2

1

you can try this way

Say this is you external.js file

function () funcEx(){
     console.log("This is logging from external function");
    }

you can call functions of external.js file in main.js file this way. say this is your main.js file

$.getscript("path/to/jsFile",function(){
 funcEx();
});

Hope you can get an idea

Muhammad Usman
  • 9,463
  • 18
  • 35
  • Hi. I tried but no luck. Please see my code above – daniel8x Oct 26 '17 at 00:01
  • what do you expect ? I mean what is your requirement ? Otherwise this code should work fine. can you please post your full code and explain how you want things to be ? – Muhammad Usman Oct 26 '17 at 00:03
  • The code above is everything that i have now. basically, i expect an alert('test') when i click btnAddGroup button which inside dashboardTemplate. the even to click btnAddGroup is stored in an external js. – daniel8x Oct 26 '17 at 00:11
1

You are trying to add event listener to an element which is not yet existing since external file is being loaded before you have clicked to create your btnAddGroup element, so the event will never be attached and fired, however you can add onClick listener to document and check if you have clicked the right element, using jquery 1.7+ it will look like this:

$(window).on("click", "#btnAddGroup", function (event) {
   event.preventDefault();
   alert('test'); 
 });
Roman Habibi
  • 594
  • 4
  • 8