1

I am using Bootstrap modal in my project and I have the following scenario. I have one html page Index.html which contains code to open bootstrap modal on button click using following code.

jQuery('#modellink').click(function(e) {
  $('.modal-container').load(url,function(result){
    $('#myModal').modal({show:true});
  });
});

In the load method URL load dynamically. The issue is that when I load modalbox.html into bootstrap modal which contains test() javascript function. After that when I again load another HTML file modalbox1.html which does not contain any javascript function. Even if modalbox1.html does not contain any javascript function then also test() javascript function is available since modalbox.html opened previously. So please help me how can I resolved this issue.

Don't Panic
  • 13,965
  • 5
  • 32
  • 51
Pankaj
  • 3,131
  • 4
  • 14
  • 22
  • what is triggering the `test` method – brk Feb 13 '19 at 10:13
  • test contains empty body.below is my test function. function test(){ }.The test() function available when I load another html in modal. – Pankaj Feb 13 '19 at 10:18
  • 1
    please try to add working snippet – Aishwarya Feb 18 '19 at 06:55
  • I have separate project to create above scenario. Where to upload?Please let me know. – Pankaj Feb 18 '19 at 06:57
  • 1
    Scripts in dynamic content are tricky because they may or may not work exactly as you expect. I normally try to put them in the main view instead of the AJAX code, or in a script file that gets loaded along with the AJAX call. – Brian Mains Feb 18 '19 at 12:26
  • I put it in separate script file and get loaded along with ajax call then also not working. – Pankaj Feb 19 '19 at 05:11

1 Answers1

2

From my understanding based on your explanation, you do not want the function test() to be available for another HTML file loaded with AJAX correct?

This can be easily accomplished by declaring the function in a different closure (How do JavaScript closures work?)

In other words, to enclose it within another function, like

(function() {
    //test is declared within the scope of the outer function only so it will not be available in the global closure, i.e. available to other HTML loaded after this
    function test() {
        //do something here
    }
    document.getElementById("someButton").addEventListener("click", test);
})();
mylee
  • 1,293
  • 1
  • 9
  • 14