I started yesterday with jQuery and JavaScript and run into an error.
All I want is to place Ads randomly after an H1-Tag (so let’s say there are 10 H1 on a page dived by 2 = 5 AdPosition) now add 5 AdBlocks after a randomly choosen H1.
Sounds pretty easy but I cant achieve this…: / because jQuery or myCode only paste one AdBlock.
JsFiddle: http://jsfiddle.net/byt3w4rri0r/eCBCK/ – working!
MyHTML:
<body>
<div id="content-inner">
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
</div>
</body>
MyJQUERY/JavaScript:
//count H1
var countH1 = parseFloat($("#content-inner h1").length)-1; //-1 because 0 is also a number!
//how often the ads should be displayed
var ad_count = Math.round(countH1 / 2);
//random helper
var min = 0;
var max = countH1;
//random position
for (counter = 0; counter < ad_count; counter++){
var random_position = Math.round((Math.random() * (max - min)) + min);
console.log("Random_Position:", random_position);
// paste google-code
if ($(".headline").hasClass('advertised') == true) {
random_position++;
console.log('already advertised!')
if (random_position > countH1) {
random_position--;
}
} else {
$('h1:eq('+random_position+')').append('<div class="google_ad1"></div>');
$('h1.headline').addClass('advertised');
}
}
console.log("CountH1 -1, because 0=1, 1=2,....", countH1);
console.log(werbung_anzahl);
console.log(zufall_position);
console.log(counter);
With this line
you are checking if any(!) of the .headline elements has already been advertised. And after the first step there is always one .headline that has been advertised, so this comparison will be true.
What you wanted to do: Check if the .headline with the current index has been advertised
On top of this, you are adding the class “advertised” to all(!) your h1.headline elements. This is what you wanted to do instead
EDIT: This is the full changed for loop from the latest fiddle at http://jsfiddle.net/eCBCK/19