Skip to content

Instantly share code, notes, and snippets.

@elzii
Created October 3, 2014 22:48
Show Gist options
  • Save elzii/10337b2eaaaae13870d4 to your computer and use it in GitHub Desktop.
Save elzii/10337b2eaaaae13870d4 to your computer and use it in GitHub Desktop.
if(typeof jQuery == 'undefined') {
console.log('%cERROR', 'color:red', ' - jQuery not found.')
} else {
var App;
!(function ($) {
"use strict";
App = window.APPLICATION = {};
/**
* Config
* Debug toggling, environment, breakpoints, etc.
*/
App.config = {
environment : (window.location.href.match(/(localhost)/g) ? 'development' : 'production' ),
debug: true,
media_queries : {
widescreen : 1280
},
compatibility : {
input_placeholders : true,
chrome_font_fix : false
},
wp : {
theme_dir : 'wp-content/themes/dsdp',
image_path : '/wp-content/themes/dsdp/assets/images'
}
}
/**
* Elements
*/
App.el = {
header : $('#header'),
modal : $('.modal'),
modal_bay : document.getElementById('modal'),
hero : $('#hero'),
nav_icons : $('#nav-icons'),
nav_icons_indicator : $('#nav-icons__indicator'),
map : $('.map'),
forms : {
contact_clean_and_safe : $('#contact--clean_and_safe')
}
};
/**
* onReady (document.onready ONLY)
*/
App.onReady = function() {
App.helpers.preloadImages([
App.config.wp.image_path + "/bg-sidebar__discover.png",
App.config.wp.image_path + "/slides/slide--downtown_overview.jpg",
App.config.wp.image_path + "/slides/slide--build_your_building.jpg",
App.config.wp.image_path + "/slides/slide--neighborhoods.jpg",
App.config.wp.image_path + "/slides/slide--about_us.jpg"
], function() {
// callback
$('body').addClass('show');
});
}
/**
* Initiate Functions (document.onready & pjax:end)
*
*/
App.init = function(){
App.initScripts();
App.compatibilityFixes();
App.helpers.userAgentDetection();
App.events();
App.scroll();
App.modals();
App.animations();
App.animationFrames();
App.konamiCode();
// Site specific
// App.memberFilters();
// App.memberFilter();
App.locationMap();
App.navIconSlider();
};
/**
* Initialize Scripts
*
*/
App.initScripts = function(){
// WOW.js
if ( !window.WOW ) { return false; } else { new WOW().init(); }
}
/**
* Fixes
*
*/
App.compatibilityFixes = function() {
// invisible font fix for chrome
if ( App.config.compatibility.chrome_font_fix ) {
if ( App.helpers.isBrowser().desktop_chrome ) {
var orig_body_offset = $('body').offset();
$('body').offset(orig_body_offset);
}
}
// placeholders for outdated browsers
if ( App.config.compatibility.input_placeholders ) {
App.helpers.inputPlaceholders();
}
};
/**
* Click Event Bindings
*
*/
App.events = function(){
/**
* Nav Icon Indicators
*/
$(document).delegate('#nav-icons li', 'click', function (event) {
var $this = $(this),
index = $this.index() + 1;
$this.siblings().removeClass('active');
$this.addClass('active')
// setNavIndicator(index);
$('#nav-icons__indicator')
.removeClass()
.addClass('nav-icons__indicator--'+index)
});
/**
* Nav Toggle
*/
$(document).delegate('#nav-toggle', 'click', function (event) {
var $this = $(this),
$wrap = $('#wrap'),
$nav = $('#nav'),
$inject_wrap = $('#inject--wrap'),
$inject = $('#inject');
$this.toggleClass('nav-toggle--open');
if (
(window.matchMedia('only screen and (min-width:1280px)').matches) &&
!$('body').hasClass('sidebar-discover--hide')
) {
// widescreen
console.log('matchMedia > 1280px, toggling #nav class');
$nav.toggleClass('nav--open_widescreen');
} else {
// other
console.log('matchMedia < 1280px, toggling #inject class');
$inject_wrap.toggleClass('nav--open');
$inject.toggleClass('nav--open');
$('#nav-toggle__text').toggleClass('nav--open');
}
});
/**
* Close sidebar
*/
$(document).delegate('#sidebar-discover--close', 'click', function (event) {
var $this = $(this),
$body = $('body'),
$nav_toggle = $('#nav-toggle');
$body.addClass('sidebar-discover--hide');
$body.removeClass('sidebar-discover--open');
if ( $nav_toggle.hasClass('nav-toggle--open') ) {
setTimeout(function() {
$nav_toggle.removeClass('nav-toggle--open');
}, 5);
}
});
/**
* Map Overlay ScrollTo
*/
$(document).delegate('.map-area', 'click', function (event) {
var $this = $(this),
target = $($this.data('target'));
console.log(target.offset().top)
App.helpers.animateScroll(target, 350, 'swing', 110);
});
/**
* Contact Clean & Safe
*/
$(document).delegate('#toggle--contact', 'click', function (event) {
var $this = $(this),
target = $('#contact');
target.slideToggle(150);
});
};
/**
* Animations
*
*/
App.animations = function() {
App.el.hero.find('.hero-image').addClass('show');
$('#content').addClass('show');
}
/**
* Scroll
*
* @require `.scroll` class on <a>
*/
App.scroll = function(){
// <a> method manual
$('a.scroll, li.scroll > a').click(function(e){
e.preventDefault();
var $this = $(this),
target_id = $this.attr('href'),
target = $(target_id),
duration = (target.offset().top - $(window).scrollTop());
App.helpers.animateScroll(target, duration, 'swing', 15);
});
};
/**
* Ajax Loader Event Bindings
*
*/
App.loadContentBindings = function() {
$('*[data-load-content]').click(function (event) {
event.preventDefault();
var $this = $(this),
url = $this.attr('href'),
selector = $this.data('load-content-selector'),
target = $this.data('load-content-target');
console.log(url, selector, target);
App.loadContent(url, selector, target);
})
}
/**
* Ajax Loader
*
*/
App.loadContent = function(url, selector, target, callback) {
var request = $.ajax({
url: url,
type: 'POST',
dataType: 'html'
})
.done(function (data) {
if ( App.config.debug ) { console.log("loadContent -> SUCCESS"); }
if ( data ) { var html = $(data); }
$(target).html(html.filter(selector));
if ( callback !== undefined ) { callback(html); }
})
.fail(function (data) {
if ( App.config.debug ) { console.log("error", data); }
})
// return request;
}
/**
* Modals
*
*/
App.modals = function() {
var modals = App.el.modal,
modal_bay = App.el.modal_bay,
modal_trigger = $('.modal-trigger'),
modal_close = $('.modal-close');
// move all modals to modal bay
if ( modals )
modals.appendTo(modal_bay);
// attach modal trigger click handler
modal_trigger.click(function (event) {
event.preventDefault();
var $this = $(this),
modal_target = $($this.attr('href'));
showModal(modal_target);
});
function showModal(target) {
// modal overlay
modal_bay.addClass('show');
// show the modal
target.addClass('show');
// close via close button
modal_close.click(function() {
target.removeClass('show');
modal_bay.removeClass('show');
});
// close via esc key
$(window).on('keydown', function (event) {
if ( event.keyCode == 27) {
target.removeClass('show');
modal_bay.removeClass('show');
}
});
}
}
/**
* locationMap
*/
App.locationMap = function() {
var map = $('.map');
if ( map.length > 0 ) {
map.clone().appendTo('#content').addClass('clone').attr('id', '#map--clone');
}
}
/**
* navIconSlider
*/
App.navIconSlider = function() {
var $control_nav = $('#nav-icons--slider_control'),
$slides = $('#nav-icons--slides'),
$slide = $slides.find('li');
// show first slide
$slide.eq(0).fadeIn();
$control_nav.find('li').click(function (event) {
event.preventDefault();
var $this = $(this),
index = $this.index(),
$target = $slide.eq(index);
$slide.fadeOut(250, function() {
setTimeout(function() {
$target.fadeIn(250);
}, 300)
})
})
}
/**
* animationFrames
*/
App.animationFrames = function(){
// var heights = [];
var scroll = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
// IE Fallback, you can even fallback to onscroll
function(callback){ window.setTimeout(callback, 1000/60) };
var lastPosition = -1;
function animationLoop(){
// Avoid calculations if not needed
if (lastPosition == window.pageYOffset) {
scroll(animationLoop);
return false;
} else lastPosition = window.pageYOffset;
// Debugging
// if ( App.config.debug ) { console.log('pageYOffset', window.pageYOffset); }
// Calculations
animateHeaderOpacity();
animateMapToFixed();
scroll( animationLoop );
}
/**
* animateHeaderOpacity
*/
function animateHeaderOpacity() {
if ( window.pageYOffset > ( $('#hero').height() - 110 ) )
App.el.header.addClass('opaque')
if ( window.pageYOffset < ( $('#hero').height() - 110 ) )
App.el.header.removeClass('opaque')
}
/**
* animateMapToFixed
*/
function animateMapToFixed() {
if ( $('.map').length <= 0 ) { return; }
var breakpoint = $('.map-wrap').offset().top + $('.map-wrap').height() - 110 ;
if ( window.pageYOffset > breakpoint ) {
$('.map.clone').addClass('show');
}
if ( window.pageYOffset < breakpoint ) {
$('.map.clone').removeClass('show');
}
}
// init loop
animationLoop();
};
// App.memberFilter = function() {
// var $member_filters = {
// industry : $('#member_filter_industry'),
// type : $('#member_filter_type')
// }
// $member_filters.industry.change(function (event) {
// $('#form-member_filter_industry').submit();
// });
// }
/**
* Member Filters
*/
App.memberFilters = function() {
var $member_filters = {
industry : $('#member_filter_industry'),
type : $('#member_filter_type')
}
$member_filters.industry.change(function (event) {
event.preventDefault();
var industry_name = $(this).val();
populateMemberTiles('member_industry', industry_name, function (data) {
console.log(data);
})
});
function populateMemberTiles(key, value, callback) {
$.ajax({
url: DSDP_vars.ajaxurl,
type: 'POST',
data: {
action: 'DSDP_ajax_members_filter',
key : key,
industry : value
}
})
.done(function (response) {
// console.log("success", response);
var json = $.parseJSON(response);
callback(response);
})
.fail(function (data) {
// console.log("error", data);
callback(response);
})
}
}
/**
* Konami Code
*
*/
App.konamiCode = function() {
var secret = '38403840373937396665',
input = '',
timer;
$(document).keyup(function (e) {
input += e.which;
clearTimeout(timer);
timer = setTimeout(function() {
input = '';
}, 500);
if( input == secret ) {
// do stuff here
if ( App.config.debug ) { console.log('konami code fired!'); }
}
})
}
/**
* DOCUMENT READY
*
*/
$(document).ready(function(){
App.onReady();
App.init();
$('a.pjax-controller').pjax('#inject', {
fragment: '#inject',
duration: 150
})
});
/**
* PJAX
*/
var heroImageClone;
$('#inject')
.on('pjax:beforeSend', function() {
if ( App.config.debug) { console.log('pjax:beforeSend'); }
var $this = $(this)
var hero_image = $this.find('.hero-image');
var content = $this.find('#content');
content.removeClass('show')
// clone the hero
heroImageClone = hero_image
})
.on('pjax:start', function() {
if ( App.config.debug) { console.log('pjax:start'); }
var $this = $(this)
var hero_image = $this.data('hero-image');
// clean up hero clones
$this.find('.hero-image-clone').remove();
})
.on('pjax:waiting', function() {
if ( App.config.debug) { console.log('pjax:waiting'); }
var $this = $(this);
})
.on('pjax:end', function() {
if ( App.config.debug) { console.log('pjax:end'); }
var $this = $(this);
var hero_image = $this.find('.hero-image');
var content = $this.find('#content');
// add classes / show
hero_image.addClass('crossfade')
content.addClass('show')
heroImageClone.addClass('hero-image-clone');
$this.find('#hero').children().last().before(heroImageClone);
// rebind
$('a.pjax-controller').pjax('#inject', {
fragment: '#inject',
duration: 150
})
// @TODO investigate why rebinding event breaks menu on pjax end
// App.init();
})
/**
* WINDOW LOAD
*
*/
$(window).load(function(){
});
/**
* WINDOW SCROLL
*
*/
$(window).on('scroll', function(){
});
/**
* WINDOW RESIZE
*
*/
$(window).resize(function(){
var ww = $(window).width(),
$body = $('body');
if ( (ww > 1279 ) && !$body.hasClass('sidebar-discover--hide') ) {
$('body').addClass('sidebar-discover--open');
} else {
$('body').removeClass('sidebar-discover--open');
}
}).trigger('resize');
var mq_widescreen = window.matchMedia('only screen and (min-width:1280px)');
mq_widescreen.addListener(function (mql) {
});
/**
* ORIENTATION CHANGE (requires jQuery mobile)
*
*/
window.addEventListener("orientationchange", function() {
}, false);
/**
* SELF INVOKING ANONYMOUS FUNCTION(s)
*
*/
(function(){
})();
/**
* Helpers
* Various helper functions for user agent detection and cross browser compatibility
*/
App.helpers = {
/**
* isUserAgent
* Determine the user agent via regex matching the string
* @return {Boolean}
*/
isUserAgent : function() {
return {
iOS : (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false),
iphone : (navigator.userAgent.match(/(iPhone|iPod)/g) ? true : false),
ipad : (navigator.userAgent.match(/(iPad)/g) ? true : false),
android : (navigator.userAgent.match(/(Android)/g) ? true : false),
mobile : ((/Mobile|iPhone|iPod|BlackBerry|Windows Phone/i).test(navigator.userAgent || navigator.vendor || window.opera) ? true : false),
mobile_all : ((/Mobile|Android|iPhone|iPod|BlackBerry|Windows Phone/i).test(navigator.userAgent || navigator.vendor || window.opera) ? true : false)
}
},
/**
* userAgentDetection
* Perform actions if the user agent is a mobile device
*/
userAgentDetection: function(){
if ( App.helpers.isUserAgent().mobile ) {
$('body').addClass('is_mobile');
} else {
$('body').addClass('non_mobile');
}
},
/**
* isBrowser
* Determine the browser based on regex matching the navigator
* @return {Boolean}
*/
isBrowser: function() {
return {
desktop_chrome : (window.chrome ? true : false),
iphone_chrome : ((navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/) && navigator.userAgent.match('CriOS')) ? true : false),
iphone_safari : ((navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/) && !navigator.userAgent.match('CriOS')) ? true : false),
android_native : (navigator.userAgent.indexOf('Android') > -1 && navigator.userAgent.indexOf('Mozilla/5.0') > -1 && navigator.userAgent.indexOf('AppleWebKit') > -1 && navigator.userAgent.indexOf('Chrome') <= -1),
android_chrome : (navigator.userAgent.indexOf('Android') > -1 && navigator.userAgent.indexOf('Mozilla/5.0') > -1 && navigator.userAgent.indexOf('AppleWebKit') > -1 && navigator.userAgent.indexOf('Chrome') > -1),
android_samsung : (navigator.userAgent.indexOf('Android') > -1 && navigator.userAgent.indexOf('Mozilla/5.0') > -1 && navigator.userAgent.indexOf('AppleWebKit') > -1 && navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('SCH') > -1)
}
},
/**
* onLocationHash
* Run a callback function when a string is the location hash
* @param {String} hash_string
* @param {Function} callback
*/
onLocationHash: function(hash_string, callback) {
if( window.location.hash ) {
var hash = window.location.hash.substring(1);
if ( hash === hash_string ) {
callback();
}
} else {
return false;
}
},
/**
* preloadImages
* Preload images by passing in array of url strings
* @param {Array} array
*/
preloadImages: function(array, callback) {
var promises = [];
for ( var i = 0; i < array.length; i++ ) {
(function (url, promise) {
var img = new Image();
img.onload = function() {
promise.resolve();
};
img.src = url;
console.log('%cPreloaded', 'color:#4f89d1;', url);
})(array[i], promises[i] = $.Deferred());
}
$.when.apply($, promises).done(function() {
callback();
});
},
/**
* inputPlaceholders
* Faux placeholders for old browsers
* @required Modernizr library
*/
inputPlaceholders: function() {
if( !Modernizr.input.placeholder) {
$('[placeholder]').focus(function() {
var input = $(this);
if ( input.val() == input.attr('placeholder') ) {
input.val('')
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if ( input.val() == '' || input.val() == input.attr('placeholder') ) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}
},
/**
* openSharePane
* Open a small popup, used for social share windows
* @param {String} url
*/
openSharePane: function(url) {
window.open( url, "socialShareWindow", "status = 1, height = 500, width = 650, resizable = 0" );
},
/**
* renderHTMLPartial
* Render an HTML partial to a page (hacky, work-in-progress, do-not-ever-use-in-production)
* @param {String} file_path
*/
renderHTMLPartial: function(file_path, target_id) {
$.ajax({
url: file_path,
dataType: 'html'
})
.done(function (data) {
console.log('%cIncluding partial', 'color:red', file_path);
var html = data.split("\n").join("");
document.getElementById(target_id).innerHTML = html;
})
},
/**
* animateScroll
* Scroll the window to the target element
* @param {String} target
* @param {Integer} duration
* @param {Sting} easing
* @param {Integer} offset
*/
animateScroll: function(target, duration, easing, offset) {
if ( duration === 'auto' ) {
duration = ((target.offset().top - $(window).scrollTop()) / 3.3 )
}
if( target ) {
if(/(iPhone|iPod)\sOS\s6/.test(navigator.userAgent)){
$('html, body').animate({
scrollTop: target.offset().top
}, duration, easing);
} else {
$('html, body').animate({
scrollTop: target.offset().top - (offset)
}, duration, easing);
}
}
},
testFunc: function() {
console.log(this);
}
}
/**
* Animate Scroll
*/
})(jQuery);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment