I have wrote the following javascript to detect if the referrer URL matches the URL in my table of products. Then we scrolls down the page to the relevant product. The actual scroll part works correctly the problem is in the if statement.
$("tr td:first").each(function(){
var product_href = $(this).find("td a:eq(0)");
if(product_href.length && document.referrer.indexOf(product_href.attr("href")) == 1){
$(this).scrollTo({
easing: 'easeOutQuad',
offsetTop: -40,
target: $(this)
}).click();
}
});
When I add alert(document.referrer + ' | ' + product_href.attr("href")); above the IF statement I get
http://localhost/product/product-uri | /product/product-uri
Scroll to plugin
$.fn.scrollTo = function(options) {
var defaults = {
target : false,
speed : 400,
easing: 'swing',
offsetTop: -20,
offsetLeft: 0
};
var opts = $.extend({}, defaults, options);
if(this.length > 0){
var elem = this;
// Element instance specific actions
$(elem).each(function() {
var dis = $(this);
var settings = $.meta ? $.extend({}, opts, dis.data()) : opts;
var url = $(dis).attr("href");
var anchor = '';
if(url && url.indexOf("#") != -1 && url.indexOf("#") == 0) {
anchor = $(this.hash);
} else
anchor = $(settings.target);
$(dis).bind('click', function(){
$('html, body').animate({
scrollTop: (anchor.offset().top + parseInt(settings.offsetTop,10)),
scrollLeft: (anchor.offset().left + parseInt(settings.offsetLeft,10))
}, settings.speed, settings.easing);
});
});
}
return this;
};
Try changing:
To:
You want to test that the product exists anywhere in the referrer string, not that the product exists and begins at the second character (0 based indexing) of the referrer string.