1

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).

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
John
  • 66
  • 7

2 Answers2

1

I was looking for a solution on this and i guess there are some things we have to consider first to make it work.

1 - We have to make 2 different div containers to load the content. Let's name the first "main-container" and the second "sub-container".

2 - We need two different link classes to point to the different div containers as you already put it. '.go-to-divA' and '.go-to-divB'.

3 - Ajaxify-html5.js is changing the url to the ahref link that is clicked.

Both classes will change the url but will function differently. For example '.go-to-divA' will load a page with the "main-container" containing also the "sub-container" and fadeIn the whole content. Now links inside the "main-container" with class ".go-to-divB" will load content in the "sub-container" fading in and out the div.

So i guess for this solution the structure of the page plays a major role on the way we have to harness the functionality of the script. We have to test this and see how it goes

drivebass
  • 137
  • 1
  • 11
  • We ended up doing pretty much this, yes. In the end it was basically a matter of splitting everything into two pieces. I made two variables for each source and replace zone and made if statements that manage the two cases. – John Sep 18 '13 at 10:15
  • @John Many thanks for the comment! Could it be possible to share a working example, I haven't managed to make it work yet:( – drivebass Sep 19 '13 at 10:03
  • Hey dB-Artwork: I've posted the working example (in use on a very big production site) as an answer to my question. I would have voted your answer up (because it prompted me to come back and post my example) but cannot because I don't have enough reputation points. Hope that helps you to move in the right direction. – John Sep 20 '13 at 04:48
  • @John Excellent! Nevermind the up vote. The working answer matters. I voted:) – drivebass Sep 20 '13 at 08:43
  • @John Would it be possible to share the link for the production site to check as a live example? – drivebass Sep 21 '13 at 07:17
  • To dB-Artwork: Unfortunately I cannot share the production website publicly due to contractual constraints (the response when I asked my employer if it would be possible). We made this site for a very big company. My apologies. – John Sep 21 '13 at 12:39
  • @John Thank you very much for the reply! I understand completely! Thanks again for sharing the code. Cheers! – drivebass Sep 21 '13 at 17:57
1

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('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; ');
          }
          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
John
  • 66
  • 7