The following code works fine for me:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
"use strict";
var nclick = 0;
$(document).ready(function() {
// ===== START OF QUESTION CODE =====
$("#button").click(function() {
nclick++;
if (nclick == 7) {
nclick = 0;
alert("Pretend that this is an ad.");
}
});
// ===== END OF QUESTION CODE =====
});
</script>
</head>
<body>
<a id="button" href="#">Click me!</a>
</body>
</html>
If your code is not running:
- Check the browser console. Are there any errors?
- Is jQuery included on your page?
- Are you attaching the
#button
function when the page is ready? You might be attempting to add an event before the button is created.
- Have you declared an
nclick
variable and initialised it to zero?
EDIT
Okay, the question has now been clarified - the ad script appears as soon as the page is loaded, but you want to delay it until a button has been clicked 7 times. The solution is basically the same as the above, though:
ads.js
alert("hello, world!");
example.htm
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
"use strict";
var nclick = 0;
var ad_script = null;
$(document).ready(function() {
// ===== START OF QUESTION CODE =====
$("#button").click(function() {
nclick++;
if (nclick == 7) {
nclick = 0;
ad_script = document.body.appendChild(document.createElement("script"));
ad_script.src = "ads.js"
}
else if (ad_script)
{
document.body.removeChild(ad_script);
ad_script = null;
}
});
// ===== END OF QUESTION CODE =====
});
</script>
</head>
<body>
<a id="button" href="#">Click me!</a>
</body>
</html>
Simply add the script into the page once the counter reaches 7.