Insert Google Block Ads with Javascript - javascript

I have a site with many pages and I want to start with Google Ads on it... so I want to insert ads to all the pages, but I want to find a good way... I don't want to add the code manually in all the files... so I tried to build a function to add the google's adsense block after some paragraphs using javascript:
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXX" crossorigin="anonymous"></script>
var display_block = '<ins class="adsbygoogle"' +
'style="display:block"' +
'data-ad-client="ca-pub-XXXXX"' +
'data-ad-slot="xxxxxxxxxx"' +
'data-ad-format="auto"' +
'data-full-width-responsive="true"></ins>' +
'<script>' +
'(adsbygoogle = window.adsbygoogle || []).push({});' +
'</script>';
var afterparagraph1 = document.getElementById('article').getElementsByTagName('p')[0]
afterparagraph1.insertAdjacentHTML('afterend', display_block );
var afterparagraph3 = document.getElementById('article').getElementsByTagName('p')[3]
afterparagraph3.insertAdjacentHTML('afterend', display_block );
Well the code is added (I can see when inspect with console) but the ads doesn´t appear... but if I insert the code manually inside each html file it appears... :(
Do you know what I am doing wrong?
Thanks for your time :)

Related

jQuery image carousel settings doesn't apply to dynamic generated content (Flickr API)

Hope you can help out! :)
I'm trying to created an image carousel (Owl Carousel) with dynamic loaded content instead of static code. This dynamic content is generated using jQuery and the Flickr API.
The script you'll find below, retrieves images from a specific Flickr album and converts the data into HTML elements (image + link). Using the $.each(data.photoset.photo, function(i, item){ function I'm creating the carousel's content according the the requirements given.
The issue is, that somehow the jQuery settings from the Owl Carousel don't apply to the dynamic generated content. Using inspect element in the browser, I can see that the content is generated correctly and also some of the carousel's settings are applied to the generated content but it's not showing in the front-end: view screenshot
Note: Converting the dynamic content to static content and inserting it inside the carousel works fine. It looks like the combination of applying a jQuery plugin on dynamic created content using another script is causing the issue.
Code snipped from the <body> (API key required in script):
<body>
<div class="owl-carousel">
</div>
<script type="text/javascript">
function getFlickrImages(setId) {
var URL = "https://api.flickr.com/services/rest/" + // Wake up the Flickr API gods.
"?method=flickr.photosets.getPhotos" + // Get photo from a photoset. https://www.flickr.com/services/api/flickr.photosets.getPhotos.htm
"&api_key=<YOUR-API-KEY>" + // API key. Get one here: http://www.flickr.com/services/apps/create/apply/
"&photoset_id=72157663149819061" + // The set ID.
"&user_id=135343422#N06" +
"&privacy_filter=1" + // 1 signifies all public photos.
"&per_page=10" + // For the sake of this example I am limiting it to 20 photos.
"&format=json&nojsoncallback=1"; // Er, nothing much to explain here.
// See the API in action here: https://www.flickr.com/services/api/explore/flickr.photosets.getPhotos
$.getJSON(URL, function(data){
var owner = data.photoset.owner;
var phot_set_id = data.photoset.id;
$.each(data.photoset.photo, function(i, item){
// Creating the image URL. Info: https://www.flickr.com/services/api/misc.urls.html
var img_src = "https://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_m.jpg";
//var img_thumb = $("<img/>").attr("src", img_src).attr("id", item.id).css("margin", "8px");
var link_src = "https://www.flickr.com/photos/" + owner + "/" + item.id + "/in/set-"+phot_set_id;
var img_link = $("<a/>").attr("href", link_src);
var img_thumb = $('<img />').attr({src:img_src}).appendTo($('<a />').attr({href:link_src,target:"_blank"}).appendTo($('.owl-carousel')).wrap("<div></div>"));
});
});
}
$(document).ready(function() {
getFlickrImages("72157650210689192"); // Call the function!
});
</script>
<!-- OWL CAROUSEL - http://www.owlcarousel.owlgraphic.com/ -->
<script src="owl.carousel.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".owl-carousel").owlCarousel();
});
</script>
</body>
Try adding the line
$(".owl-carousel").owlCarousel();
at the end of the function getFlickrImages(setId).
The issue might be that the owlCarousel setting applied the first document.ready() got called and at that time your dynamic content had not generated. Thus, if you apply the owlCarousel at the end of the function getFlickrImages(setId), your dom content has already been generated and then the carousel would apply.
I fell into the same issue while using another liquid carousel(http://www.nikolakis.net/liquidcarousel/), but applied the same solution as I have described above and it worked.
Hope it helps.

Javascript on wordpress website page disappears as soon as I try to save it

I'm trying to insert JavaScript to a WordPress page. I added this to functions.php:
function add_custom_code() {
if (is_front_page()) { ? >
< script >
(function() {
var randomId = Math.floor(Math.random() * 100000);
var targetElemId = ‘bcom_rwidget_’ + randomId;
document.write(‘ < div id = ”‘+targetElemId + ‘” > < /div>‘);
var script = document.createElement(‘script’);
script.type = ‘text / javascript’;
script.async = true;
script.src = ‘http: //www.booking.com/review_widget/gb/the-manor-house-bed-amp-breakfast-enter code here`trunch.en.html?tmpl=review_widget/review_widget&wid=’ + targetElemId + ‘&wtype=box_small&hotel_id=XXXXX&`enter code here`widget_language=en’;
var node = document.getElementsByTagName(‘script’)[0];
node.parentNode.insertBefore(script, node);
}()); < /script> < ? php
}
}
add_action('wp_footer', 'add_custom_code');
But when I add the script to the page, it disappears as soon as I
try to save it.
How can I run a secure JavaScript on a WordPress page?
Have you tried writing the javascript in a diffrent file, then enqueueing it in functions.php and calling it with in case of front page?
You could use one of the following..
1. Using the HTML view of the WYSIWYG Editor.
You need to change the writing mode from Visual to HTML and copy-paste your JavaScript code into the text box. There If you already have some content for the post, then you shall see the HTML for it, just type/paste your js at the bottom of the post content.
Remember to enclose the js code inside the <style> tags. This method will work most of the time, if it doesn't, then we have a plan B :)
2. Using Custom Fields + Short Codes
Here you create a new custom field and set the value of this custom field to the JavaScript code. Then insert a shortcode in your post content which will in turn fetch the value of that custom field.

Blogger feed from RSS on website

I'm trying to get posts from a blog to show on my website via RSS/JavaScript. I can successfully get the title and link to posts to pull in, but nothing else will show when I try to get the actual post content. I feel like I'm missing something simple although after reading through Google's API docs for the last two days I can't seem to figure it out.
Here is the script I'm using:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
var feedContainer=document.getElementById("blog-feed")
var feedURL="http://MYBLOGTITLE.blogspot.com/feeds/posts/default?alt=rss"
var postsReturned=2
var rssoutput="<ul>"
function rssFeedSetup(){
var pullFeed=new google.feeds.Feed(feedURL)
pullFeed.setNumEntries(postsReturned)
pullFeed.load(showFeed)
}
function showFeed(result){
if (!result.error){
var thefeeds=result.feed.entries
for (var i=0; i<thefeeds.length; i++)
rssoutput+="<li><a href='" + thefeeds[i].link + "'>" + thefeeds[i].title + "</a>" + thefeeds[i].content +"</li>"
rssoutput+="</ul>"
feedContainer.innerHTML=rssoutput
}
else
alert("There was an error loading the blog posts.")
}
window.onload=function(){
rssFeedSetup()
}
</script>
Does anyone know if it's possible to get the content this way, or am I approaching this completely wrong? Thank you!
For the sake of clarity, you should include brackets in your for-loop:
for (var i=0; i<thefeeds.length; i++) {
rssoutput+="<li><a href='" + thefeeds[i].link + "'>" + thefeeds[i].title + "</a>" + thefeeds[i].content +"</li>"
}
I'm not sure if this is causing your problem or not. You may have some browser compatibility issues without the brackets.
You should also include semicolons at the end of every statement.
I managed to get your code working by changing the blog URL to an active Blogspot blog. I had to add
<div id="blog-feed"></div>
above your javascript.
Upon further digging, it looks like it's an issue with the Google Feed API and Blogger not passing all of the info to it. When debugging and viewing the raw RSS I can see the content, but when viewing what the script returns it is empty. The code above is working as intended for RSS feeds from Wordpress, it's only Blogger not working. I'll just go with the titles and links for now - thank you!

How to make a JavaScript code run before another

I'm having a problem with my script because of the AdSense script... when the AdSense script fails to load, my script runs well, but if AdSense loads, My script doesn't load. And I know my script runs AFTER the AdSense script.
So I'm thinking, if my script runs before the AdSense script runs (because is a script to change a pre tag to a table, therefore it only changes the layout), everything will load, instead of just loading the AdSense...
My javascript is:
window.onload = function(){
var preElements = document.getElementsByTagName('pre');
var codeLine = new Array();
var newContent
for(var i = 0; i < preElements.length; ++ i)
{
var element = preElements[i];
newContent='<div align="center"><table width="75%" border="1" cellpadding="0" cellspacing="0" >'
codeLine = element.innerHTML.split('\n');
for(var j=0 ; j < codeLine.length ; j++){
newContent = newContent + '<tr><td width="30" class="codeNumber" >' + j.toString() + ' </td><td class="codeTab"> ' + codeLine[j] + '</td></tr>';
}
newContent = newContent + '</table></div>';
element.innerHTML = newContent;
}
}
It is loaded on the Head section and the AdSense is loaded inside a cell and I only have one adspace.
I can't give an ID to cell because the AdSense isn't the only thing on the cell... And another thing.. The place where the AdSense is being called is completely different where i have the pre tag's
SOLVED: First I really didn't know much about this, and after a little research I've found the problem.
1º The AdSense was having a connection problem, and because of that all the scripts that runs after it, will not load
2º It doesn't matter where you have the script if you have "window.onload" in it... I thought that function worked when the window is loading but actualy, it will function after the window fully loads, and this is why it was creating a conflict with the AdSense.
You guys helped me see this things faster!
Generally most people put Ad and Analytics code includes right before the closing </body> tag.
You should try to avoid race conditions with your code, from loading to execution it should be event driven and modular. If Adsense needs to go in a container that is being set by another script, it would make sense to have that other script load Adsense when it's finished updating your DOM, as a callback. Something like this:
function loadAdsense(elementId) {
    var js = document.createElement('script');
    js.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
window.google_ad_client = 'ca-pub-xxxxxxxxxxxx';
window.google_ad_slot = '1234567890';
window.google_ad_width = 336;
window.google_ad_height = 280;
document.getElementById(elementId).appendChild(script);
}
function preToTable() {
// set PRE to TABLE - id = myNewTable
// then load Adsense
loadAdsense('myNewTable');
}
You should place your javascript in the head tag, and the AdSense code at the end of your content. Another solution is to use a javascript event to print the AdSense script when your first script is done.
SOLVED: First I really didn't know much about this, and after a little research I've found the problem. 1º The AdSense was having a connection problem, and because of that all the scripts that runs after it, will not load 2º It doesn't matter where you have the script if you have "window.onload" in it... I thought that function worked when the window is loading but actualy, it will function after the window fully loads, and this is why it was creating a conflict with the AdSense.

JavaScript source file not loading in IE8 Popup

I have an issue where the JavaScript source file is loading in popup for IE6, Chrome, Firefox, Safari and Opera. But the same source file is not loading up in IE8.
As a result of this the HTML is not being replaced in the Popup and I am getting an error in IE8 popup saying tinyMCE is not defined
I have referred to Formatting this JavaScript Line and solved issue on all browsers except IE8.
The JavaScript function is as follows:
function openSupportPage() {
var features="width=700,height=400,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes";
var winId=window.open('','',features);
winId.document.open();
winId.document.write('<html><head><title>' + document.title + '</title><link rel="stylesheet" href="../css/default.css" type="text/css">\n');
var winDoc = winId.document;
var sEl = winDoc.createElement("script");
sEl.src = "../js/tiny_mce/tiny_mce.js";/*TinyMCE source file*/
sEl.type="text/javascript";
winDoc.getElementsByTagName("head")[0].appendChild(sEl);
winId.document.write('<script type="text/javascript">\n');
winId.document.write('function inittextarea() {\n');
winId.document.write('tinyMCE.init({ \n');
winId.document.write('elements : "content",\n');
winId.document.write('theme : "advanced",\n');
winId.document.write('readonly : true,\n');
winId.document.write('mode : "exact",\n');
winId.document.write('theme : "advanced",\n');
winId.document.write('readonly : true,\n');
winId.document.write('setup : function(ed) {\n');
winId.document.write('ed.onInit.add(function() {\n');
winId.document.write('tinyMCE.activeEditor.execCommand("mceToggleVisualAid");\n');
winId.document.write('});\n');
winId.document.write('}\n');
winId.document.write('});}</script>\n');
window.setTimeout(function () {/*using setTimeout to wait for the JS source file to load*/
winId.document.write('</head><body onload="inittextarea()">\n');
winId.document.write(' \n');
var hiddenFrameHTML = document.getElementById("HiddenFrame").innerHTML;
hiddenFrameHTML = hiddenFrameHTML.replace(/&/gi, "&");
hiddenFrameHTML = hiddenFrameHTML.replace(/</gi, "<");
hiddenFrameHTML = hiddenFrameHTML.replace(/>/gi, ">");
winId.document.write(hiddenFrameHTML);
winId.document.write('<textarea id="content" rows="10" style="width:100%">\n');
winId.document.write(document.getElementById(top.document.forms[0].id + ":supportStuff").innerHTML);
winId.document.write('</textArea>\n');
var hiddenFrameHTML2 = document.getElementById("HiddenFrame2").innerHTML;
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/&/gi, "&");
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/</gi, "<");
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/>/gi, ">");
winId.document.write(hiddenFrameHTML2);
winId.document.write('</body></html>\n');
winId.document.close();
}, 300);
}
Additional Information:
Screen shot of the page
Rendered HTML
Original JSPF
please help me with this one.
Why are you using actual DOM functions to add the <script> tag that includes tinymce.js but everything else is using document.write?
I think that's also where your problem lies, as <head> is within <html>, which is not yet closed where you want to append said <script> tag.
Otherwise, you could use the existing <script> tag in the popup to add the code that includes the required external javascript file. If that makes any sense.
So, basically I'm saying, try it the same way as everything else is in your script, using document.write.
(quick addition) I'm not saying this is the 'best' way to do this, I would recommend creating an actual page instead of dynamically creating one in the popup. But in this scenario, I think what I wrote earlier might solve the problem you are having.

Categories