I know whats wrong in code but i am not able to understand why jquery is doing that ,so let me explain my problem with following code
test.html
#############
<!doctype html>
<html class="no-js" lang="en">
<head>
<script type="text/javascript" src="js/jquery-1.12.0.min.js"></script>
</head>
<body>
<div class="wrapper wrapper-layout"> <!-- Header with navigation - Start -->
<button id="btnTestMain" type="button" value="Adjust" class="btn btn-
red1">Button test MAIN</button>
<div id="injectHeaderMainHTML"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#injectHeaderMainHTML").load("/ui-test/test_page.html", 'f' + (Math.random() * 1000000));
$.getScript("js/test1.js", function() {
});
});
</script>
</body>
</html>
###test1.js######
$(document).ready(function() {
$("#btnTestMain").click(function (event) {
$.getScript("/ui-test/js/test.js").done(function() {
console.log("script loaded");
}).fail(function() {
console.log('problem in loading test js');
});
});
}); // Document Ready Closed
test_Page.html
###############################
<button id="btnTest1" type="button" class="btn btn-red1">Button test
1</button>
<button id="btnTest2" type="button" class="btn btn-red1">Button test 2</button>
test.js
###############
function testFunction()
{
console.log("test function called");
}
$(document).ready(function () {
$("#btnTest1").click(function (event) {
console.log("button1 clicked");
});
$("#btnTest2").click(function (event) {
testFunction();
});
});
Now every time i click btnTestMain, it adds event listener to btnTest1 and btnTest2 , so if i click btnTestMain 5 times there will be 5 click event listeners on btnTest1 and 5 on btnTest2. Can anyone explain why this is happening? I know how to resolve the issue but i am not able to understand reason for duplicate event listeners.
jQuery("#btnTest1").click(function (event) { console.log("button1 clicked"); });, 5 times$(document).ready(function () {gets executed everytime your button loads the script.