Page Navigation Script not fully working in Blogger - javascript

I picked up this great javascript from MS-Potilas of http://yabtb.blogspot.com/ which gives me my next and previous blog titles appended to the prev and next icons by calling the title information from the blog feed. And if that somehow fails, it has a backup, which is to pull the information off the urls and turn that into the title in its PseudoTitle mode.
Thing is, it only works for about the newest half of my blog posts. After that, it switches into PseduoTitle mode.
Here's what I don't understand. It's supposed to work for 500 posts. My site only has 350+. So why does it seem to work properly for only the newest 100+ posts?
Also, is there something I can do so that I can increase the number of posts that this script will work for after I go past 500 posts?
Thanks a lot for your help.
Here's the script;
<script type='text/javascript'>
// Post titles to Older Post and Newer Post links (without stats skew)
// by MS-potilas 2012. See http://yabtb.blogspot.com/
//<![CDATA[
var urlToNavTitle = {};
function getTitlesForNav(json) {
for(var i=0 ; i < json.feed.entry.length ; i++) {
var entry = json.feed.entry[i];
var href = "";
for (var k=0; k<entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
href = entry.link[k].href;
break;
}
}
if(href!="") urlToNavTitle[href]=entry.title.$t;
}
}
document.write('<script type="text/javascript" src="//'+window.location.hostname+'/feeds/posts/summary?redirect=false&max-results=500&alt=json-in-script&callback=getTitlesForNav"/>');
function urlToPseudoTitle(href) {
var title=href.match(/\/([^\/_]+)(_.*)?\.html/);
if(title) {
title=title[1].replace(/-/g," ");
title=title[0].toUpperCase() + title.slice(1);
if(title.length > 28) title=title.replace(/ [^ ]+$/, "...")
}
return title;
}
$(window).load(function() {
window.setTimeout(function() {
var href = $("a.blog-pager-newer-link").attr("href");
if(href) {
href = href.replace(/\http\:[^/]+\//, "https");
var title=urlToNavTitle[href];
if(!title) title=urlToPseudoTitle(href);
if(title) $("a.blog-pager-newer-link").html("<< Newer<br />" + title);
}
href = $("a.blog-pager-older-link").attr("href");
if(href) {
href = href.replace(/\http\:[^/]+\//, "https");
var title=urlToNavTitle[href];
if(!title) title=urlToPseudoTitle(href);
if(title) $("a.blog-pager-older-link").html("Older >><br />" + title);
}
}, 500);
});
//]]>
</script>

Seems I managed to figure it out.
Apparently, even though the script says max-results=500, the script is really only pulling 150 posts. I don't know why that is.
So I just added more retrieval scripts like this to cover the rest.
document.write('<script type="text/javascript" src="//'+window.location.hostname+'/feeds/posts/summary?redirect=false&max-results=150&start-index=151&alt=json-in-script&callback=getTitlesForNav"/>');
function urlToPseudoTitle(href) {
var title=href.match(/\/([^\/_]+)(_.*)?\.html/);
if(title) {
title=title[1].replace(/-/g," ");
title=title[0].toUpperCase() + title.slice(1);
if(title.length > 28) title=title.replace(/ [^ ]+$/, "...")
}
return title;
}
Many thanks to Adam over at http://too-clever-by-half.blogspot.com/ for providing the solution to the &start-index=151 extension.

Related

where is showing conversation value

THis topic is abouton google add word (conversation)
Below is my conversation setup screenshot
http://nimb.ws/alycTQ
Below is my code that was putted on body tag
<script type="text/javascript">
/* <![CDATA[ */
function GoogleFormTracker()
{
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = 949468534;
w.google_conversion_label = "9xLwCK7rm3IQ9vrexAM";
w.google_conversion_value = 1;
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
}
/* ]]> */
</script>
<script type="text/javascript"
src="//www.googleadservices.com/pagead/conversion_async.js">
</script>
GoogleFormTracker() fired on footer when site is load.
And also i verified my code on tag manager chrome addons(No error showing there).
but i don't know where to showing me how many time this function is fired ?
let me know any mistake in my code or where is showing tracking value in add word (with screenshot and step by step).
Thanks
In google add word account follow below step
Tool->Attribution
In Attribution available you conversation value.
I hope u need like above
"but i don't know where to showing me how many time this function is fired". Not entirely sure I understand, but perhaps you just need to put a console.log('marco'); inside the function and view the browser console (ctrl + shift + i) to see how many times the function is called?

AJAX - Losing the Javascript data

I have been struggling ajaxing my website, which happens to be a WordPress.
What I am trying to do, is to only refresh the content of my blog. What I mean is that my header, footer # sidebar shouldn't be refreshed when I navigate through my website.
It sounded easy to me when I first started, but I was wrong. I've been looking around to find a way to get around problems and found this but it did not help... So, here is my terrible issue :
There are Javascript scripts that are involved in my "refreshed content" and the innerHTML does not keep the JS. Only Html is transposed... As a result, my plugins aren't working anymore.
So, I have been looking for a way to keep the JS content.
I hope I have been clear in desribing my problems and pray for you guys to be able to help me :)
Here is my website : www.construction.urbaineparis.com
If you need more details, I will be very willing to give you the code you need to help.
Here is a part of the source that I believe contains the issue.
//start changing the page content.
jQuery('#' + AAPL_content).fadeOut("slow", function() {
//See the below - NEVER TRUST jQuery to sort ALL your problems - this breaks Ie7 + 8 :o
//jQuery('#' + AAPL_content).html(AAPL_loading_code);
//Nothing like good old pure JavaScript...
document.getElementById(AAPL_content).innerHTML = AAPL_loading_code;
jQuery('#' + AAPL_content).fadeIn("slow", function() {
jQuery.ajax({
type: "GET",
url: url,
data: getData,
cache: false,
dataType: "html",
success: function(data) {
AAPL_isLoad = false;
//get title attribute
datax = data.split('<title>');
titlesx = data.split('</title>');
if (datax.length == 2 || titlesx.length == 2) {
data = data.split('<title>')[1];
titles = data.split('</title>')[0];
//set the title?
//after several months, I think this is the solution to fix & issues
jQuery(document).attr('title', (jQuery("<div/>").html(titles).text()));
} else {
if (AAPL_warnings == true) {
alert("WARNING: \nYou seem to have more than one <title> tag on the page, this is going to cause some major problems so page title changing is disabled.");
}
}
//Google analytics?
if (AAPL_track_analytics == true) {
if(typeof _gaq != "undefined") {
if (typeof getData == "undefined") {
getData = "";
} else {
getData = "?" + getData;
}
_gaq.push(['_trackPageview', path + getData]);
} else {
if (AAPL_warnings == true) {
alert("WARNING: \nAnalytics does not seem to be initialized! Could not track this page for google.");
}
}
}
///////////////////////////////////////////
// WE HAVE AN ADMIN PAGE NOW - GO THERE //
///////////////////////////////////////////
try {
AAPL_data_code(data);
} catch(err) {
if (AAPL_warnings == true) {
txt="ERROR: \nThere was an error with data_code.\n";
txt+="Error description: " + err.message;
alert(txt);
}
}
//get content
data = data.split('id="' + AAPL_content + '"')[1];
data = data.substring(data.indexOf('>') + 1);
var depth = 1;
var output = '';
while(depth > 0) {
temp = data.split('</div>')[0];
//count occurrences
i = 0;
pos = temp.indexOf("<div");
while (pos != -1) {
i++;
pos = temp.indexOf("<div", pos + 1);
}
//end count
depth=depth+i-1;
output=output+data.split('</div>')[0] + '</div>';
data = data.substring(data.indexOf('</div>') + 6);
}
//put the resulting html back into the page!
//See the below - NEVER TRUST jQuery to sort ALL your problems - this breaks Ie7 + 8 :o
//jQuery('#' + AAPL_content).html(output);
//Nothing like good old pure JavaScript...
document.getElementById(AAPL_content).innerHTML = output;
Change
document.getElementById(AAPL_content).innerHTML = AAPL_loading_code;
to
$("#"+AAPL_content).html(AAPL_loading_code);
jQuery takes care of executing scripts that are in the HTML, which .innerHTML does not do.
I doubt this really breaks in IE 7, as your comment says, unless you're using jQuery 2.x (they've dropped support for old IE versions).

Why am I suddenly not getting content from the Blogger API?

I have been using the Google API to get JSON data from my Blogger account and display and format blog posts on my own webiste.
It was working perfectly for weeks, and then suddenly, as of yesterday, the content stops displaying. The title, update (the date the post was updated), and the id, all come back just as they always have. Only the content stopped coming back.
I haven't changed the code in any way since first implementing it, and I looked for documentation to see if the API had changed, but didn't come across anything. So I am completely stumped as to why this one aspect of the code would suddenly stop working.
This is pretty much the entire Javascript that I use to get the JSON data. Is there something wroing with it?
function init() {
// Get your API key from http://code.google.com/apis/console
gapi.client.setApiKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
// Load the Blogger JSON API
gapi.client.load('blogger', 'v3', function() {
// Load the list of posts for code.blogger.com
var request = gapi.client.blogger.posts.list({
'blogId': 'xxxxxxxxxxxxxxxxxxx',
'fields': 'items(content,title,updated,id)'
});
request.execute(function(response) {
var blogger = document.getElementById("blogger");
var anchor = 0;
for (var i = 0; i < response.items.length; i++)
{
var bloggerDiv = document.createElement("div");
bloggerDiv.id = "blogger-" + i;
bloggerDiv.className = "bloggerItem";
$(bloggerDiv).append("<h2>" + response.items[i].title + "</h2>");
var date = response.items[i].updated;
date = date.replace("T", " ");
date = date.replace("+09:00", "");
var printDate = new moment(date);
$(bloggerDiv).append("<p><span class='byline'>" + printDate.format('dddd, MMMM Do YYYY, h:mm:ss a') + "</span></p>");
$(bloggerDiv).append(response.items[i].content)
bloggerAnchor = document.createElement("a");
bloggerAnchor.name = "blogger-" + response.items[i].id;
blogger.appendChild(bloggerAnchor);
blogger.appendChild(bloggerDiv);
anchor = anchor + 1;
}
// find out which anchor the user wanted...
var hashVal = window.location.hash.substr(1);
// ... then jump to that position:
location.hash = "#" + hashVal;
});
});
}
Now fetchBodies defaults is false instead of true. For this reason you need to add param fetchBodies=true.

only add script to head if doesn't exist

I want to add additional scripts and styles to my site when a specific div is loaded.
I start out by defining a path to either a script or stylesheet and then create an element. Hereafter I append the element to the head tag in HTML.
But I would like a way to see if the script or stylesheet already has been append before I append it again. It would be stupid to append an already existing script or stylesheet.
Q: How do I use javascript to check wether or not a script already exists in the head tag, and then append the element if not?
EDIT
I have made a function based on the answer from #KernelPanik. It doesn't work yet but hopefully it will. The function is currently in question: my script appending function doesn't work
If you can use jquery, this code is good
function appendScript(filepath) {
if ($('head script[src="' + filepath + '"]').length > 0)
return;
var ele = document.createElement('script');
ele.setAttribute("type", "text/javascript");
ele.setAttribute("src", filepath);
$('head').append(ele);
}
function appendStyle(filepath) {
if ($('head link[href="' + filepath + '"]').length > 0)
return;
var ele = document.createElement('link');
ele.setAttribute("type", "text/css");
ele.setAttribute("rel", "Stylesheet");
ele.setAttribute("href", filepath);
$('head').append(ele);
}
In your code write
appendScript('/Scripts/myScript.js');
appendStyle('/Content/myStyle.css');
var lib = '/public/js/lib.js';
if (!isLoadedScript(lib)) {
loadScript(lib);
}
// Detect if library loaded
function isLoadedScript(lib) {
return document.querySelectorAll('[src="' + lib + '"]').length > 0
}
// Load library
function loadScript(lib) {
var script = document.createElement('script');
script.setAttribute('src', lib);
document.getElementsByTagName('head')[0].appendChild(script);
return script;
}
You can use the DOM getElementsByTagName("script") to get all of the <script> tags in the document. Then you can check the src urls of each script tag returned, for the url of the script(s) that you have added to the head section. Likewise, you can do something similar for the style sheets by replacing the search of "script" with "style".
For example, if the url of the script appended to the <head> section is header_url.html
var x = document.getElementsByTagName("script");
var header_already_added = false;
for (var i=0; i< x.length; i++){
if (x[i].src == "header_url.html"){
// ... do not add header again
header_already_added = true;
}
}
if (header_already_added == false){
// add header if not already added
}
Likewise, if the url of the style appended to the <head> section is header_style.css
var x = document.getElementsByTagName("style");
var header_already_added = false;
for (var i=0; i< x.length; i++){
if (x[i].src == "header_style.css"){
// ... do not add header again
header_already_added = true;
}
}
if (header_already_added == false){
// add header if not already added
}
A similar question was also asked here: Check if Javascript script exists on page
I used Jack Lee's solution. It was easy to implement and quickly versitile with just about any type file.... I didn't expand on anything ...I actually probably stupefied it a bit... just wanted to list what I did in case it helps someone else...
var lib_jq = '//pathtofile/jquery.js';
var lib_bs = '//pathtofile/bootstrap.min.3.5.js';
var lib_cs = '//pathtofile.css';
///checks files with the SRC attribute
function isLoadedScript(lib) {
return document.querySelectorAll('[src="' + lib + '"]').length > 0
}
///checks files with the HREF attribute
function isLoadedCss(lib) {
return document.querySelectorAll('[href="' + lib + '"]').length > 0
}
///loads the script.js files
function loadScript(link) {
document.write('<scr' + 'ipt type="text/javascript" src="'+link+'"></scr' + 'ipt>');
}
///loads the style.css files
function loadCss(link) {
document.write('<link rel="stylesheet" href="'+link+'">');
}
/// run funtion; if no file is listed, then it runs the function to grab the URL listed. ///Run a seperate one for each file you wish to check.
if (!isLoadedScript(lib_jq)) { loadScript(lib_jq); }
if (!isLoadedScript(lib_bs)) { loadScript(lib_bs); }
if (!isLoadedCss(lib_cs)) { loadCss(lib_cs); }
I know there is always a "better" and more "elegant" solution, but for us beginiers, we got to get it working before we can start to understand it...
Another way with a function helper like below
function isScriptAlreadyPresent(url) {
var scripts = Array.prototype.slice.call(document.scripts);
return scripts.some(function(el) {
return el.src && el.src != undefined && el.src == url;
});
}
isScriptAlreadyPresent('http://your_script_url.tld/your_lib.js');
It uses Array.prototype.some function. You may need a es5-shim if your are in browsers not supporting ES5 (IE7 and IE8...)
maybe headjs can help you.
or maybe you can add onload attribute in the script tag.
my english is a little poor,so maybe i'm misunderstand your question.
if(ie){
js.onreadystatechange = function(){
if(js.readyState == 'complete'){
callback(js);
}
}
else{
js.onload = function(){
callback(js);
}
You can try calling some function, object, variable from that js script file, if it finds it then it exists, if not, you need to insert that js script file.

Change all website links to affiliate links automatically

I would like to be able to automatically change links into affiliate links automatically on my MediaWiki installation. This would help to reduce the amount of time managing links in case the code needs to be changed in the future.
This is the setup of my GOG.com affiliate scheme: I need to append this key to the end of every GOG.com link: ?pp=708a77db476d737e54b8bf4663fc79b346d696d2
gog.com/en/gamecard/baldurs_gate_the_original_saga/?pp=708a77db476d737e54b8bf4663fc79b346d696d2
Is it possible for a piece of code, like Javascript, to intercept all links (like http://www.gog.com/en/gamecard/baldurs_gate_the_original_saga/) and append the affiliate code on the end, as in the above example?
I'm aware of this piece of Javascript code called Amazon Associate Link Localiser which does a similar thing. However, it only works for Amazon links, and it also localises links which is a feature I don't want.
Right way is to use LinkerMakeExternalLink mediawiki hook like that ( you can put it at bottom of your LocalSettings.php:
$wgHooks['LinkerMakeExternalLink'][] = 'ExampleExtension::exampleLinkerMakeExternalLink';
class ExampleExtension {
public static function exampleLinkerMakeExternalLink( &$url, &$text, &$link, &$attribs, $linktype ) {
if( strpos( $url, 'gog.com') !== false ) {
$url .= '?pp=708a77db476d737e54b8bf4663fc79b346d696d2';
}
return false;
}
}
Not sure how great it would be performance wise for hundreds of links.
// Plain Javascript
var links = document.getElementsByTagName('a');
for (var i = 0, max = links.length; i < max; i++) {
var _href = links[i].href;
if (_href.indexOf('gog.com') !== -1) {
links[i].href = _href + '?pp=708a77db476d737e54b8bf4663fc79b346d696d2';
}
}
DEMO
So you can also use jquery to bind any link click. This way you can do your link eval on the fly. This jsfiddle is a rough run through of what i think you're trying to accomplish. The alerts are just for your benefit and should be removed.
$("a").click(function() {
addAffiliate(this);
});
myCode = "?pp=708a77db476d737e54b8bf4663fc79b346d696d2";
myAmazonCode = "?tag=shihac-20"
function addAffiliate(link) {
alert("enterting script: " + link.href);
if ((link.href).indexOf("gog.com") > -1 && (link.href).indexOf(myCode) < 0) {
link.href = link.href + myCode;
}else if((link.href).indexOf("amazon.com") > -1 && (link.href).indexOf(myAmazonCode) < 0){
link.href = link.href + myAmazonCode;
}
alert(link.href);
return true;
}​
http://jsfiddle.net/du47b/23/
UPDATE: added code and fully qualified paths
UPDATE: added 'else if' block for other codes. using 'else if' instead of just another if block will hopefully cut back on unnecessary processing.

Categories