ajaxify-html5.js by balupton : https://github.com/browserstate/ajaxify
I need to modify this great script to fulfill the following scenario :
Some links on my page need to load content into one div and then scroll to it, other links on my page need to load content into another div and then scroll to it.
The ajaxify-html5 script already has the ability to block out links with a certain class. If I could harness that functionality and split it in two, I'd be all set to go (ie. I would put class .go-to-divA for some links and .go-to-divB for others).
Here's how I ended up doing it. There's a bit of extra stuff you can ignore.
// History.js It!
// v1.0.1 - 30 September, 2012
// https://gist.github.com/854622
(function(window,undefined){
// Prepare our Variables
var
History = window.History,
$ = window.jQuery,
document = window.document;
// Check to see if History.js is enabled for our Browser
if ( !History.enabled ) {
return false;
}
if ($.browser.msie && parseInt($.browser.version, 10) > 9) {
return false;
}
// Wait for Document
$(function(){
// Prepare Variables
var
/* Application Specific Variables */
contentSelector = '#contenucoeur',
replaceZoneActus = '.emplacementactu',
scrollZoneActus = '#topemplacementactu',
replaceZoneArticles = '.emplacementarticle',
scrollZoneArticles = '#topemplacementarticle',
$contentActus = $(replaceZoneActus),
$contentArticles = $(replaceZoneArticles),
contentNodeActus = $contentActus.get(0),
contentNodeArticles = $contentArticles.get(0),
$blocArticle = $('.blocArticle'),
$menu = $('.articualites'),
activeClass = 'articleactive',
activeSelector = '.articleaactive',
menuChildrenSelector = '> article',
completedEventName = 'statechangecomplete',
/* Application Generic Variables */
$window = $(window),
$body = $(document.body),
testurl = History.getHash(),
rootUrl = History.getRootUrl();
console.log( History, testurl );
// Ensure Content
if ( $contentActus.length === 0 || $contentArticles.length === 0 ) {
$content = $body;
}
// Internal Helper
$.expr[':'].internal = function(obj, index, meta, stack){
// Prepare
var
$this = $(obj),
url = $this.attr('href')||'',
isInternalLink;
// Check link
isInternalLink = url.substring(0,rootUrl.length) === rootUrl || url.indexOf(':') === -1;
// Ignore or Keep
return isInternalLink;
};
// HTML Helper
var documentHtml = function(html){
// Prepare
var result = String(html)
.replace(/<\!DOCTYPE[^>]*>/i, '')
.replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
.replace(/<\/(html|head|body|title|meta|script)\>/gi,'</div>');
// Return
return result;
};
// Ajaxify Helper
$.fn.ajaxify = function(){
// Prepare
var $this = $(this);
// Ajaxify
$this.find('#columns a:not(.btPrint, .linkMore, .linkScroll, .backtopPag, .linkRssActu a, .fluxrsspresse a, .wrapFiltreFAQ a, .page-sitemap .inside a, .titleSearchResult a, .itemWaypoint, .profilLink a, .field-liens-internes a, #ctaDiscover, .downloadMedia a, .homeLink, .wrapFormulaire a, .noAjax, .wrapperArticle a, a[href$=".pdf"], a[href|="http"], a[rel="external"], .wrapError a, .popin a )').live('click', function(event){
event.preventDefault();
// Prepare
var $this = $(this),
url = $this.attr('href'),
title = $this.attr('title')||null;
// variable de la pagination =< cas des précédent - suivant
pagin = $this.hasClass('linkPag');
// variable d'empalcement cible de chargement
emplacement = $this.attr('data-emplacement');
if( $this.is('.accordilink, .sliderlink, .lienFamille, .closeArticle') ) {
var idSlider = parseInt( $this.attr('data-slider'), 10 ),
idAccordeon = parseInt( $this.attr('data-accordeon'), 10 ),
idBrand = $this.attr('data-category');
if( $this.is('.closeArticle') ){
$this.parents('.block-content').fadeOut(700, function(){
$this.empty();
});
if( /homeactus|intranav_homeactus/.test(emplacement) ) {
if( $('html').attr('lang') == 'fr' ) {
url = '/';
} else {
url = '/en';
}
title = 'kendrick ';
setTimeout(function(){jQuery.scrollTo('#mini-panel-blue_bar', 800, {'axis':'y'});}, 300);
$blocArticle.removeClass('active');
} else
if( /articles|intranav_articles|intranav_brands/.test(emplacement) ) {
setTimeout(function(){jQuery.scrollTo('.titlePage', 800, {'axis':'y'});}, 300);
$blocArticle.removeClass('active');
} else
if( /actualites|intranav_actualites/.test(emplacement) ) {
setTimeout(function(){jQuery.scrollTo('.panelsRegion-kendrick_basic-actualit__s-inside', 800, {'axis':'y'});}, 300);
$blocArticle.removeClass('active');
}
} else if( $this.is('.accordilink') ){
jQuery('.view-rubrique-slider .view-content').accordion('activate', jQuery('#' + idAccordeon + 'rubriqueaccordion').prevAll().length);
setTimeout(function(){jQuery.scrollTo('#' + idAccordeon + 'rubriqueaccordion', 800, {'axis':'y'});}, 300);
} else if( $this.is('.lienFamille') ){
jQuery('.view-marque-accordion .view-content').accordion('activate', jQuery('#' + idBrand).prevAll().length );
setTimeout(function(){jQuery.scrollTo('#' + idBrand, 800, {'axis':'y'});}, 300);
} else if( $this.is('.sliderlink') ){
if ($('#views_slideshow_cycle_main_rubrique_slider-mainslider').length) {
$('#views_slideshow_pager_field_item_bottom_rubrique_slider-mainslider_' + idSlider + '').trigger('click');
//Drupal.viewsSlideshow.action({ "action": 'goToSlide', "slideshowID": 'rubrique_slider-mainslider', "slideNum": idSlider });
}
}
} else {
/* état actif */
if (!pagin) {
$('.blocArticle', $('.view-articles')).removeClass('active');
$this.parents('figure').addClass('active');
} else {
dirNext = $this.hasClass('nextActu');
}
}
History.pushState(null,title,url);
// Continue as normal for cmd clicks etc
if ( event.which == 2 || event.metaKey ) { return true; }
// Ajaxify this link
return false;
});
// Chain
return $this;
};
// Ajaxify our Internal Links
$body.ajaxify();
// Hook into State Changes
$window.bind('statechange',function(){
// Prepare Variables
var
State = History.getState(),
url = State.url,
url_split = State.url.split('/'),
relativeUrl = url.replace(rootUrl,'');
if( url_split.length > 4 ){
var urlPop = url_split.pop()[0].substring(0, 1);
}
// Ajax Request the Traditional Page
$.ajax({
beforeSend: function() {
// Start Fade Out
// Animating to opacity to 0 still keeps the element's height intact
// Which prevents that annoying pop bang issue when loading in new content
// Call emplacement specific actions
// and only if new content was request
if( urlPop == '_' ){
// optimisation http://www.onextrapixel.com/2013/02/21/improve-your-code-with-smart-javascript-techniques-and-patterns/
if( /articles|intranav_articles|intranav_brands/.test(emplacement) ) {
//On crée juste la div pour le loader
$('<div />', {'id':'loader', 'height':'24px'}).prependTo(scrollZoneArticles);
$contentArticles.animate({
opacity: 0
}, 800);
$.scrollTo(scrollZoneArticles, 800, {'axis':'y'});
} else if( /actualites|homeactus|intranav_actualites|intranav_homeactus/.test(emplacement) ) {
//On crée juste la div pour le loader
$('<div />', {'id':'loader', 'height':'24px'}).prependTo(scrollZoneActus);
$contentActus.animate({
opacity: 0
}, 800);
$.scrollTo(scrollZoneActus, 800, {'axis':'y'});
}
} else {
$('#topemplacementactu, #topemplacementarticle').find('.view-content').empty();
$blocArticle.removeClass('active');
return false;
}
},
url: url,
success: function(data, textStatus, jqXHR){
// Prepare
var
$data = $(documentHtml(data)),
$dataTitle = $data.find('.document-title'),
$dataBody = $data.find('.document-body:first'),
$dataContent = $dataBody.find(contentSelector).filter(':first'),
$menuChildren,
contentHtml = $dataContent.html()||$data.html(),
$scripts;
// Fetch the scripts
$scripts = $dataContent.find('.document-script');
if ( $scripts.length ) {
$scripts.detach();
}
// Fetch the content
// contentHtml = $dataContent.html()||$data.html();
// if contentHtml is null-vide
if ( !contentHtml ) {
//document.location.href = url;
return false;
}
function animateLoad(el, elScroll) {
if (!pagin) {
el.html(contentHtml).css('opacity', 100);
} else {
// if (dirNext) {
// var marginLeft = $VAR.widthWindow;
// } else {
// var marginLeft = -$VAR.widthWindow;
// }
var marginLeft = -$VAR.widthWindow;
el.html(contentHtml).css({
'opacity': 100,
'margin-left': marginLeft,
'width': ($VAR.widthWindow > 1280) ? '1280' : $VAR.widthWindow
}).animate({
'margin-left': 0
}, 500, function(){
$(this).css('width', 'auto');
});
}
el.find('.closeArticle').attr('data-emplacement', emplacement).attr('data-accordeon');
$.scrollTo(elScroll, 800, {'axis':'y'});
}
// Update the content if needed
if( /articles|intranav_articles|intranav_brands/.test(emplacement) ) {
animateLoad($contentArticles, scrollZoneArticles);
} else
if( /actualites|homeactus|intranav_actualites|intranav_homeactus/.test(emplacement) ) {
animateLoad($contentActus, scrollZoneActus);
}
if( $('.innerDiapo').length ){
setTimeout(initDiapo, 1000);
}
if( $('#map').length ){
setTimeout(imageMap, 1000);
}
// Update the title
document.title = $dataTitle.text();
try {
document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<','<').replace('>','>').replace(' & ',' & ');
}
catch ( Exception ) { }
// Add the scripts
$scripts.each(function(){
var $script = $(this), scriptText = $script.text(), scriptNode = document.createElement('script');
scriptNode.appendChild(document.createTextNode(scriptText));
contentNode.appendChild(scriptNode);
});
// We clear out the loader zone
$('#loader').remove();
$window.trigger(completedEventName);
// Inform Google Analytics of the change
if ( typeof window._gaq !== 'undefined' ) {
window._gaq.push(['_trackPageview', relativeUrl]);
}
// Inform ReInvigorate of a state change
if ( typeof window.reinvigorate !== 'undefined' && typeof window.reinvigorate.ajax_track !== 'undefined' ) {
reinvigorate.ajax_track(url);
// ^ we use the full url here as that is what reinvigorate supports
}
},
error: function(jqXHR, textStatus, errorThrown){
document.location.href = url;
return false;
}
}); // end ajax
}); // end onStateChange
}); // end onDomLoad
})(window); // end closure