Reputation: 1429
jQuery(document).ready(function(){
var insertionTemplate = jQuery(".hiddenAdBox").eq(0).html(),
insertionTarget = jQuery('ul'),
insertionTargetChildren = insertionTarget.find('li'),
insertionFrequency = 2;
var random;
for (var i = 0; i < insertionFrequency; i++) {
random = Math.floor(Math.random() * insertionTargetChildren.length) + 0;
insertionTargetChildren.eq(random).after(insertionTemplate);
}
});
I have list of items, also need to show ads randomly when you refresh page. Now when ads count is 2 (insertionFrequency = 2
) there is a time when they appear near each other but it shouldn't be so. How can I detect it and don't let ads appear near each other?
Upvotes: 1
Views: 43
Reputation: 29683
To prevent ads horizontally you can do it as below:
for (var i = 0; i < insertionFrequency; i++) {
random = Math.floor(Math.random() * insertionTargetChildren.length) + 0;
if(insertionTargetChildren.eq(random).next('.placeforad').length || insertionTargetChildren.eq(random).prev('.placeforad').length)
//check whether its previous li or next li has ad with class .placeforad
{
i--; //decrease the count so as to come up with separate random number
}
else
insertionTargetChildren.eq(random).after(insertionTemplate);
}
But for vertical prevention since you do not have equal amount of squares in each row like 1st and 2nd rows have 3 blocks and last row has only 2, its very tricky to identify horizontal. If there equal amount of squares then some approach might be taken to achieve that too..
Update
Since you agreed to get 3 blocks in a row the below code will avoid getting ads horizontally as well as vertically
A small DEMO
for (var i = 0; i < insertionFrequency; i++) {
random = Math.floor(Math.random() * insertionTargetChildren.length) + 0;
var currentElement=insertionTargetChildren.eq(random);
var addedElement=$('li.placeforad:visible');
if(currentElement.next('.placeforad').length || currentElement.prev('.placeforad').length)
{
i--;
}
else
{
if(i!=0)
{
if(addedElement.index() > currentElement.index() &&
(addedElement.index() - currentElement.index())==3)
{
i--;
}
else if(currentElement.index() - (addedElement.index()-1)==3)
{
i--;
}
else
{
insertionTargetChildren.eq(random).after(insertionTemplate);
}
}
else
insertionTargetChildren.eq(random).after(insertionTemplate);
}
}
Upvotes: 1