Displaying pictures under specific conditions

I've recently completed the coding and CSS for my website after working on it for quite some time. Now, I want to enhance it by incorporating new features. The website is fully operational and generates revenue primarily through Google AdSense. I am interested in displaying different images based on whether Adblock is active or not.

Here is the method I found for detecting AdSense activity:

JS (saved as advertisement.js)

document.write('<div id="TestAdBlock" style="display:none;">an advertisement</div>'); 

The part of HTML code:

<div id="adblockFrame">
    <script type="text/javascript" src="js/advertisement.js"></script>
    <script type="text/javascript">
        if (document.getElementById("TestAdBlock") != undefined)
        {
            document.write('<img src="image1.jpg" alt="Image A">');
        }
        else
        {
            document.write('<img src="image2.jpg" alt="Image B">');
        }
   </script>
</div>

CSS:

#adblockFrame {
    visibility: hidden;
}

I am seeking assistance from someone who can help me modify the JS code to display images instead of text. My understanding of JS is limited, so any support would be greatly appreciated.

Answer №1

To start, I would generate an empty div to serve as the target:

<div id="adDetectionContainer"></div>

  <script type="text/javascript">
        if (document.getElementById("AdBlockTest") != undefined)
        {
            document.getElementById('adDetectionContainer').innerHTML="<img src='noAdBlockFound.jpg' alt='No ad blocker detected' />";
        }
        else
        {
            document.getElementById('adDetectionContainer').innerHTML="<img src='adBlockDetected.jpg' alt='Adblock detected!' />";
        }
   </script>

Answer №2

If you're using jquery, and I'm assuming you are based on the tag:

Here's how you can add a div element:

<div id="wheretoappend"></div>

Here is the javascript code:

var whereToAppend = '#wheretoappend';
 var myDiv = $('<div/>', {id: 'mydiv'});
 ($('#adblockFrame').length)
 ? myDiv.addClass('hasit').appendTo(whereToAppend)
 : myDiv.addClass('doesnt').appendTo(whereToAppend);

And the corresponding CSS:

.hasit  {background: url('hasit.png');}
.doesnt {background: url('doesnt.png');}

Answer №3

It is highly recommended not to use the document.write method in your code.

  • To add content to your page, utilize DOM methods or the .innerHTML property.
  • If you need to detect AdBlock, create a global variable in a file called advertisement.js.

Here is an example setup:

advertisement.js:

window.TestAdBlock = true;

Your webpage:

<div id="adblockFrame">
    <img id="TestAdBlock" alt="AdBlock Detected???" />
    <script type="text/javascript" src="js/advertisement.js"></script>
    <script type="text/javascript">
    (function() {
        var AdBlockImg = document.getElementById('TestAdBlock');
        if (window.TestAdBlock)
        {
            AdBlockImg.src = "/images/AdBlockDetected.jpg";
            AdBlockImg.alt = "AdBlock Detected!";
        }
        else
        {
            AdBlockImg.src = "/images/AdBlockNOTDetected.jpg";
            AdBlockImg.alt = "AdBlock NOT Detected!";
        }
        AdBlockImg.title = AdBlockImg.alt;
    });
   </script>
</div>

Answer №4

One should avoid using document.write in their code as it is considered bad practice. Here's an approach using jquery that I would recommend:

<div id="adblockFrame>
<script type="text/javascript" src="js/advertisement.js"></script>
<script type="text/javascript">
    var adsAllowed = adsAllowed || false;
    var src = adsAllowed ? '/images/myAd.png' : '/images/noAd.png';

    $('#ad').attr('src',src);
</script>
<img id="ad"/>
</div>

advertisement.js

var adsAllowed = true;

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

Implementing line breaks in JSON responses in an MVC application

I am looking to show a JavaScript alert with line breaks using the message returned from a controller action that returns JSON result. I have included "\n" in the message for line breaks. Below is the code snippet from my controller: [HttpPost] publ ...

Creating clones of <li> elements using JQuery and appending them to the end of a <ul> list

I have a regular ul li list and I am looking to add an additional li based on the first one in the list. Here is the HTML: <div id="gallery"> <ul> <li>Point Nr 1<p>lol</p></li> <li>Point Nr 2</li> <li> ...

Comparing strings in AngularJS

Struggling to compare two strings in AngularJS, I've come across various examples online. From what I understand, there are different methods like angular.equals(str1, str2), ===, and == if you're certain both are strings... Despite trying all t ...

Adding JSON data to an array in Node.JS

I am facing an issue where my JSON data is successfully being appended to an array inside a JSON file. However, the problem is that it is not appending inside of the brackets in the JSON file. Below is the code snippet for my NODE if (req.method == &apo ...

Is there a way to transform a JavaScript array into JSON format in order to use it as the returned data from a RESTful API

Currently, I am exploring how to efficiently convert an array of arrays into a JSON string for retrieval through a RESTful API. On my server, data is fetched from a database in the format: {"user":"some name","age":number ...

Challenges regarding OAuth2 and the angular-auth2-oidc Library - Utilizing PKCE Code Flow

As a newcomer to OAuth2 and the angular-auth2-oidc library, I may make some beginner mistakes, so please bear with me. MY GOAL: I aim to have a user click on the login link on the home page, be directed to the provider's site to log in, and then retu ...

What is the best way to incorporate a sliding effect into my cookie form?

I created a cookie consent form for my website and I'm looking to include a sliding effect when it first appears and when it disappears after the button is clicked. How can I implement this sliding effect into the form? Here's the HTML, CSS, and ...

Troubleshooting problem with CSS alignment within Bootstrap framework

Having trouble with the alignment when using bootstrap CSS. My desired layout is as follows: Place name: dropdownbox Gender (radio-button)Male (radio-button)Female Amount Max: textbox Min: textbox Any advice on how to achieve this? ...

Load the React component asynchronously while waiting for the data to be fetched

My ReactJS component looks like this: import React, {useState} from 'react'; import Plot from 'react-plotly.js'; import {utility} from "./utility"; function Chart() { const [use_data, setData] = useState([]); c ...

AngularJs can manipulate the visibility of elements by showing or hiding them based

I wanted to create a simple hover effect where only the child element of each <li> is displayed when I hover over it. Initially, I set up a ng-show value of false for all elements and tried to change it to true on hover. However, this caused all chil ...

Comparison: NumberFormatter versus NumberFormat in PHP and JavaScript

My attempts to format currency seem to yield inconsistent results. Using PHP with the NumberFormatter class, here's a snippet of my code: $number = 5125.99; echo getInternationallyFormattedCurrency($number, 'tl-PH', 'PHP'); echo & ...

How to Make Your Site/Content Fade In with jQuery Upon Loading?

Is there a way to add a fade-in effect to a website once it has finished loading, in order to avoid any sudden changes and ensure that the content appears smoothly? It might be simpler if the fading effect is applied only to certain sections, such as head ...

What's the best way to execute multiple actions within a single gulp task?

Is there a way to execute multiple actions within one gulp task? I have tried using event-stream's merge feature following the example in How to perform multiple gulp commands in one task, but it doesn't work properly when combined with the del p ...

Finding web page links from competition rankings using pattern matching

Challenge I am currently delving into the realm of natural language processing projects. Before diving in, I intend to explore existing works on datasets, particularly those organized on a leaderboard (refer to the "Three-way Classification" section). Ho ...

Inserting HTML content into a DIV with the help of jQuery

Looking for a solution with my index.html file. I want to load other HTML files into a DIV by clicking on buttons. Here's an example of what I'm trying to achieve: I've searched through various examples online, but none seem to work for ...

"Troubleshooting: Why isn't my Tailwindcss box shadow

I'm currently incorporating Tailwindcss into a React project to recreate the Star Wars website mobile menu. However, I am facing an issue where the box shadow added to the hamburger icon segments is not visible when the navigation drawer is opened. A ...

How can I create a box-shaped outline using Three.js?

As someone new to threejs, I have been trying to figure out how to render a transparent box around a symbol in my canvas. The box should only display a border and the width of this border should be customizable. Currently, I am using wireframe to create a ...

jQuery encountering error when uploading multiple files upon loading

I'm having trouble with this jQuery plugin ( ). Whenever I try to set the events on it, I keep getting an error message saying "Function expected". Can someone provide assistance? Everything seems to be working fine except for binding to the events. ...

Using JavaScript, include a child class into a parent class

I am facing an issue with my class hierarchy, which includes classes like Parent, Child1 (which extends Parent), and Child2. Parent contains an array of child items, but importing Child1 and Child2 into Parent leads to circular dependencies and errors whe ...

vue-router incorrectly updates parameters upon reload

One question I have is related to routing in Vue.js: // routes.js { path: '/posts', name: 'Posts', component: PostsView }, { path: '/post/:post_id', name: 'PostRead', component: PostReadView, }, { pat ...