Skip to content

Instantly share code, notes, and snippets.

@dewski
Created August 26, 2010 18:12
Show Gist options
  • Select an option

  • Save dewski/551890 to your computer and use it in GitHub Desktop.

Select an option

Save dewski/551890 to your computer and use it in GitHub Desktop.
/**
* jQuery.ScrollTo - Easy element scrolling using jQuery.
* Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Dual licensed under MIT and GPL.
* Date: 5/25/2009
* @author Ariel Flesler
* @version 1.4.2
*
* http://flesler.blogspot.com/2007/10/jqueryscrollto.html
*/
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
jQuery.fn.eachDelay = function(callback, speed){
return jQuery.eachDelay( this, callback, speed)
}
jQuery.extend({
eachDelay: function(object,callback, speed){
var name, i = -1, length = object.length, $div = $('<div>'), id;
if (length === undefined) { //not an array process as object
var arr = [], x = -1;
for (name in object) arr[++x] = name;
id = window.setInterval(function(){
if( ++i === arr.length || callback.call(object[ arr[i] ], arr[i], object[ arr[i] ]) === false)
clearInterval(id);
}, speed);
}
else { //array-compatible element ie. [], jQuery Object
id = window.setInterval(function(){
if (++i === object.length || callback.call(object[i], i, object[i]) === false)
clearInterval(id);
}, speed);
}
return object;
}
});
var Coal = Coal || {};
$(function() {
$("input, textarea, select, button").uniform();
$(".productNav ul.products").each(function() {
if ($(this).parent().hasClass('considered')) {
return;
};
var list = $(this);
var size = 8;
var current_size = 0;
list.children().each(function() {
if (++current_size > size) {
var new_list = $("<ul class=\"col3 products\"></ul>").insertAfter(list);
list = new_list;
current_size = 1;
}
list.append(this);
});
});
if ($('.product .colors').length) {
var activateSizingSkus = function(root) {
var $product = root.closest('.product');
var a = root.find('a');
var selectedImageSelector = a.attr('href');
// hide all others, show selected item
$product.find('.gallery_image').fadeOut();
$product.find(selectedImageSelector).fadeIn();
// remove active class on other colors, then make current active
root.closest('.colors').find('.color').removeClass('active');
root.addClass('active');
var index = root.index();
// copies skuInfo markup to the "Add to shopping bag button";
var skuInfo = root.find('.skuInfo').html();
$product.find('.enlargeImage .embiggen').removeClass('active').eq(index).addClass('active');
$product.find('.buyNow').hide(0, function() {
$(this).show();
$(this).html(skuInfo);
$(this).find('li').eachDelay(function() {
$(this).fadeIn();
}, 200);
});
}
$('.product .colors .color').live('click', function(e) {
e.preventDefault();
activateSizingSkus($(this));
return false;
});
$('.product .colors .color').each(function(index, color) {
if ($(color).index() == 0) {
activateSizingSkus($(color));
};
})
};
$('.productNav .products a').live('click', function(e) {
e.preventDefault();
var slug = $(this).attr('href').split('/').pop();
var top = $('#' + slug).position().top;
var offset = $('.productNav').height();
$('.productNav .products li').removeClass('active');
$(this).parent().addClass('active');
var currentPos = $(window).scrollTop();
var duration = Math.log(Math.abs((top - offset) - currentPos)) * 100;
$(window).scrollTo(top - offset, duration, { axis: 'y'});
});
// this "pins" the cart object to the top of the screen so its always visible
if ($('#cartTracker').length) {
var cartTopOffset = $('header').height() + $('.productNav').height();
function positionCartObject(){
if ($(window).scrollTop() > cartTopOffset) {
var calculatedTopValue = ($(window).scrollTop());
// $("#cartTracker").css({top:calculatedTopValue+"px"});
leftPos = $('#cartTracker').offset().left
$("#cartTracker").css({position: 'fixed', top:"0px", left: leftPos+"px"});
} else {
var calculatedTopValue = cartTopOffset;
// $("#cartTracker").css({top:calculatedTopValue+"px"});
$("#cartTracker").css({position: 'absolute', top:calculatedTopValue+"px", left: '100%'});
};
}
positionCartObject();
$(window)
.scroll(positionCartObject)
.resize(positionCartObject);
};
if ($('.productNav').length) {
var productNavTopOffset = $('header').height() + $('.mainNav').height();
var productScrollTops = new Object();
$('.product').each(function(index, item) {
productScrollTops[$(item).position().top] = $(item).attr('id');
});
console.log(productScrollTops);
function positionProductNavObject(){
if ($(window).scrollTop() <= productNavTopOffset) {
$(".productNav").css({position: 'relative', top:0+"px"});
$('.content').css('marginTop', 0+"px");
} else {
var calculatedTopValue = ($(window).scrollTop()); ;
// $(".productNav").css({width: '960px', position: 'absolute', top:calculatedTopValue+"px"});
$(".productNav").css({width: '960px', position: 'fixed', top:0+"px"});
$('.content').css('marginTop', $('.productNav').height()+"px");
};
}
positionProductNavObject();
$(window)
.scroll(positionProductNavObject)
.resize(positionProductNavObject);
//if we are on a product page, we should start set
// the anchor of the page to where in the category its in
var url = window.location.pathname;
var urlChunks = url.split('/');
//we know we're at a product URL by the scheme /:productId/:productslug
var productSlug = urlChunks.pop();
var productId = urlChunks.pop();
var currentProduct = productSlug;
if ($('#'+productSlug).length) {
var top = $('#'+productSlug).position().top - $('.productNav').height();
$(window).scrollTo(top);
};
};
$('.removeBag, .addBag, .size').live('click', function(e) {
e.preventDefault();
var href = '';
var $link = null;
var sizing = false;
var $buyNow = $(this).closest('.buyNow');
var img = '<img src="/img/addBag.png" />';
if ($(this).hasClass('size')) {
href = $(this).attr('href');
$link = $buyNow.find('.addBag');
sizing = true;
} else {
$link = $(this);
href = $link.attr('href');
}
if (sizing) {
$buyNow.find('ul').fadeOut().remove();
}
$link.html(img+' adding to cart...')
console.log(href);
$.ajax({
type: 'get',
url: href,
dataType: 'json',
success: function(json) {
console.info(json);
$('#cartTracker').find('.cartCount strong').text(json.cartCount);
if (json.status == 'added') {
$link.html(cancelImg(json.item.sku)+'1 '+json.item.title+' '+json.item.color + ' '+json.item.size);
} else {
$link.parent().html(img+' item removed');
}
},
error: function(json) {
$link.html(img+' error: '+json.error);
}
});
return false;
});
var cancelImg = function(sku) {
return '<a class="removeBag" href="/checkout/remove/sku/'+sku+'"><img src="/img/cancelBag.png" /></a> ';
}
if ($('#use_same').length) {
if($('#use_same').is(':checked')) {
$('#shipping_address').hide();
}
$('#use_same').click(function() {
if (!$(this).is(':checked')) {
$('#billing_address input, #billing_address select').each(function(index, item) {
var name = $(item).attr('name');
var value = $(item).val();
if (value != '') {
console.log(value);
var matchingElement = $('#shipping_address').find('input[name="'+name+'"], select[name="'+name+'"]');
console.log(matchingElement);
matchingElement.val(value);
$.uniform.update(matchingElement);
};
});
$('#shipping_address').slideDown();
} else {
$('#shipping_address').slideUp();
}
})
};
// Product Lightbox
$("a.embiggen").fancybox({
'titleShow' : false,
'transitionIn' : 'fade',
'transitionOut' : 'fade',
'autoDimensions' : false,
'width' : 420,
'height' : 'auto',
'padding' : 0
});
// Form Swap Values
$(function() {
swapValues = [];
$("#siteSearch").each(function(i){
swapValues[i] = $(this).val();
$(this).focus(function(){
if ($(this).val() == swapValues[i]) {
$(this).val("");
}
}).blur(function(){
if ($.trim($(this).val()) == "") {
$(this).val(swapValues[i]);
}
});
});
});
});
/**
* Coal.Homepage
*/
Coal.Homepage = {
speed: 3000,
current: null,
slideshow: {
id: null,
speed: 15000
},
init: function () {
$('.carousel li.next a').click(this.nextLinkListener);
$('.carousel li.back a').click(this.backLinkListener);
this.startSlideshow();
this.__adjustBackground(); // Need to resize the initial image
$(window).resize(this.__adjustBackground);
},
startSlideshow: function () {
this.slideshow.id = setInterval(function () {
Coal.Homepage.switchSlides('next');
}, this.slideshow.speed);
},
nextLinkListener: function (e) {
e.preventDefault();
Coal.Homepage.switchSlides('next');
},
backLinkListener: function (e) {
e.preventDefault();
Coal.Homepage.switchSlides('back');
},
/**
* We need to find the next or previous slide, if it's the
* last one, loop all the way back to the next one so it's
* infinite.
*/
findNextSlide: function (direction) {
var total = $('.slide', '.carousel').length,
current = $('.slide:visible', '.carousel'),
selected;
if (direction == 'next') {
selected = (current.next('.slide').length == 0) ? $('.slide:eq(0)', '.carousel') : current.next('.slide');
} else {
selected = (current.prev('.slide').length == 0) ? $('.slide:eq('+ (total-1) +')', '.carousel') : current.prev('.slide');
}
return selected;
},
switchSlides: function (direction) {
var self = this,
el = this.findNextSlide(direction),
nextId = this.current = el.attr('id').substr(6),
text = el.attr('data-subtitle');
/**
* If they are 15 seconds in, we don't want them seeing
* 15 seconds of the slide they are currently viewing.
*/
if (this.slideshow.id !== null) {
clearInterval(this.slideshow.id);
}
$('.slide_bg').css('z-index', '-2').removeClass('active');
var nextSlide = $('#slide_bg_'+ nextId);
nextSlide.addClass('active');
this.__adjustBackground();
// If they support css, let the browser do the animation.
if (this.__supportsCSS3()) {
nextSlide.css({
'z-index': '-1',
'margin-top': '0'
});
} else {
nextSlide.css('z-index', '-1').animate({
'margin-top': '0'
}, this.speed, 'linear', this.__resetBackgrounds);
}
setTimeout(function () {
self.switchSlideText(el, text, direction);
}, this.speed/2);
},
switchSlideText: function (el, text, direction) {
$('.carousel ul .subtitle').fadeOut(function () {
$(this).text(text).fadeIn();
});
$('.slide:visible', '.carousel').fadeOut(function () {
el.fadeIn();
});
},
__resetBackgrounds: function () {
// Starting the new interval after full transition is complete.
Coal.Homepage.startSlideshow();
$('.slide_bg:not(#slide_bg_'+ Coal.Homepage.current +')').css({
'z-index': '-2',
'margin-top': '100%'
});
},
__adjustBackground: function () {
var image = $('img', '.slide_bg.active'),
imgRatio = image.width() / image.height(),
bgWidth = $(window).width(),
bgHeight = bgWidth / imgRatio,
windowHeight = $(window).height();
if(bgHeight < windowHeight) {
bgHeight = windowHeight;
bgWidth = bgHeight * imgRatio;
}
var bgOffsetW = Math.round((bgWidth - windowHeight) / 2);
var bgOffsetH = Math.round((bgHeight - windowHeight) / 2);
image.width(bgWidth).height(bgHeight)
.css({ position: 'relative', top: '-' + bgOffsetH + 'px', left: '0px'});
if(typeof callback === "function") callback();
},
__supportsCSS3: function () {
return ($.browser.webkit && parseFloat($.browser.version) > 400) || ($.browser.mozilla && parseFloat($.browser.version) >= 2);
}
}
/**
* About Page
*/
Coal.About = {
init: function () {
$('.friends_list a').click(this.toggleFriend);
},
toggleFriend: function (e) {
e.preventDefault();
var id = $(this).parents('li').prevAll().size();
// Add active class to the current link, and remove the existing
$('.friends_list .active').removeClass('active');
$(this).addClass('active');
$('.content .friends .active').fadeOut(function () {
$(this).removeClass('active');
$('.friends .friend:eq('+ id +')').fadeIn(function () {
$(this).addClass('active')
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment