How to write a Google Content Experiment that disables a stylesheet? - javascript

I am currently trying to setup a Client Side Experiment without Redirects as opposed to the default Content Experiment A/B testing. All I want to do is for half my visitors disable one of two existing stylesheets on a page.
To me it doesn't make sense to do this the default A/B way because then I would have to setup a second page with the stylesheet disabled for every page on my site.
There is also Running a Server-side Experiment but to me that is too heavy handed for something I think should be somewhat simple.
I have the js all setup, I just need to be able to tell the page that when there is a given variation disable the stylesheet or don't render the stylesheet before the DOM loads.
One thing I considered is, given a certain variation, redirect to the same page but append a url query parameter like &stylesheet_disabled=true then I would simply not render the stylesheet on the server side but when I briefly looked at that I ran into a redirect loop but perhaps someone has a better way to write the js.
Any help greatly appreciated.

You could do something like this:
<head>
...
<script>
if (cxApi.chooseVariation() != 1) { // not in the experiment
document.write('<link href="... />'); // add the stylesheet
}
</script>
...
Only use document.write while the page is still being loaded.
This is all client-side, so no need for redirects and extra server work.

Here is how I did it:
<head>
<script src="//www.google-analytics.com/cx/api.js?experiment=EXPERIMENT_ID"></script>
<script>
// Ask Google Analytics which variation to show the visitor.
var chosenVariation = cxApi.chooseVariation();
function redirectVariation($variation) {
var url = window.location.href;
if ($variation === 1) {
var queryString = document.location.search;
if (queryString.indexOf("stylesheet_disabled=true") == -1) {
if (Boolean(queryString)) {
url += "&stylesheet_disabled=true";
} else {
url += "?stylesheet_disabled=true";
}
window.location.href = url;
}
}
}
redirectVariation(chosenVariation);
</script>
This is only setup for one different variation but could easily be modified for more. Then you just have your application on the server side detect the presence of the querystring parameter and execute whatever logic you like, in my case not displaying a stylesheet.
Theoretically this could be used to do any kind of server side logic with GA Content Experiment Client Side Redirects. Hopefully this helps someone else.

Related

Detect which link was clicked with javascript that got user to specific page

Been searching on the web for a solution, but couldn't find anything, so maybe it's not possible, although I hope it still is.
What Im trying to do is detect the button (class or id) that was clicked when being redirected to another page on my site.
What I have is a portfolio page that contains a large amount of divs with different classes, so when someone clicks on a specific button on the homepage and gets redirected to the portfolio page, is it possible to detect on the portfolio page how the visitor got directed from. So detect which button got clicked.
no idea how to approach this, something maybe with if previous window.location last action find class or id.
Hopefully my question makes sense and someone can give me an idea if even possible.
I imagine it would rather be possible to do with php, but unfortunately server side languages are not an option in this case.
Thanks
Examples of methods you can use
add the information in the originating url - use location.search or location.hash depending on your choice of ? or #
Set a cookie (or use session/localStorage in modern browsers) in originating page and read it in the target page
Interrogate document.referrer (not always set)
You can't do it without either modifying the links (adding a query string or hash), or having code on the source pages (where the links are).
The former is pretty obvious: Just add a query string or hash (I'd use a hash) that identifies where the click came from, and look for the hash on the portfolio page. E.g., links:
Portfolio
Portfolio
and in the portfolio page:
var from = location.hash;
If you don't want to do that, and you can put code on those pages, it's easy: Add a click handler that sets information about the link in sessionStorage (very well-supported on modern browsers), and look for it in sessionStorage when you get to the portfolio page.
E.g.,:
$(document).on("click", "a", function(e) {
// Maybe check the link is going to portfolio, or refine the selector above
sessionStorage.setItem("linkFrom", this.className);
});
and then in the portfolio page:
var from = sessionstorage.getItem("linkFrom");
You can use window.localStorage to save the last id of the clicked element.
localStorage.setItem('last_clicked_id', id);
And then read it in the next page:
localStorage.last_clicked_id
Before running you should check for localStorage support:
if(typeof(Storage) !== "undefined") {
//localStorage code
} else {
//no localStorage support
}
this is how it works: the recent page or url is set on the URL parameters like a GET server request, but instead the client will receive it and parse it not the server. the recent page or url is on the "fromurl" parameter. on every page put this in (it's a javascript code):
function getURIparams(s) {
loc = window.location.href;
loc = loc.substring((loc.indexOf("?")+1));
loc = loc.split("&");
for (l = 0; l < loc.length; l++) {
lcc = loc[l].split("=");
if (lcc[0] == s) {
return lcc[1];
break;
}
}
}
next on every anchor link put this in href:
The Link to another page
after that, on every page execute this javascript:
from_url = getURIparams("fromurl");
the "from_url" variable will be the string variable of where the user clicked before it comes to that page.
if you are to lazy to put all those anchor one by one like this, do this work around but you need jquery for this. you dont need to put the parameter on the links for it to know where it comes from it will be automatically added by jquery.
$(document).on('click', 'a', function(e){
e.preventDefault();
window.location.href = e.target.href + "?fromurl=" + window.location.pathname;
});

Preload page on hover and link on click

I'm playing around with a possibility to preload a page using ajax on hover over a button and have this page available quicker on click on this button. I'm quite at the beginning and can't really find a good solution for this / might be totally wrong. Here is what I have tried, looks like a little promissing for me:
document.getElementById('link').addEventListener('mouseover',function() {
var r = new XMLHttpRequest();
r.open("POST", "index.php", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
document.getElementById('link').addEventListener('click',function() {
window.location.assign('index.php');
});
};
r.send('');
});
But I don't think that does it.
Can someone point me in a direction without sharing code/solutions? I'm mainly interested in how I can achieve this by myself - is ajax the right way to start?
I'm looking for a javascript only solution
You'll need a bit of a framework for subbing out the page content and managing what's in the URL without sending another request to the server and reloading the page.
Push state can help with the URL manipulation.
You would need to replace the body of your page (or less, depending on your markup, maybe just everything inside #container or whatever you have on the page) when you received a partial of HTML from your server via AJAX.
Look into how something like Rails' TurboLinks uses an approach called PJAX to quickly navigate pages. Then the prefetching on hover could be layered on top of an approach like that.
More reading: http://pjax.herokuapp.com/

Add to favorites button for adding favorite html Pages

I am creating a mobile website with different events in a specific month. I want to add a button on every event page let user add different as'favorites'. I want that when user click the Add to favorites button, the event should be automatically added to a html page 'favorites'
I would go with a small javascript, external and called on the event pages (since there will be many instances of it). It's actually a very simple process you're asking about.
Create a new javascript file called favorites.js
Save it with this code:
Modified To support Opera
function bookmark(title,url){
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
url =url+sPage;
if (window.sidebar) // firefox
window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
var elem = document.createElement('a');
elem.setAttribute('href',url);
elem.setAttribute('title',title);
elem.setAttribute('rel','sidebar');
elem.click();
}
else if(document.all)// ie
window.external.AddFavorite(url, title);
}
In the head of every HTML document you write, you need to call this script (extremely similar to calling a CSS definition):
<script src="**/dir/**favorites.js" charset="UTF-8" type="text/javascript" defer/></script>
Defer is optional but recommended with a script like this which is not essential to the functioning of the page. However, if you want the possibility that the user can make use of the add to bookmarks function before the rest of the page loads, you may change defer to async.
Now you're almost there. At this point, to save yourself some frustration, make sure that your pages load without error before trying to use a link. This will ensure there are no bugs with your javascript or existing code.
To make use of the add to favorites button, it's as simple as using anchors and links. A link which would make use of this script in particular looks like this:
bookmark me
or
<img src="imgs/bookmarklogo.png" **other-img-definition-stuff**>
And in the old days it was common to use a form button, like this:
<input type="button" name="Bookmark this page" onclick="bookmark()" />
Several years have gone by since I really bothered myself with HTML/CSS, and in that time, options such as AddThis have come about. If you find this task too difficult, I would just go with something like that. And also I would recommend getting away from handcoding and go to some sort of CMS, like Drupal or Wordpress. Especially if you are on tight schedules.

What to do if $(window).load(function(){}); is too early

I need to trigger a piece of code after every single bits are done downloading. The script works if injected after everything is loaded, but how do I trigger that automaticly?
My script is:
var divId = "jwplayer-0_wrapper";
if ($('#' + divId).length == 1) {
myReg = /https?:\/\/www\.youtube\.com\/watch\?v=[^"]+/;
var plainText = $('#' + divId).parent().children('script').text();
var url = plainText.match(myReg);
if (url !== null) {
window.location = url;
};
};
It is used to skip certain site that decide to use the JW player witch I find horribly buggy. So it looks for a div with the indication of the JW player and if there's one, it finds the link to the original youtube video and directly goes there.
Its triggered By Google Chrome Add-on named Javascript Injector and I apply the script on every page I visit. The plug in work perfectly well on sites like www.ayoye.co and www.veuxturire.com. But on other sites, that uses the same pathern, it seems that the script is triggerd too early. For example there www.mondedestars.com and www.lesautos.ca triggers it too early.
If I use the "inject now" fonction of the Add on after the page is really done loading, then it redirects me to the youtube page as expected. I am lost on the why it works some where and not were else.
I'm not trying to understand every single website here, I'd prefer make it dynamicly triggered after the page has done loading everything from its php, ajax, script, flash, html and CSS.
I've tryed to look to the JWplayer API, but since its terribly unclear to me, over the fact that its partialy in flash, it woudl be simpler if there was a way to trigger it after, or maybe just triggering it after i hover over the body, since every sites has a body. It cant be specific to one page.
Use something like this
var timer;
function injectYouTube() {
// DO YOUR STUFF HERE
// ONCE DONE CALL clearInterval(timer);
clearInterval(timer);
}
timer = setInterval(injectYouTube, 2000);
I am not saying this will be called after everything is loaded but instead you can make sure your code is executed when you want it to.
The JWPlayer API are not that difficult. You can retrive the informations you need even not knowing the container id.
This is an example:
var player = jwplayer(0); // get the first jwplayer element of the page
var video = player.getPlaylistItem(); // get the player video
var url = video.file // retrieve the video url
I think the setTimeout or setInterval are unreliable.
Setting up a listener on jwplayer onReady event would be better.
The pessimistic answer to this is that you can't wait until a page has finished all AJAX operations etc. because web pages can continue loading new content indefinitely if they wish.
What you might consider is running your code every time a new HTML element is added to the page. This way, you can be certain to catch JWPlayer the moment it is inserted into the page.
document.addEventListener("DOMNodeInserted", yourRemovalFunction);

Using Bookmarks with jQuery Address

I am using jQuery's Address plugin (website) to enable the back/forward buttons on my website. I would REALLY like to also have the ability for people to bookmark pages and to copy the address from the address bar and share it with friends.
Address claims it can do this, so then what am I doing wrong.
My code is
function BackButton() {
$.address.change(function(event) {
// do something depending on the event.value property, e.g.
// $('#content').load(event.value + '.xml');
});
$('a').click(function() {
$.address.value($(this).attr('href').replace(/^#/, ''));
});
}
BackButton() is then called on every AJAX pageload to ensure it works with the pages loaded by ajax.
Thanks for your help
looks like you copied directly from the example at the plugin's website. your address.change function does nothing, there are only two commented lines in there.
So I used
if ( $.address.value() !== "\/" ) {
window.location = "http://www.domainname.com/" + $.address.value()
}
to redirect the user to the correct page.
So is this correct? Or are their problems with it?
What would be the benefits of using the $.address.init function of jQuery.Address?
Also this forces them to wait until the page (&javascript) is loaded to see any content. comments?

Categories

Resources