infinite scroll + masonry + google analytics

I know it’s been done a million times before, but here it is again:

// Masonry and Infinite Scroll
$(function(){

// define content container
var $container = $('#content');

// apply masonry to loaded elements
$container.imagesLoaded(function(){
  $container.masonry({
    itemSelector: '.post', // your posts
    isAnimated: true
  });
});

// apply infinite scrolling
$container.infinitescroll({
  navSelector  : '#page-nav',    // selector for the paged navigation
  nextSelector : '#page-nav a',  // selector for the NEXT link (to page 2)
  itemSelector : '.post',     // selector for all items you'll retrieve
  extraScrollPx: 0,
  loading: {
      finishedMsg: 'No more items to load.',
      msgText: '',
      img: '.../ajax-loader.gif'
    }
  },
  // trigger Masonry and google analytics in the callback
  function( newElements, opts ) {
    // track google page view
    var page = opts.state.currPage;
    try { ga('send', 'pageview', '/page/'+page); } catch(err) {  }
 
    // masonry elements that have just loaded onto the page
    var $newElems = $( newElements ).css({ opacity: 0 });
    var $newElemsIDs = $newElems.map(function () { return this.id; }).get();
    $newElems.imagesLoaded(function(){
      $newElems.animate({ opacity: 1 });
      $container.masonry( 'appended', $newElems, true );
      // apply code here to do stuff after images loaded
    });
  });
});

Get a xml feed from a WordPress site using jQuery

To get a xml feed from a WordPress site and add it to a bulleted list:

Add this to the body:

    <ul id="posts"></ul>

Add this to the footer of the page:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
    $(function() {
        
		url = 'http://www.endreywalder.com/blog/rss?'+parseInt($.now());
		$.ajax({
			type: "GET",
			url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
			dataType: 'json',
			error: function(){
				alert('Unable to load feed, Incorrect path or invalid feed');
			},
			success: function(xml){
				values = xml.responseData.feed.entries;
				console.log(values);
				$.each( values, function( i, val ) {
				  console.log(i);
				  console.log(val.link);
				  console.log(val.title);
				  $("#posts").append("<li><a href='"+val.link+"'>"+val.title+"</a></li>");
				});
			}
		});
	
    }); 
    </script>

Do someting 30 seconds after page load in Javascript

seconds = 30;

var interval = window.setInterval(function() {
	// do your stuff here
}, 1000);

window.setTimeout(function() {
	window.clearInterval(interval);
}, seconds * 1000);		

Google Analytics Tracking Snippet for External Links using jQuery

// external link tracker using jquery
$("a[rel*='external']").click(function(){
    if (typeof _gaq !== "undefined" && _gaq !== null) {
        _gaq.push(['_trackEvent','/outgoing/'+ $(this).text(),'/outgoing/'+ $(this).attr('href'),'/outgoing/'+ $(this).attr('title')]);
    }
});

AddThis to Shopify Theme with Configuration Variables

Setup a Google Analytics account and record the profile ID.

Setup an AddThis Sharing account, add a new profile and record the profile ID.

Setup a Bitly account, go to Advanced Settings and record your “login” and “API Key”

Add the following configuration settings to your Shopify theme ‘settings/settings_data.json’ file:

{
  "current": {
    ....
    "addthis_profile_id":"PUT YOUR ADDTHIS PROFILE ID HERE",
    "google_profile_id":"PUT YOUR GOOGLE PROFILE ID HERE",
    "enable_bitly":true,
    ....
  }
}

Add the following fields to your Shopify theme ‘settings/settings.html’ file:

<fieldset>
  <legend>Sharing Settings</legend>
  <table>
    <tr>
      <td><label for="addthis_profile_id">Addthis Profle ID</label></td>
      <td><input id="addthis_profile_id" name="addthis_profile_id" class="text" /></td>
    </tr>
    <tr>
      <td><label for="enable_bitly">Enable Bitly URL Shortener for Addthis</label></td>
      <td><input type="checkbox" id="enable_bitly" name="enable_bitly" /></td>
    </tr>
    <tr>
      <td><label for="google_profile_id">Google Profle ID</label></td>
      <td><input id="google_profile_id" name="google_profile_id" class="text" /></td>
    </tr>
  </table>
  
</fieldset>

Add the following at the bottom of your Shopify theme ‘layouts/theme.liquid’ file (before the </body> tag):

NOTE: I set ‘data_track_addressbar’ to ‘false’ because it adds hashed variables to URLs which can screw with someJavascript dependant themes.

{% if settings.addthis_profile_id.size > 0 %}
<!-- AddThis Button  -->
<script type='text/javascript'>
var addthis_product = 'mag-1.0';
{% if settings.enable_bitly %}var addthis_share = { url_transforms : { shorten: { twitter: 'bitly' } }, shorteners : { bitly : {} }  }{% endif %}
var addthis_config = {data_track_addressbar:false{% if settings.google_profile_id.size > 0 %}, data_ga_property:'{{ settings.google_profile_id }}'{% endif %}};
</script>
<script type="text/javascript" src="https://s7.addthis.com/js/300/addthis_widget.js#pubid={{ settings.addthis_profile_id }}"></script>
<!-- AddThis Button  -->
{% endif %}

Then you can simply add the code to any page/liquid template like this:

{% if settings.addthis_profile_id.size > 0 %}
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style addthis_32x32_style">
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_preferred_4"></a>
<a class="addthis_button_compact"></a>
<a class="addthis_counter addthis_bubble_style"></a>
</div>
<!-- AddThis Button END -->
{% endif %}

Then add Facebook open graph tags to your page like this:

NOTE: Save a coming soon image called “my-coming-soon-image.jpg” in your assets for collections that do not have images.

{% if template contains 'product' %}
  <meta property="og:url" content="{{ shop.url }}{{ current_url }}" />
  <meta property="og:title" content="{{ product.title }}" />
  <meta property="og:description" content="{{ product.description | newline_to_br | strip_html | truncatewords: 100, '' | escape  }}" />
  <meta property="og:image" content="{{ product.featured_image | product_img_url: 'medium' }}" />
{% elsif template contains 'article' %}
  <meta property="og:url" content="{{ shop.url }}{{ current_url }}" />
  <meta property="og:title" content="{{ article.title }}" />
  <meta property="og:description" content="{{ article.excerpt_or_content | newline_to_br | strip_html | truncatewords: 100, '' | escape  }}" />
  {% if article.content contains "<img" %}
    {% assign src = article.content | split: 'src="' %}
    {% assign src = src[1] | split: '"' | first | replace: '//cdn', 'http://cdn' | replace: 'http:http://', 'http://' | remove: 'https:'  %}
    {% if src %}<meta property="og:image" content="{{ src }}" />{% endif %}
 {% endif %}
{% elsif template contains 'collection' %}
	{% if collection.all_products_count > 0 %}
            {% if collection.image %}
                {% capture meta_img_src %}{{ collection.image.src | collection_img_url: 'medium' }}{% endcapture %}
            {% else %}
                {% capture meta_img_src %}{{ collection.products.first.featured_image.src | product_img_url: 'medium' }}{% endcapture %}
            {% endif %}
            {% if meta_img_src contains "no-image" %}
                {% capture meta_img_src %}{{ 'my-coming-soon-image.jpg' | asset_url }}{% endcapture %}
            {% endif %}
        {% else %}
            {% capture MybadUrl %}{{ collection.image.src | collection_img_url: 'medium' }}{% endcapture %}
            {% if MybadUrl contains "no-image" %}
                {% capture meta_img_src %}{{ 'my-coming-soon-image.jpg' | asset_url }}{% endcapture %}
            {% else %}
                {% capture meta_img_src %}{{ MybadUrl }}{% endcapture %}
            {% endif %}  
        {% endif %}
      	<meta property="og:title" content="{{ current_title }}" />
  	<meta property="og:image" content="{{ meta_img_src }}" />
  	<meta property="og:url" content="{{ shop.url }}{{ current_url }}" />
{% else %}
  {% if settings.use_logo %}
    <meta property="og:image" content="{{ 'logo.png' | asset_url }}" />
  {% endif %}
{% endif %}

Countdown Magento CMS Page Content Using jQuery and Layout XML

Create a cool page that only shows content after a certain date.

Download this Countdown jQuery Plugin by Keith Wood.

Extract the contents of the ZIP file to your preferred Magento theme JS folder (in my case /js/jquery/jquery.countdown.package-1.6.1/).

Copy the file ‘jquery.countdown.css’ to your skin folder (to take advantage of your CDN settings).

Create a new CMS page and add the title.

In the Content field (hide the WYSIWYG editor) enter:

<script type="text/javascript">
jQuery(function () {
	jQuery("#before").show(); 
	jQuery("#after").hide(); 
	

// set the due date/time
	var eventDate = new Date()
	var eventDate = new Date("January 1, 2014 00:00:00"); 

// load the countdown
	jQuery('#defaultCountdown').countdown({ 
            until: eventDate, 
            timezone: +10,         // set your timezone here (this is AEST)
            onExpiry: liftOff,     // a callback function to call at the due date/time (see below)
            alwaysExpire: true 
        });

// a callback function to call at the due date/time	
	function liftOff() { 
		//console.log('liftOff');
		var template = 'WRITE YOUR HAPPY NEW YEAR CONTENT HERE';
		jQuery("#before").hide(); 
		jQuery("#after").append(template); 
		jQuery("#after").show(); 
	} 
	
// a function to create a link that will help us test it before the due date
	jQuery('#shortlyStart').click(function() { 
		jQuery('#defaultCountdown').countdown('option', { until: -3580 }); 
	}); 	
});
</script>

    <div id="countdownContainer" style="">
        <!-- div to show before due date/time //-->
        <div id="before">
            <p>Counting down to 1 Jan <span id="year">2014</span>, 12:00am AEST.</p>
            <div id="defaultCountdown"></div>
        </div>
        <!-- div to show after and on due date/time //-->
        <div id="after">
            <p>This is it!</p>
        </div>
        <!-- a button to test before date/time... remove for production //-->
        <button type="button" id="shortlyStart">Click here to test before start date</button>        
    </div>

Go to Design Tab > Page Layout > Layout Update XML and enter:

<reference name="head"> 
	<action method="addJs"><script>jquery/jquery.countdown.package-1.6.1/jquery.countdown.min.js</script></action>
	<action method="addCss"><stylesheet>css/countdown.css</stylesheet></action>
</reference>

Center a popup with jQuery, CSS, HTML

A simple horizontally and vertically centered popup. Allows you to create several on one page.

Add this jQuery:

jQuery(".popupopen").click(function() {
  box = jQuery(this).attr('rel);
  jQuery('#'+box).show();
  width = -1 * parseInt((jQuery('#'+box).width()/2));
  height = -1 * parseInt((jQuery('#'+box).height()/2));
  jQuery('#'+box).css('margin-left',width).css('margin-top',height);
  return false;
});
jQuery(".popupclose").click(function() {
  jQuery(this).parent().hide();
  return false;
});

Add this HTML:

<p><a title="Open this popup" href="#" class="popupopen" rel="popup1">open a popup</a></p>
<div class="popup" id="popup1">
  <p>My popup insides</p>
  <a title="Close this popup" href="#" class="popupclose">close</a>
</div>

Add this CSS:

.popup { 
  z-index:999; 
  position:fixed; 
  top:50%; 
  left:50%; 
  width:66%;
  max-width:300px;
  padding:20px; 
  display:none;
  text-align:center;  
}

References: