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

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>

Related

Display images in javascript condition

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....

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.

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>

How to force a script reload and re-execute?

I have a page that is loading a script from a third party (news feed). The src url for the script is assigned dynamically on load up (per third party code).
<div id="div1287">
<!-- dynamically-generated elements will go here. -->
</div>
<script id="script0348710783" type="javascript/text">
</script>
<script type="javascript/text">
document.getElementById('script0348710783').src='http://oneBigHairyURL';
</script>
The script loaded from http://oneBigHairyURL then creates and loads elements with the various stuff from the news feed, with pretty formatting, etc. into div1287 (the Id "div1287" is passed in http://oneBigHairyURL so the script knows where to load the content).
The only problem is, it only loads it once. I'd like it to reload (and thus display new content) every n seconds.
So, I thought I'd try this:
<div id="div1287">
<!-- dynamically-generated elements will go here. -->
</div>
<script id="script0348710783" type="javascript/text">
</script>
<script type="javascript/text">
loadItUp=function() {
alert('loading...');
var divElement = document.getElementById('div1287');
var scrElement = document.getElementById('script0348710783');
divElement.innerHTML='';
scrElement.innerHTML='';
scrElement.src='';
scrElement.src='http://oneBigHairyURL';
setTimeout(loadItUp, 10000);
};
loadItUp();
</script>
I get the alert, the div clears, but no dynamically-generated HTML is reloaded to it.
Any idea what I'm doing wrong?
How about adding a new script tag to <head> with the script to (re)load? Something like below:
<script>
function load_js()
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.src= 'source_file.js';
head.appendChild(script);
}
load_js();
</script>
The main point is inserting a new script tag -- you can remove the old one without consequence. You may need to add a timestamp to the query string if you have caching issues.
Here's a method which is similar to Kelly's but will remove any pre-existing script with the same source, and uses jQuery.
<script>
function reload_js(src) {
$('script[src="' + src + '"]').remove();
$('<script>').attr('src', src).appendTo('head');
}
reload_js('source_file.js');
</script>
Note that the 'type' attribute is no longer needed for scripts as of HTML5. (http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#the-script-element)
Creating a new script tag and copying the contents of the existing script tag, and then adding it, works well.
var scriptTag = document.createElement('script');
scriptTag.innerText = "document.body.innerHTML += 'Here again ---<BR>';";
var head = document.getElementsByTagName('head')[0];
head.appendChild(scriptTag);
setInterval(function() {
head.removeChild(scriptTag);
var newScriptTag = document.createElement('script');
newScriptTag.innerText = scriptTag.innerText;
head.appendChild(newScriptTag);
scriptTag = newScriptTag;
}, 1000);
This won't work if you expect the script to change every time, which I believe is your case. You should follow Kelly's suggestion, just remove the old script tag (just to keep the DOM slim, it won't affect the outcome) and reinsert a new script tag with the same src, plus a cachebuster.
Small tweak to Luke's answer,
function reloadJs(src) {
src = $('script[src$="' + src + '"]').attr("src");
$('script[src$="' + src + '"]').remove();
$('<script/>').attr('src', src).appendTo('head');
}
and call it like,
reloadJs("myFile.js");
This will not have any path related issues.
Use this function to find all script elements containing some word and refresh them.
function forceReloadJS(srcUrlContains) {
$.each($('script:empty[src*="' + srcUrlContains + '"]'), function(index, el) {
var oldSrc = $(el).attr('src');
var t = +new Date();
var newSrc = oldSrc + '?' + t;
console.log(oldSrc, ' to ', newSrc);
$(el).remove();
$('<script/>').attr('src', newSrc).appendTo('head');
});
}
forceReloadJS('/libs/');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
I know that is to late, but I want to share my answer.
What I did it's save de script's tags in a HTML file,
locking up the scripts on my Index file in a div with an id, something like this.
<div id="ScriptsReload"><script src="js/script.js"></script></div>
and when I wanted to refresh I just used.
$("#ScriptsReload").load("html_with_scripts_tags.html", "", function(
response,
status,
request
) {
});

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