I have the following jQuery source (modalConnect()) for loading a form and presenting it via a boostrap modal. It basically prevents the default behavior of an href tag and instead submits an ajax get call. This works fine.
Now I have to add another .js script tag to the dom which I receive from the server. This also works for the first click, for each succeeding click the method is executed the number of times it has been already executed + 1. Which is very strange.
So for the first click I receive the following in the console:
function executed Additional JS executed
which is fine.
For the second click (on the same or another – makes no difference) I receive the following:
function executed Additional JS executed
function executed Additional JS executed
Having now printed the text in total three times in the console, whereas I would only expect having printed it two times.
<script type="text/javascript">
function modalConnect()
{
$(".editItem").click(function(ev) { // for each edit item <a>
ev.preventDefault(); // prevent navigation
var url = ($(this)[0].href); //get the href from <a>
$.get(url, function(results){
var itemForm = $("#ajax_form_modal_result", results);
console.log("function executed");
//update the dom with the received results
$('#itemFormModal').html(itemForm);
//add a new js script to the document. Repeated method calling effect only occurs if I add the following two lines
scriptText = "console.log('Additional JS executed')";
appendScriptTag(scriptText);
//show a bootstrap modal with the loaded form
$("#itemFormModal").modal('show');
}, "html");
return false; // prevent the click propagation
})
}
</script>
asdf
<script type="text/javascript">
function appendScriptTag(scriptText)
{
//create a script tag and append it to the dom
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.text = scriptText;
//the following lines seem to have no effect.
//the "method called more often" effect is not influenced by these lines
document.body.appendChild(script);
document.body.removeChild(document.body.lastChild);
delete UnusedReferencedObjects; // replace UnusedReferencedObject with any object you created in the script you load.
}
</script>
In addition I would be glad if someone could explain me how to properly remove the last js script tag which I added with appendScriptTag(). I think I end up with multiple js included, which is actually bad.
Not sure whether it is correct as I did it there, I followed the explanation from Hendra Uzia from this post.
Once a script is parsed and loaded, removing a script tag will not remove the script. So that’s why those lines have no effect.
If you call modalConnect() multiple times throughout your code, the event listener on the button will also get duplicated, so that one click will cause 5 event listeners to be fired, resulting in 5 messages. That might be it…