Prevent the clustering of advertisements using jQuery

Check out my code in action here!

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 a list of items and want to display ads randomly when the page is refreshed. However, with an ad count of 2 (insertionFrequency = 2), there are times when they appear close together. How can I prevent this and ensure that ads do not show up near each other?

Here are screenshots for reference: https://i.sstatic.net/O3d9J.jpg

https://i.sstatic.net/DWZuK.jpg

Answer №1

If you want to prevent advertisements from appearing horizontally on your website, you can use the following code snippet:

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);
} 

View DEMO

Preventing ads from displaying vertically can be trickier, especially when dealing with rows of different sizes. If each row has an equal number of squares, there are methods that can help achieve vertical prevention as well.


Update:

To ensure 3 blocks appear in a row and avoid both horizontal and vertical ad placement issues, consider using this code snippet:

Check out the 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);
    }
} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to target the sibling of the currently selected or focused element with CSS?

I'm attempting to add button functionality to show and hide errors using CSS. By clicking the CSS button or link, I can target the siblings of the focused element as shown below. This method is only effective in IE8+ browsers. #ShowErrors:focus + a ...

Generate a blank image using the canvas.toDataURL() method

I've been attempting to take a screenshot of this game, but every time I try, the result is just a blank image. var data = document.getElementsByTagName("canvas")[0].toDataURL('image/png'); var out = document.createElement('im ...

Checking if the current time falls within a specific time range, without taking the year into account, using Javascript

I am looking to add a special feature using JavaScript. I would like to change the background images of my webpage to ones related to Christmas during the holiday week, and have it repeat every year. How can I determine if the current date and time fall ...

Creating a uniform mobile version for all smartphones on a website

My website, www.sauleezy.altervista.org, is experiencing an issue that I have been unable to resolve. I have set up two different .css files for desktop (style.css) and mobile (handheld.css). In my index file, I included the following code: <meta name= ...

The output of VueJs hooks shows a blank refs object first, followed by the referenced elements

Below is the HTML VueJS code sample that I am working with: <div v-for="site in topSites" ref="ts"><a :href="site.url"> ... </div> Update: Here is the full div code: <div v-for="site in topSites& ...

Can you explain the difference between the <li> and <div> elements in HTML? How are they used differently

I'm currently exploring the elements for Selenium usage. I have a question about the <li> tag in HTML - could you explain its significance to me? Also, how does it differ from the <div> tag? ...

React Native View will automatically resize to accommodate its content when it is centered

I am facing an issue with a React Native View. I want the View to extend up to a certain width but not exceed it. Inside this View, there is a Text element that should fill out the full width of its parent. The problem arises when I try to center align the ...

How to Programmatically Assign Bootstrap Class to an Element Using Angular 2

I am working on a page with several input boxes that need to be flagged for certain criteria. <div class="form-group"> <label class="d-block">Allowance Type</label> <div class="input-group"> ...

The connection between an HTML form and PHP is not being established

variable-passing.php `<form method="post" action="variable-catching.php"> <input type="text" name="name1"/><br/> <input type="text" name="name2"/><br/> <input type="text" name="name3"/><br/> <input type="te ...

How can I dynamically update the URL parameter based on the selected option in a dropdown list?

There is a single select option box with three options. When a user selects an option, the corresponding value should be appended to the URL (e.g., value=needbyDate). If another option is selected later, the previous value in the URL should be replaced w ...

Please ensure that the menu is included within the HTML file

How can I include a menu from menu.html into index.html? The content of menu.html is: <li><a href="home.html">Home</a></li> <li><a href="news.html">News</a></li> In index.html, the code is: <!docty ...

Adding a variety of data types to a MongoDB collection through Node.js

I'm currently using the Sails web framework along with Node.js and MongoDB to develop my own website. I am encountering some challenges while attempting to add a new user and input values (of different types: Number, Array, Object) to my 'users&a ...

Display the LOADING indicator until the entire page has finished loading

Here is the JavaScript code that I am currently using: function generateRequest(){ var request; if(window.XMLHttpRequest){ // Works with Firefox, Safari, Opera request = new XMLHttpRequest(); } else if(window.ActiveXObject) ...

What is the method for adding a new value to an array stored in a data attribute using square brackets around a text input?

I am dealing with an element that contains an array specified in the following code snippet: <div class="home_team" data-home='["10","20","30"]'></div> Whenever I input a value in the text fi ...

Exploring pathways in Ruby on Rails: navigating the world of web

Having an issue with applying link effects in Ruby on Rails. Here is my current code: <header class="navbar navbarfixed navbar-default navstyle> <%= link_to "Cocktails", root_path, class: "btn btn-lg", id: "logo" %> <nav class="cl-effect-5 ...

Attempting to utilize Ajax to save a file in Laravel, however unsure of what may be causing the issue in my code

Looking for a way to save an image file using ajax in Laravel, here is the code I am currently using: Controller public function store(Request $request) { $item = new Item; // if remove $it_files_path , $it_files_name , $path code work co ...

What is the best way to implement sorting in a table using react virtualized?

I've been working on implementing sorting in my project using the table sorting demo available on Github. Here is the code I'm using: import React from 'react'; import PropTypes from 'prop-types'; import { Table, Column, Sor ...

Can a substring within a string be customized by changing its color or converting it into a different HTML tag when it is defined as a string property?

Let's discuss a scenario where we have a React component that takes a string as a prop: interface MyProps { myInput: string; } export function MyComponent({ myInput }: MyProps) { ... return ( <div> {myInput} </div> ...

Issue with having Clipboard.js function not properly executing within the jQuery.get() method's done

My goal is to perform certain actions when the user clicks a button: Retrieve data from the server using jQuery AJAX. Upon success, assign this data as the value for the button's attribute data-clipboard-text. Copy this value to the clipboard using ...

What is the best way to include a specific stylesheet for Blackberry Curve devices based on certain conditions

Is there a method to include a custom style-sheet specifically for the 'Blackberry curve 2007'? Or perhaps implement a redirect that can identify this device and direct them to a different .html page? I'm looking to create a simplified versi ...