Mutation Observer can help you do some crazy customization. I was searching for this to listen to some attribute changes. I got this website approved for Google AdSense. You may have seen blank spaces on websites, where ads should be running. But for some reasons like insufficient available ads for your specific criteria, AdSense may not show ads inside your ad-container. You can detect this failure in a lot of ways so that some fixes can be implemented to provide your website visitors with a much better user experience. JavaScript Mutation Observer is what you need if you wanna go crazy with the customization of your ads-container by detecting any change to the data-ad-status attribute for AdSense ad units.
Setting Up Mutation Observer
I want you to know that there are a lot of different ways to just get rid of the blank space occupied by unfilled ads. One way is by using a simple CSS approach shown in another article. But the best way is to use JavaScript method, which will unlock all sorts of additional customization to any element you wanna customize depending on the attribute change by using DOM manipulation techniques.
Google Ads
These ads are safe, informative and interesting. Turn off ad-blocker for this website. Ad revenue helps to keep the site alive.
Please Disable Ad BlockeR
These ads are safe, informative and interesting. Turn off ad-blocker for this website. Ad revenue helps to keep the site alive.
Please Disable Ad BlockeR
In this article, we will listen to attribute change. As I wanna show you how to customize ad containers by listening to attribute, so we will target the ▶ data-ad-status ◀ attribute. But first, let’s set up the built-in mutation observer object that will eventually help us to detect any change being made in real-time in the DOM tree. We will check if it’s working or not, using the ▶ console.log() ◀ method.
We need to give an id for the ins tag of the AdSense ad unit. First, we’ll initialize the element through the id, then declare the mutation observer and later observe for our desired attribute. Console.log() will give us the mutations, attribute names and values. So, now let’s see the HTML and JS code for this much work.
HTML
<div class="display-ad-phone" id="ads-display-phone">
<script async src="https://pagead2.googlesyndication.com/pagead/js/
adsbygoogle.js?client=ca-pub-xxxxxxxxxx"
crossorigin="anonymous"></script>
<!-- Display horizontal -->
<ins class="adsbygoogle"
id="ins-dis-phone"
style="display:block"
data-ad-client="ca-pub-xxxxxxxxxx"
data-ad-slot="xxxxxxxxxx"
data-ad-format="fluid"
data-full-width-responsive="true">
</ins>
<script> (adsbygoogle = window.adsbygoogle || []).push({}); </script>
</div>
CSS
.display-ad-phone
{
position: relative;
left: 100px;
width: 306px;
height: auto;
min-height: 200px;
border: 3px rgba(112,112,112,0.45) solid;
border-radius: 5px;
margin-bottom: 100px;
margin-top: 100px;
}
JavaScript
document.addEventListener('DOMContentLoaded', lookforchange);
function lookforchange()
{
// mutation observer code
const checkme = document.getElementById("ins-dis-phone");
const observer = new MutationObserver( mutations =>
{
console.log(mutations);
mutations.forEach( record =>
{
if(record.type === 'attributes')
{
const attrname = record.attributeName;
const attrvalue = record.target.getAttribute(attrname);
// check on the console
console.log("attribute-name = ", attrname);
console.log("attribute-value = ", attrvalue);
}
});
});
observer.observe(checkme, { attributes: true,
attributeFilter: ['data-ad-status'] });
}
AD
Checking For Specific IDs
We have already initialized our mutation observer with an element’s id. Now let’s add two more elements, you can add as many as you need. You can also use the querySelector method to select multiple elements. So let’s check for ▶ data-ad-status=''filled'' ◀ here the values can be filled or unfilled. We should add one more condition inside the if statement to check for our element/ins-tag. When the attribute has value filled and it’s the targeted id, the codes inside if conditions will get executed.
JavaScript
document.addEventListener('DOMContentLoaded', lookforchange);
function lookforchange()
{
// mutation observer code
const checkme = document.getElementById("ins-dis-phone");
const checkme1 = document.getElementById("ins-dis-phone-1");
const checkme2 = document.getElementById("ins-dis-phone-2");
const observer = new MutationObserver( mutations =>
{
console.log(mutations);
mutations.forEach( record =>
{
if(record.type === 'attributes')
{
const attrname = record.attributeName;
const attrvalue = record.target.getAttribute(attrname);
// check on the console
console.log("attribute-name = ", attrname);
console.log("attribute-value = ", attrvalue);
if(attrvalue === 'filled' &&
record.target.id === 'ins-dis-phone')
{
document.getElementById("ads-display-
phone").style.background = "#4D4D4D";
}
}
});
});
observer.observe(checkme, { attributes: true,
attributeFilter: ['data-ad-status'] });
observer.observe(checkme1, { attributes: true,
attributeFilter: ['data-ad-status'] });
observer.observe(checkme2, { attributes: true,
attributeFilter: ['data-ad-status'] });
}
Remove When It’s Unfilled
We just changed the background color of our ad-container when the ad unit is filled. Now when the ad unit has ▶ data-ad-status=''unfilled'' ◀ we will set display none to the container as the element’s style. This will remove the element/div that’s containing the ad unit from the DOM tree. It will release memory and space, also help with the page performance and user experience. So let’s do that by taking advantage of javascript mutation observer.
JavaScript
document.addEventListener('DOMContentLoaded', lookforchange);
function lookforchange()
{
// mutation observer code
const checkme = document.getElementById("ins-dis-phone");
const observer = new MutationObserver( mutations =>
{
console.log(mutations);
mutations.forEach( record =>
{
if(record.type === 'attributes')
{
const attrname = record.attributeName;
const attrvalue = record.target.getAttribute(attrname);
// check on the console
console.log("attribute-name = ", attrname);
console.log("attribute-value = ", attrvalue);
if(attrvalue === 'unfilled' &&
record.target.id === 'ins-dis-phone')
{
document.getElementById("ads-display-
phone").style.display = "none";
}
}
});
});
observer.observe(checkme, { attributes: true,
attributeFilter: ['data-ad-status'] });
}
AD
Additional Customization As Needed
The crazy thing about using JS is, you have full control over the DOM. You can’t do that by using any CSS method for this purpose like styling the ad-container. With mutation observer, you can set additional conditions inside if statement like targeting specific screen sizes and depending on that setting different borders, paddings, backgrounds and so on. I am just showing you the potential, later you can go crazy with this.
JavaScript
document.addEventListener('DOMContentLoaded', lookforchange);
function lookforchange()
{
// mutation observer code
const checkme = document.getElementById("ins-dis-phone");
const observer = new MutationObserver( mutations =>
{
console.log(mutations);
mutations.forEach( record =>
{
if(record.type === 'attributes')
{
const attrname = record.attributeName;
const attrvalue = record.target.getAttribute(attrname);
// check on the console
console.log("attribute-name = ", attrname);
console.log("attribute-value = ", attrvalue);
if(attrvalue === 'filled' &&
record.target.id === 'ins-dis-phone' &&
window.matchMedia("(min-width: 615px)").matches)
{
document.getElementById("ads-display-
phone").style.background = "#4D4D4D";
document.getElementById("ads-display-
phone").style.border = "3px transparent solid";
}
if(attrvalue === 'unfilled' &&
record.target.id === 'ins-dis-phone' &&
window.matchMedia("(min-width: 615px)").matches)
{
document.getElementById("ads-display-
phone").style.display = "none";
}
}
});
});
observer.observe(checkme, { attributes: true,
attributeFilter: ['data-ad-status'] });
}
Examples Of Some Running Ads
You know it’s true that sometimes when the ads are customized in a simple yet attractive way, even if the visitor isn’t interested enough to click on the ad, they might wanna spend more time on the page, which eventually benefits you in a lot of ways. People like me can appreciate those little but simple and clean details. Look at the right ▶ in-feed ◀ ad given below. On mobile the ads have linear-gradient borders when they are filled - it looks awesome.
Showing Message When Ads Blocked
Another way to take advantage of Mutation Observer is by showing a message when ads are blocked by the browser or some ad-blocker extensions. Inside the ads container you can create a div with some inner text like ▶ please disable ad-blocker ◀ and then when the data-ad-status parameter has value filled you can hide the message. Previously we did set ▶ display=none ◀ to the ad-container when the value is unfilled. This will totally remove the unnecessary blank space and the message, which will provide a better cleaner user experience. If you run ad-blocker on this webpage, you should see a message like in the image given below.
Conclusion
The Mutation Observer object is a very powerful tool to use and learn more about it. Check out this link to know more about mutation observers like how to disconnect it and so on. I have researched a lot while learning this but for the most part, it was kinda confusing like how the author tried to demonstrate its usage. I wanted to show it to you in a very simple and functional way, which should be so easy to understand and implement.
Google Ads
These ads are safe, informative and interesting. Turn off ad-blocker for this website. Ad revenue helps to keep the site alive.
Please Disable Ad BlockeR
These ads are safe, informative and interesting. Turn off ad-blocker for this website. Ad revenue helps to keep the site alive.
Please Disable Ad BlockeR
I hope you have got enough information from this article to implement mutation observer. My guess is you like observing stuff through javascript - check the intersection observer. If you like what I’m doing, then maybe help me out by checking out my youtube channel. I think you like technology, there are a lot of articles and reviews about tech that I published - check them out to gain more knowledge and get a taste of my opinions.
motion+ review article motion+ review youtube
nillkin super frosted matte case review
motion+ bass response