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.

6
  • what is triggering the test method Commented Feb 13, 2019 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. Commented Feb 13, 2019 at 10:18
  • 1
    please try to add working snippet Commented Feb 18, 2019 at 6:55
  • I have separate project to create above scenario. Where to upload?Please let me know. Commented Feb 18, 2019 at 6: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. Commented Feb 18, 2019 at 12:26

1 Answer 1

2
+25

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);
})();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.