Delay href click, but not with SetTimeout - javascript

I am trying to track the outbound links via google analytics, and Google suggests using this:
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
_gat._getTrackerByName()._trackEvent(category, action);
setTimeout('document.location = "' + link.href + '"', 100);
}
</script>
Which is fine, except, my outbound links are to be opened in a new tab, and I am (naturally) using a target="_blank" for that..
but, the setTimeout method takes that away, and opens the link in the same page..
I've tried using window.open() but I am worried that it will be blocked by browsers..
So, is there anyway that I can execute this js function, and delay the click for just a little while? (100ms as google suggests)?
Thanks.
I've looked at other questions like this on SO, but they don't deal with opening in new tab/window.

Ok to evolve the answer above here is a Jquery plugin that can provide listen a selection of links (based on your own criteria) and provide you a method for callback to them.
fiddle
So in the OP's case the setup could look like:
Google
$(document).ready(function() {
$('a').trackOutBound(null,function() {
var category= $(this).data('category');
_gat._getTrackerByName()._trackEvent(category, $(this).attr('href'));
});
});

Simple, just remove the setTimeout() part of it. So all it does is call the _trackEvent function.
Your links should execute both the javascript function and open the new window, if you just keep them something like:
Click here
<script type="text/javascript">
function recordOutboundLink(category, action) {
_gat._getTrackerByName()._trackEvent(category, action);
}
</script>

I use this to keep the function waiting before continuing with the default browser behavior:
var wait_until = new Date().getTime() + 500;
while (new Date().getTime() < wait_until) {
//Do nothing, wait
}

Related

addEventListener to div element

I am trying to fire a script when the contents of a div are altered, specifically when a div receives the next set of results from a js loaded paginator.
I have this:
<script script type="text/javascript" language="javascript">
document.addEventListener("DOMCharacterDataModified", ssdOnloadEvents, false);
function ssdOnloadEvents (evt) {
var jsInitChecktimer = setInterval (checkForJS_Finish, 111);
function checkForJS_Finish () {
if ( document.querySelector ("#tester")
) {
clearInterval (jsInitChecktimer);
//do the actual work
var reqs = document.getElementById('requests');
var reqVal = reqs.get('value');
var buttons = $$('.clicker');
Array.each(buttons, function(va, index){
alert(va.get('value'));
});
}
}
}
</script>
This works well when the doc loads (as the results take a few seconds to arrive) but I need to narrow this down to the actual div contents, so other changes on the page do not fire the events.
I have tried:
var textNode = document.getElementById("sitepage_content_content");
textNode.addEventListener("DOMCharacterDataModified", function(evt) {
alert("Text changed");
}, false);
But the above does not return anything.
Can what I am trying to do be done in this way? If yes where am I going wrong?
Using Social Engine (Zend) framework with MooTools.
I did this in the end with a little cheat :-(
There is a google map loading on the page that sets markers to match the location of the results. So I added my events to the end this code namely: function setMarker() {}.
I will not mark this as the correct answer as it is not really an answer to my question, but rather a solution to my problem, which is localised to the Social engine framework.
I will add a Social engine tag to my original question in the hope it may help someone else in the future.
Thanks guys.

How to detect completed tweet made using Twitter intents and Javascript

I'm totally new to programming Twitter, so please excuse my ignorance. I've tried to find a solution to this problem, but to no avail..
In HTML I've got this:
<a href='javascript: submit_with_twitter()'>submit</a>
I'm using my own button to trigger the tweet because the button is actually a 'submit and tweet' button, not just a standard 'tweet' button.
in JS:
function submit_with_twitter() {
twttr.events.bind('click', function (event) {
alert("foo");
});
var myURL = encodeURIComponent("http://www.xxx.org.uk/compose-letter");
var my_text = encodeURIComponent("blah blah");
var url = "https://twitter.com/intent/tweet?url=" + myURL + "&text=" + my_text + "&via=xxx";
window.open(url, "Twitter", "status = 1, left = 430, top = 270, height = 550, width = 420, resizable = 0");
}
The twitter pop up window opens and the tweet can be posted successfully. But, 2 problems:
1) the tweet is actually the first stage of the form submit process, so when the tweet has been made JS needs to detect this so it can trigger the form submission
2) the pop up window does not close automatically
If I manually include the twitter JS like so:
<script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
I get this console error when my JS function is called:
Uncaught TypeError: Object function a(e){if(!e)return;var t,r,i,o;n.apply(this,[e]),t=this.params(),r=t.size||this.dataAttr("size"),i=t.showScreenName||this.dataAttr("show-screen-name"),o=t.count||this.dataAttr("count"),this.classAttr.push("twitter...<omitted>...t'
If I don't manually include the twitter JS, the tweet still works but there's no error message and nothing else happens.
I should add that all this is being done in wordpress. I include my own JS file in the WP page editor, as this seems to work best generally, and I have added:
<meta name="twitter:widgets:csp" content="on">
to the page.
------------ EDIT ---------------------
now I've got my JS like this:
jQuery(document).ready(function($) {
// Code here will be executed on document ready. Use $ as normal.
console.log("jQuery(document).ready");
$.getScript('https://platform.twitter.com/widgets.js', function(){
// console.log("twttr: "+twttr);
console.log("twttr object: %o", twttr);
console.log("jQuery object: %o", jQuery);
$(twttr).ready(function (twttr) {
console.log("twttr ready, adding tweet handler");
$(twttr.events).bind('tweet', function () {
console.log("tweeted event!");
});
$(twttr.events).bind('click', function () {
console.log("click event!");
});
$(twttr.events).bind('follow', function () {
console.log("follow event!");
});
});
});
});
which gets rid of all errors, the tweet window now closes itself and all the console logs are seen as expected, except for those which should appear after the tweet is made.
Basically, everything seems fine except that the tweet event is never caught!
Ok,
For future sufferers, I finally figured out that twitter was being set up elsewhere in wordpress, so there was no need to use
$.getScript('https://platform.twitter.com/widgets.js', function(){}
or
<script type="text/javascript" src="https://platform.twitter.com/widgets.js"></script>
or any other attempt to set up twitter widgets.
I haven't looked into which plugin (if any) is causing twitter to be initialised..
Also, if the page does not contain an HTML twitter link, something like this:
<a href='https://twitter.com/intent/tweet' >Tweet Test</a>
twitter is not initialised, so events cannot be detected. So, it's easiest to trigger the tweet normally using the link, then use the captured tweet event to run any subsequent JS, rather than using JS to trigger the tweet

Clicking a link programmatically after using preventDefault()?

I'm trying to change a href link programmatically (according to a result from an ajax async operation) and open it in a new window (I don't want to use window.open as it behaves like a popup and being blocked in IE).
The following code works only after clicking MANUALLY on the link for a second time, how can I make it work on the first click?
Simplified example:
trying to change href link dynamically
<script type="text/javascript">
document.getElementById('link').addEventListener("click", function (e) {
if (!e.target.hasAttribute("target")) //only preventDefault for the first time..
{
e.target.setAttribute("target", "_blank");
e.preventDefault();
updateLink();
}
});
function updateLink() {
// --HERE I PERFORM AN AJAX CALL WHICH TAKES A WHILE AND BY ITS RESULT I DECIDE WHICH URL TO USE - BUT HERE I JUST USE IT HARDCODED--
document.getElementById('link').setAttribute("href", "http://google.com");
document.getElementById('link').click();
}
I organized your code in this jsFiddle: http://jsfiddle.net/mswieboda/Hhj4D/
The JavaScript:
var $link = document.getElementById('link');
$link.addEventListener("click", function (e) {
if (!e.target.hasAttribute("target")) {
//only preventDefault for the first time..
e.target.setAttribute("target", "_blank");
e.preventDefault();
updateLink();
}
});
function updateLink() {
$link.setAttribute("href", "http://google.com");
$link.click();
}
This worked for me when I ran it. Hovering the link, you could see http://demo.com but clicking it takes you to http://google.com. Is this the desired functionality? You can definitely use the updateLink function any time (after an AJAX call) to change the href, also, you could probably set the _target in that function as well, makes more sense to me that way.

jQuery ATTR funk in IE

I am dynamically creating javascript and attaching it to the onclick event of links on my page using $(document).ready()
My onclick javascript is used to generate event functions that I am passing to Google Analytics to track events on my page, such as clicks on banners and downloaded PDFs. I am getting stats in Google Analytics for these events from every browser except for IE. So, something is wrong with my code in IE (I have searched and searched for errors on my page, there are none).
Normally I would just do something like $("a").click ... do stuff ... but for whatever reason, the only way I could get the Google Analytics event tracking to work was by putting the tracking event function directly on my links. So I'm using the following code to inject the tracking event function into my link's onclick once the page loads....
// Tracks favorites on the home page.
$("._gatHomePageFavorites").each
(
function(index)
{
var description = "Content ID: " + getParameterNamedID($(this).attr("href")) + " - " + $(this).children().first().attr("alt");
$(this).attr("onclick","alert('1');_gaq.push(['_trackEvent', 'Favorites - Home Page', 'Icon Click','" + _gatCleanString(description) + "']);alert('2');");
}
);
I think my problem is that IE is not putting my code on the onclick. But I don't know of a good way to view the generated source in IE. I have tried a couple of javascript functions in the address bar to bring up the generated source, assuming they work, then my code is not injecting the tracking event function into my link's onclick for IE. I see the tracking event function in the onclick in Firefox's view generated source.
As another test, you can see I added alerts around my tracking event funciton. In FF both alerts trigger, In IE neither alert triggers.
One more piece of info. My Google Analytics is not recording events for any IE browser. As far as I can tell, my issue is not specific to one version of IE.
How can I tell if my dynamic javascript is getting into the onclick for IE, and then what can I do to get it into the onclick for IE?
UPDATE
To simplify the problem and to focus the direction of the answers, I removed the Google Analytics event function. Now, all I am doing is injecting alert() into the onlick. IE won't even trigger the alert(). I have tried the following...
// Tracks favorites on the home page.
$("._gatHomePageFavorites").each
(
function(index)
{
$(this).attr("onclick","alert('1')");
}
);
and
// Tracks favorites on the home page.
$("._gatHomePageFavorites").each
(
function(index)
{
$(this).attr("onclick","setTimeout(\"alert('1')\", 1000);return false");
}
);
So I'm still leaning towards my javascript is not being injected into the onclick in IE.
What is the most reliable way to view generated source in IE?
If I can confirm that my code is not being injected into the onclick attribute of the link, then I can at least have an answer as to why Google Analytics isn't tracking events for IE. It would be because my injected code does not exist in IE.
You should not be adding the 'onclick' attr, but rather using this using jQuery .click() event.
function(index){
var description = "Content ID: " + getParameterNamedID($(this).attr("href")) + " - " + $(this).children().first().attr("alt");
$(this).click(function() {
alert('1');
_gaq.push(['_trackEvent', 'Favorites - Home Page', 'Icon Click', _gatCleanString(description)]);
alert('2');
});
}
something like above, sorry wrote this quick, so might have a typo.
Slim chance, but if you have any VBScript on your page then you should prepend your onclick string with "javascript:"
You could just use the time-honoured DOM0 onclick property, though there's really no decent reason why jQuery's click() method wouldn't work.
$("._gatHomePageFavorites").each
(
function(index)
{
var $this = $(this);
var description = "Content ID: "
+ getParameterNamedID($this.attr("href")) + " - "
+ $this.children().first().attr("alt");
this.onclick = function() {
alert('1');
_gaq.push(['_trackEvent', 'Favorites - Home Page', 'Icon Click',
_gatCleanString(description)]);
alert('2');
};
}
);
jQuery's attr() method is generally not useful, but that's a whole different rant.
Something to be aware of tracking links is that if the browser leaves the page before the tracking pixel is fetched, the event may not be recorded, depending on the browser, computer, & network speed. I've had good luck with the following (modified from #Tim Down's code):
$("._gatHomePageFavorites").each
(
function(index)
{
var $this = $(this);
var description = "Content ID: "
+ getParameterNamedID($this.attr("href")) + " - "
+ $this.children().first().attr("alt");
$this.click(function(e) {
alert('1');
_gaq.push(['_trackEvent', 'Favorites - Home Page', 'Icon Click',
_gatCleanString(description)]);
if ($this.attr('target') != '_blank') {
e.preventDefault();
setTimeout('document.location = "' + $this.attr('href') + '"', 150);
}
});
}
);
Essentially, if the link isn't opening in a new window, wait and follow it ourselves.
It turns out that my problem had nothing to do with Google Analytics or it's tracking event. After a lot of testing, I finally determined that in IE, jQuery's $().attr() was not working.
The odd thing was that it didn't break or throw an error. IE just ignored it somehow and would not add my dynamic javascript to the onclick parameter of the anchor tag.
Solutions...
The obvious one is to bind to the event like everyone suggested. If you can use $().click() then I agree, use it, always. Never use $().attr("onclick","do something");
However other circumstances in my project prevented me from using $().click(). I was unable to get stats into Google Analytics using it's event tracking function unless the event tracking function was inline on the anchor tag.
Went old school...
$(".obj").each
(
function (index) {
this.setAttribute("onclick", "alert('It is Working');");
}
);
Thanks for everyone's help.

Javascript - add anchor for design reasons

i have a tiny JS problem:
If a user visits a special site http://www.test.de i would like to automatically add an anchor to that url for design reasons -> result http://www.test.de/#welcome.
After 10 seconds i would like to change the anchor to http://www.test.de/#thankyou
Is this possible in some way? Maybe with window.location?
big thx for any help!
You could use window.location.hash here
window.onload = function(){
window.location.hash = 'welcome';
setTimeout( function(){
window.location.hash = 'thankyou';
}, 10*1000);
};
window.onload = function ()
{
window.location.hash = '#welcome';
setTimeout(function ()
{
window.location.hash = '#thankyou';
}, 10*1000);
}
MDC window.onload() docs
MDC window.location.hash docs
The first part of your question - remapping www.test.de to www.test.de/#welcome can be done using URL rewriting. See mod_rewrite for Apache installations or urlrewrite for IIS.net
The second could easily be done using a JavaScript timer and window.location as you have suggested.
<script type="text/javascript">
setTimeout("window.location.href='http://www.test.de/#thankyou'", 10000); // 10 secs
</script>
Although I would question this approach from a user experience perspective. If you are actually referring to specific anchors within the document body, then the user might be dismayed to find his screen jumping to a new part of the page after 10 seconds. If there are no corresponding anchors, then it's just odd (though not necessarily bad).

Categories