JavaScript TypeErrors - javascript

I keep getting JS errors in my browsers web console, I have been able to clean up some but I also seem to break more and more the harder I try. I'm not exactly the most experienced JavaScript coder and I just don't know how to solve this to prevent further issues on my clients site.
Any help or insight on what I could do would be much appreciated!
[21:34:36.569] TypeError: $ is not a function # http://bolivares.com/shop/aurelio-tank-baby-blue/:103
http://bolivares.com/shop/aurelio-tank-baby-blue/
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-35293709-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script>
/* <![CDATA[ */
// call fancybox
function openFancy(){
setTimeout( function() {$('#autoStart').trigger('click'); },3000); // show after a second
}
// create cookie on button click
function dontShow(){
$.fancybox.close(); // optional
$.cookie('cookie1', 'yes', { expires: 30 }); // expiration in 30 days
}
function askLater(){
$.fancybox.close(); // optional
$.cookie('cookie2', 'yes', { expires: 7 }); // expiration in 30 days
}
</script>
<script>
$(window).load(
function() {
var visited = $.cookie('cookie1') || $.cookie('cookie2') || $.cookie('cookie3'); // create cookie 'visited' with no value
if (visited == 'yes') {
return false;
} else {
openFancy(); // cookie has no value so launch fancybox on page load
$.cookie('cookie3', 'yes', { expires: 3 }); // expiration in 30 days
}
$('#autoStart').fancybox();
function toggleStuff(){
$('li.toggle-content').hide();
$('h4').click(function() {
$(this).find('ul').slideToggle();
});
}
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=500,left = 590,top = 275');");
}
});
</script>

It looks like you are trying to use jQuery but has not linked it in your source code. Try link it in your code.
And also as a general rule I would say to you to test very small parts of the code. Code one line or two and test it. This way you will know what coused the error and it will be easier to fix.

Make sure that you're including jQuery in your code BEFORE you run this function and any which require $. If this is already the case, check your console to make sure nothing is breaking it.
EDIT: Just took another look. Turns out the issue is that one of your plugins is calling jQuery.noConflict() (http://api.jquery.com/jQuery.noConflict/) Try using jQuery in this place instead of $, or if you're feeling risky, try resetting jQuery with $ = jQuery;

Related

_gaq.push not working in google analytics

ok, so, I have been trying to make _gaq.push work since so long now.
And my corresponding code is as below.
var ext_id = localStorage.ext_id;
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxx-xx']);
_gaq.push(['_trackPageview']);
//console.log(_gaq);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = chrome.extension.getURL('js/ga.js'); //uncomment this
//ga.src = "js/ga.js"
// ga.src = 'https://ssl.google-analytics.com/ga.js';
document.head.append(ga); // make it head
// var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); // comment this out
})();
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "google-analytics");
port.onMessage.addListener(function(response) {
console.log("Message Passing with response",response.category,response.action, response);
// _gaq.push(['_gat._forceSSL']); // remove this
_gaq.push(['_trackEvent', response.category, response.action,ext_id]); // trouble shoot this
console.log(_gaq, "sending this");
});
});
so, the above will be run when there's no activity on the payments page for more than 1 second. And its triggering properly, i.e its executing after 1 second of inactivity on payments page. But, but _gaq.push is showing no trace in the network tab, to make it more obscure, I'm not even getting any error. Can someone pls tell me what I could possibly be doing wrong?
The gaq.push looks fine and should work.
I think your ga.js library is not loading. Maybe since getURL is deprecated? https://developer.chrome.com/extensions/extension#method-getURL

Google Analytics - event tracking code in separate <script> than the page tracking code

On a site I'm working on, the main section of the tracking code is located at the bottom of the pages (not my choice of placement, but that's where it is). That code is the main:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
On one specific page, I want to track an event that gets auto launched on page load. What I have for code at the top of the page (and therefore in a separate tag than the above code) is:
function getFile()
{
if("<%= getFileURL()%>".length>0){
window.location.href = "<%=getFileURL() %>";
var _gaq = _gaq || [];
_gaq.push(['_trackEvent', 'Downloads', '<%= getFileURL()%>']);
}
}
It doesn't seem to be tracking the event though. I'm sure I'm doing something wrong here and I can take some guesses, but it's not clear enough for me to know exactly what I need to change.
Two problems with your code:
You're redirecting before tracking the event. For best results (like #EkoostikMartin mentioned), you'll want a slight delay between the event tracking and redirect.
You've got a local _gaq defined inside getFile(), so you're not talking to the actual Google analytics code.
Try:
function getFile() {
var href = "<%=getFileURL() %>";
if (href.length > 0) {
_gaq.push(['_trackEvent', 'Downloads', href]);
setTimeout(function(){window.location.href = href}, 100);
}
}
You need to delay the redirect. Something like this below has worked for me in the past:
function getFile() {
var href = "<%=getFileURL() %>";
if(href){
_gaq.push(['_trackEvent', 'Downloads', href]);
setTimeout("gotoUrl('" + href + "')", 100);
}
};
function gotoUrl(href) {
window.location.href = href;
};

Browser Update Script

Browser-Update.org provides a nice piece of javascript which alerts users of out-of-date browsers to update them. Unfortunately (a) IE7 is not included in the default list of out-of-date browsers, and (b) the script doesn't work over SSL.
The script they suggest is
<script type="text/javascript">
var $buoop = {}
$buoop.ol = window.onload;
window.onload=function(){
try {if ($buoop.ol) $buoop.ol();}catch (e) {}
var e = document.createElement("script");
e.setAttribute("type", "text/javascript");
e.setAttribute("src", "http://browser-update.org/update.js");
document.body.appendChild(e);
}
</script>
Instead, I'm using external javascript as follows:
app.onload(function() {
if ('https:' === document.location.protocol) return; // Browser Update script is not currently available over SSL.
var $buoop = {vs:{i:7,f:2,o:10.5,s:2,n:9}};
var e = document.createElement('script');
e.setAttribute('type', 'text/javascript');
e.setAttribute('src', 'http://browser-update.org/update.js');
document.body.appendChild(e);
});
To be clear: app.onload() is a nice function which adds functions to the window.onload handler.
This seems to work, but there's an unfortunate side-effect. If the alert is dismissed, it shouldn't show again in that browsing session. With the script above, that doesn't seem to work. On IE7, the alert happens on each page load. Is there a way around that?
var _shown = false;
app.onload(function() {
if(!_shown) {
if ('https:' === document.location.protocol) return; // Browser Update script is not currently available over SSL.
var $buoop = {vs:{i:7,f:2,o:10.5,s:2,n:9}};
var e = document.createElement('script');
e.setAttribute('type', 'text/javascript');
e.setAttribute('src', 'http://browser-update.org/update.js');
document.body.appendChild(e);
_shown = true;
}
});
and if the page is reloading between navigation store it in a cookie or as a session variable.
you could save a cookie when the alert is shown and check every time if that cookie exists before showing the alert.

Google Analytics; Track outbound clicks; How?

I read this article about tracking outbound links on banners and such:
http://seogadget.co.uk/how-to-count-your-outbound-click-stats-with-onclick-in-google-analytics/
So I added this code to the onClick event of my href:
javascript: pageTracker._trackPageview('/outbound/top_banners/banner_name');
Is this enough?
Because I have read some places I need a "link delay" function or something in the HEAD of my document as well, before any javascript is executed!
Also, where exactly in GA (in the interface) will I be able to view the clicks?
Thanks
Here's the problem: every item of data recorded & reported by Google Analytics is sent to the GA Servers in the Request URL component of a Request by the client for the __utm.gif. The function _.trackPageview() provokes the collection/concatenation of the data into a Request URL, as well as the Request itself. In other words, if _trackPageview() isn't called, no data is sent to the GA Servers.
So the question is whether the GA Request (above) is processed before the Request associated with the outbound link. If it is not, then the click on the outbound link is not recorded by GA, which is not what you want.
So what you want to is delay, just slightly--long enough for the GA Request to occur but short enough so that the user doesn't notice the delay--the outbound link Request.
There are a few differences between the code posted in your Q, and the code below--all diffs are directed to this 'race condition'.
First, notice that the return value from the onClick handler is set to "false"--preventing the client browser from (immediately) navigating to http://www.outbound-link.com
The second diff is the call to setTimeout. The third argument passed in, '100' is the number of milliseconds delay.
Third, the onclick handler (fnx) creates its own tracking object, and therefore doesn't rely on a pageTracker object to have been initialized elsewhere.
Your second question is, where in the GA Browser do you view these clicks? Using GA, you can track events in two distinct ways--using _trackEvent() or _trackPageView().
By tracking outbound links the second way (as you did and therefore as i did below) the 'click' shows up not as an event, but as a pageview ('virtual pageview' is the term most often used by the GA Consultants, et al. to indicate something tracked as a page view but which is actually not). So you will see these clicks reported along with other page views--i.e., in Content (along with Traffic and Visitors, the three main headings in the left-hand panel). How can you tell which lines in that report refer to the these outbound clicks? The value of the Page field (usually the left-most column heading) will be the url of the outbound link. Once you know this, of course, you can create an Advanced Segment or Custom Report or even a new Profile, to report these separately.
<script type="text/javascript">
function fnx(that) {
try {
var pageTracker=_gat._getTracker("UA-YOURACCOUNTHERE-PROFILE");
pageTracker._trackPageview("http://www.outbound_link.com");
setTimeout('document.location = "' + that.href + '"', 100)
}catch(err){}
}
</script>
<a href="www.outbound_link.com" onclick='fnx(this);return false;'>"Take Me Here"</a>
This is my 100%-working solution for tracking all outbound links (I love jQuery, so you need to add jquery.js script to page).
function isLinkExternal(link) {
var r = new RegExp('^https?://(?:www.)?' + location.host.replace(/^www./, ''));
return !r.test(link);
}
$(document).ready(function() {
$(document).bind('click', function(e) {
var target = (window.event) ? e.srcElement : e.target;
while (target) {
if (target.href) break;
target = target.parentNode;
}
if (!target || !isLinkExternal(target.href)) return true;
var link = target.href;
link = '/outgoing/' + link.replace(/:\/\//, '/');
_gaq.push(['_trackPageview', link]);
});
});
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-YOURCODE-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
This script give all outbound links to GA like: /outgoing/http/www.example.com.
For better experience you need to create advanced segment for this links. Create it with parameters: "Page" "Starts with" "/outgoing/http".
That's all! Now you have full statistics for your outbound links.
This solution will allow you to click links with target='_blank' and additionally, will allow you to set data attributes on any link and have those automatically send up to GA.
$('a').bind('click', function( event ) {
var target = $(this).attr('href');
if ($(this).attr("data-event-category") !== undefined && $(this).attr("data-event-label") !== undefined) {
gtag('event', 'click', {
'event_category': $(this).attr("data-event-category"),
'event_label': $(this).attr("data-event-label"),
'event_callback': function(){handle_redirect($(this), event);}
});
} else {
handle_redirect($(this), event);
}
});
function handle_redirect(element, event) {
var target = element.attr('href');
var regExp = new RegExp("//" + location.host + "($|/)");
var isLocal = (target.substring(0,4) === "http") ? regExp.test(target) : true;
var url = target;
if(isLocal===true) {
return;
} else {
event.preventDefault();
gtag('event', 'click', {
'event_category': 'outbound',
'event_label': window.location.href + ' --> ' + url,
'transport_type': 'beacon',
'event_callback': function(){element.unbind( "click"); element[0].click();}
});
}
}

How to delay loading external JS file (Google Analytics)?

I'm using the following code to load my Google Analytics (external javascript) in a way that is meant to not block rendering.
However, using both YSlow and Safari Web Inspector - the network traffic clearly shows that the ga.js script is still blocking rending.
/*
http://lyncd.com/2009/03/better-google-analytics-javascript/
Inserts GA using DOM insertion of <script> tag and "script onload" method to
initialize the pageTracker object. Prevents GA insertion from blocking I/O!
As suggested in Steve Souder's talk. See:
http://google-code-updates.blogspot.com/2009/03/steve-souders-lifes-too-short-write.html
*/
/* acct is GA account number, i.e. "UA-5555555-1" */
function gaSSDSLoad (acct) {
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."),
pageTracker,
s;
s = document.createElement('script');
s.src = gaJsHost + 'google-analytics.com/ga.js';
s.type = 'text/javascript';
s.onloadDone = false;
function init () {
pageTracker = _gat._getTracker(acct);
pageTracker._trackPageview();
}
s.onload = function () {
s.onloadDone = true;
init();
};
s.onreadystatechange = function() {
if (('loaded' === s.readyState || 'complete' === s.readyState) && !s.onloadDone) {
s.onloadDone = true;
init();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
}
/* and run it */
gaSSDSLoad("UA-5555555-1");
Any ideas on how I can use JavaScript to delay the loading of the ga.js file, because the code above doesn't appear to do as it intends, until the entire page has been rendered so that I don't block rendering?
/* and run it */
gaSSDSLoad("UA-5555555-1");
Don't “run it” until the page has finished rendering. That is: onload or elsewhere further along. Don't include the above lines in your inline script block itself, or you won't gain anything.
If you use jQuery you can include the run it part in (which is the same as the body onLoad() event):
$(window).load(function() {
/* and run it */
gaSSDSLoad("UA-5555555-1");
});
and if that is not good enough, you run it a second later (for example...):
$(window).load(function() {
setTimeout("run_it()", 1000);
});
function run_it() {
/* and run it */
gaSSDSLoad("UA-5555555-1");
}
Shouldn´t be necessary though...
You can add a listener to the window, document or body's onload event and execute your gaSSDSLoad function at that time.
The code you get from Google Analytics is already non blocking.
Should be something like this:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-5555555-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
Google suggests to include it before the closing tag.
In general if you want to load other javascripts asyncronously I suggest you use some loader like:
LABjs
or ControlJS

Categories

Resources