Display images in javascript condition - javascript

What I want is to replace the area where an ad is supposed to be with a picture of my own if the user has adblock enabled.
I have the code to detect weather the user has adblock enabled or not:
<script type="text/javascript">
function _enabled() {
alert('detected');
}
function _disabled() {
alert('not detected');
}
var _abdDetectedFnc = '_enabled';
var _abdNotDetectedFnc = '_disabled';
</script>
<script type="text/javascript" src="http://adblockdetector.com/script.php"></script>

I would recommend looking into querySelector and innerHTML, or look at a tutorial on jQuery
https://developer.mozilla.org/en-US/docs/Web/API/Element.querySelector
https://developer.mozilla.org/en-US/docs/Web/API/element.innerHTML
You would do something like this:
function _enabled() {
var adSpace = document.body.querySelector("css selector for target ad space");
var htmlContent = getAddBlockedContent();
adSpace.innerHTML = htmlContent;
}
function getAddBlockedContent() {
return "<img ..../>";
}

If disabled, insert your custom tag into the innerHTML of the ad div. Not sure of the question beyond that....

Related

How to Replace Part of Style Background:url in Blogger Widget

Firstly, apologies, I'm a complete novice, I'm sure I'll be using the wrong terminology somewhere.
I am trying to increase the resolution of the images in my Recent Posts widget and Random Posts widget.
I need a piece of code that replaces part of the "background:url" of "a class="mag-thumb", the code needs to replace "/s72-c/" in the url with "/s300/"
e.g.
https://4.bp.blogspot.com/-0STAMmB_Qws/W3bMkXzc2aI/AAAAAAAAKec/zxATGYlKdFM61Y343kTGa1C5FNli11Y9ACLcBGAs/s72-c/s_tronic2_en__download.jpg
would become
https://4.bp.blogspot.com/-0STAMmB_Qws/W3bMkXzc2aI/AAAAAAAAKec/zxATGYlKdFM61Y343kTGa1C5FNli11Y9ACLcBGAs/s300/s_tronic2_en__download.jpg
I am using this theme -> https://www.themexpose.com/2017/09/seoboost-best-seo-optimized-blogger.html
On a test blog here -> https://andybuckdetailing.blogspot.com/
There is already a piece of jQuery code running on the site to do exactly what I want, but only for the Popular Posts widget. However, due to the way the Popular Posts widget is written I can't just copy and modify for the Random and Recent Posts widgets.
Popular Posts has an img src, whereas Recent Posts uses a style background.
Thanks so much in advance for your help!
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var dimension = 150;
$('#PopularPosts1,#PopularPosts2,#PopularPosts3').find('img').each(function(n, image) {
var image = $(image);
image.attr({
src: image.attr('src').replace(/s72-c/, 's' + dimension)
})
})
});
//]]>
</script>
I've tried #Bassam 's solution below, but may have input it into the code incorrectly, I placed it directly below the script above, formatted like this:
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
$('.mag-thumb').each(function () {
var img = this.style.background;
this.style.background = img.replace('/s72-c/', '/s300/');
});
//]]>
</script>
Second try at #Bassam 's solution.
</div>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
$('.mag-thumb').each(function () {
var img = this.style.background;
this.style.background = img.replace('/s72-c/', '/s300/');
});
//]]>
</script>
</body>
Third try at #Bassam's solution, this one's live on the test blog linked above if that helps anyone determine why it's not working.
</div>
<script>
//<![CDATA[
$('.mag-thumb').each(function () {
var img = this.style.background;
this.style.background = img.replace('/s72-c/', '/s300/');
});
//]]>
</script>
</body>
Use this to manipulate background attribute of .mag-thumb
<script>
//<![CDATA[
document.onreadystatechange = function () {
if (document.readyState === 'complete') {
$('.mag-thumb').each(function () {
var img = this.style.background;
this.style.background = img.replace('/s72-c/', '/s300/');
});
}
}
//]]>
</script>

append child after the node of the script that made the call

When the call bellow is done the class creates a set of elements (a form) and then I want to append them right after the script that called it.
I have been looking at various similar questions but the best of them simply append it after the last script on the page.
It would work nicely in the head but not the body.
<script type="text/javascript">
new exampleClass();
</script>
You should have some type of unique identification to find and append elements after the script. You can use document.getElementById() if you have id, or document.getElementsByTagName("script") to get script elements and get the required script element and then use appendChild()
Ok, here is the horrible hack mentioned.
HTML
<div>Stuff</div>
<script type="text/javascript">
noop();
</script>
<div>More stuff</div>
<script type="text/javascript">
new ExampleClass();
</script>
<div>More stuff</div>
<script type="text/javascript">
noop();
</script>
<div>More stuff</div>
Javascript
function noop() {}
function appendAfter(node, newNode) {
if (node.nextSibling) {
node.parentNode.insertBefore(newNode, node.nextSibling);
} else {
node.parentNode.appendChild(newNode);
}
}
function ExampleClass() {
window.addEventListener("load", function () {
var scripts = document.getElementsByTagName("script"),
div = document.createElement("div"),
length = scripts.length,
i = 0,
script;
div.appendChild(document.createTextNode("Inserted"));
while (i < length) {
script = scripts[i];
if (script.firstChild && script.firstChild.nodeValue.indexOf("ExampleClass()") !== -1) {
appendAfter(script, div);
}
i += 1;
}
}, false);
}
On jsfiddle
Based on some of your comments and some other similar I have thought of doing something like this and it seems to work.
// Generate random string we can use as element id
var rs = Math.random().toString(36).substring(2);;
// Document write an empty div with the above string as id
document.write('<div id="' + rs + '"></div>');
// Get the element to use for append
var ip = document.getElementById(rs);
Please feel free to comment if you think it may have a fatal flaw.

My javascript popup shows for a split second if there's a cookie

I have no clue what I'm doing wrong. It works it just shows the popup for a split second. Would a timeout option be better? Which part is the problem? I'm a little new to Javascript so I don't really know what to exactly look for.
<script language="javascript" type="text/javascript">
/** Create a html cookie and set expiry as a day. **/
function createCookie(name,value,days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = date.toGMTString();
document.cookie = name+"="+value+"; expires="+expires+"; path=/";
}
/** Check if already a cookie has been created. **/
function readCookie(name) {
var flag = 0;
var dcmntCookie = document.cookie.split(';');
for(var i=0;i < dcmntCookie.length;i++) {
var ck = dcmntCookie[i];
while (ck.charAt(0)==' ') {
ck = ck.substring(1,ck.length);
}
if(ck) {
cparts = ck.split('=');
if (cparts[0] == name) flag=1;
}
}
if(flag) {
return true;
} else {
return false;
}
}
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
if (readCookie(name)) {
document.getElementById('google').style.display = "none";
document.getElementById('google').style.visibility = "hidden";
}
else createCookie(name,"cookie 4 the day",1);
}
</script>
<script type="text/javascript">
function closeThisDiv()
{
var openDiv = document.getElementById('google');
openDiv.style.display = 'none';
}
</script>
<body onLoad="checkCookie('MyCookie')"
If your goal is to have the element with id="google" to be hidden from the very beginning of the page display (so it never shows), then you should add a CSS rule that loads in the head section like this:
#google {display: none;}
Or, you should add a style element to the HTML itself:
<div id="google" style="display:none"></div>
As your code is currently written, it sounds like it is doing what it is supposed to. It waits for the entire document to be loaded (including images) and then it hides the element with id="google". That means the item will show briefly while the page is loading and then your code will hide it.
If you can't modify the CSS or the HTML for the google object and you're just trying to hide it as soon as possible with javascript and the google object is present in the HTML of your page (not added programmatically), then you can do this:
<body>
other HTML here
<script>
// script that executes right before the /body tag
checkCookie("MyCookie")
</script>
</body>
This will at least not wait for all images to load before hiding it.
I fixed it like this:
Create a css property of display:none; for #google
#google{display:none;}
Then switch around the last portion of code to display only if they don't have the cookie, and to create the cookie.
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
if (readCookie(name)) {
}
else document.getElementById('google').style.display = "inline";
document.getElementById('google').style.visibility = "visibility";
createCookie(name,"cookie 4 the day",1);
In case anyone runs into this problem. Worked great for me.

How to run and display processing code (currently in part of the document.body) in an html canvas?

NOTE: I know I can import .pde files but I need to run code on screen so I will not be using this.
My three following attempts failed. I do not know which one was closer to achieving and I do not prefer one as long as it produces desired result. Appreciate the help by helping me get any of the attempts working/suggesting a new one.
1ST ATTEMPT) - use getText function written below but then some text that is not code can be found in the resulting jscode variable and thus the processing instance does not work.
function getText(n) {
var s = [];
function getStrings(n, s) {
var m;
if (n.nodeType == 3) { // TEXT_NODE
s.push(n.data);
}
else if (n.nodeType == 1) { // ELEMENT_NODE
for (m = n.firstChild; null != m; m = m.nextSibling) {
getStrings(m, s);
}
}
}
getStrings(n, s);
var result = s.join(" ");
return result;
}
var processingCode = getText(document.body)
processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = document.getElementById("mysketch");
var processingInstance = new Processing(canvas, jsCode);
....
<span class="sketch">
<canvas id="mysketch"></canvas>
</span>
2ND ATTEMPT) Same as above but added a tag with id="all_processing_code" but couldn't figure out how to get the text within anyway. This did not work:
var processingCode = getText(document.getElementbyId(all_processing_code));
3RD ATTEMPT) Removed getText and tried to use JQuery text() to isolate the code. Was having trouble mixing JS and Jquery though. Tried different stuff and none worked. What would be appropriate way to mix it in? What script type should I use? This was confusing.
<script type="text/jquery">
var processingCode = $('#all_processing_code').text();
//processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = $.Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = $(#'mysketch');
var processingInstance = new $.Processing($('canvas'), $('jsCode'));
}
</script>
First, check if your processing code is wrapped by an html element (like a div or something else) with an id. If it isn't, please do it!
For exemple:
<div id="mycode">
void setup() {
background(0);
}
</div>
After this, check if you have the getProcessingSketchId() function declared in your code. Processing IDE in JavaScript mode already exports html files with that function. If there isn't, please declare it inside your <head>:
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
You can include JQuery from google api including this line in your html before you use JQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
Assuming that you want to run your processing code when the page just has loaded, just append this code after the getProcessingSketchId() declaration.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
You can create this code inside any other <script type="text/javascript">.
At the end, you will have something like this:
<html>
<head>
<!-- Your title, meta tags, stylesheet and all other stuff here -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
</head>
<body>
<div id="mycode">
void setup() {
background(0);
}
</div>
</body>
</html>

Remove <script> tags using jQuery

I want to remove this Google Analytics block, using jQuery.
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
//var pageTracker = _gat._getTracker("xxx");
pageTracker._trackPageview();
} catch(err) {}
</script>
THE REASON
Because I am creating a bespoke screen reader convertor for jQuery based on a client specification. It's the Google Analytics that is bugging me.
THE PROBLEM
It works with .remove() until you navigate away, then press back. Google Analytics hangs.
Try this:
var replacementDoneIn = $(document.body).text(); //remove Google Analytics document.write line
var regExMatch = /document\.write\(unescape/g;
var replaceWith = "//document.write";
var resultSet = replacementDoneIn.replace(regExMatch, replaceWith);
$("body").html(resultSet);
Hope that helps!
You can also hook document.write and check if its google anlytics code before stopping it like this:
<script>
// Must run before google analytics though
old_document_write = document.write;
document.write = function(str)
{
if(/* determine if the str is google analyic code */)
return false; // dont write it
else
old_document_write(str);
}
</script>
So this work as you hope. At least I think it will:
<script type="text/javascript">
$(document).ready(function () {
$("script").each(function () {
if (this.innerHTML.length > 0) {
var googleScriptRegExp = new RegExp("var gaJsHost|var pageTracker");
if (this.innerHTML.match(googleScriptRegExp) && this.innerHTML.indexOf("innerHTML") == -1)
$(this).remove();
}
});
});
</script>
Just to explain. I loop through all script tags on the page. If their innerHTML property has a length greater than 0 I then check the innerHTML of the script and if I find the string var gaJsHost or var pageTracker in it. I then make sure that I also don't see innerHTML in it as our script will obviously have these in it. Unless of course you have this code in a script loaded on the page using src in which case this script would not have an innerHTML property set and you can change the if line to just be
if (this.innerHTML.match(googleScriptRegExp))
Hope this is what you were looking for.
To actually remove the elements, jQuery('script:not([src^=http])').remove() will work.

Categories

Resources