Conditional click events on a Youtube Video (check state if playing or stopped)

I wanted to create on click events:

  • When the video playing send user to another page
  • When the video is stopped, re-start the video

Requried javascript API:

<script src="https://www.youtube.com/iframe_api"></script>

HTML mark-up

<div class="herovideo"> <!-- this is the wrapper //-->
  <div class="herovideo-clicker"></div> <!-- this is the clicker //-->
  <div class="video-wrapper"> <!-- this is a responsive wrapper //-->
    <div id="video-placeholder"></div> <!-- this gets replaced with iframe //-->
  </div>
</div>

CSS:

<style>
	.video-wrapper {   }
	.herovideo { position:relative;  }
	.herovideo-clicker { z-index:99; position:absolute; width: 100%; height: 100%; cursor:pointer;}
	.herovideo .video-wrapper { position:relative; z-index:9; }
</style>

Javascript that will:

  • Initialise the player and define it’s appearance
  • Do the responsive resizing
  • On stae change, set the click event
<script>

var player;
function onYouTubeIframeAPIReady() {
	player = new YT.Player('video-placeholder', {
		width: 1280,
		height: 720,
		videoId: 'Write your Youtube Video ID here',
		playerVars: {
			modestbranding: 1,
			autoplay: 1,
			controls: 0,
			enablejsapi: 1,
			fs: 0,
			rel: 0,
			showinfo: 0,
			color: 'white'
		},
		events: {
			onReady: initialize,
			onStateChange: onytplayerStateChange
		}
	});
}

function initialize(){

	var $allVideos = $("iframe[src*='//player.vimeo.com'], iframe[src*='//www.youtube.com'], object, embed"),
		$fluidEl = $(".video-wrapper");

	$allVideos.each(function() {
	  $(this)
	  .attr('data-aspectRatio', this.height / this.width)
	  .removeAttr('height')
	  .removeAttr('width');
	});

	var newWidth = $fluidEl.width();
	  $allVideos.each(function() {
		var $el = $(this);
		$el
		.width(newWidth)
		.height(newWidth * $el.attr('data-aspectRatio'));
	  });

}
  
function onytplayerStateChange(newState) {

  if(newState.data == 1) {
	 // take the user to a new page while the video is playing
	 $( ".herovideo-clicker").unbind( "click" );
	 $('.herovideo-clicker').on('click', function(){
		window.location.href = 'write your URL here'; 
		return false;
	 });
  } else  {
	// restart the video if it is not playing
	$( ".herovideo-clicker").unbind( "click" );
	$('.herovideo-clicker').on('click', function(){
		player.playVideo();
		return false;
	});
  }
}

</script>

References:

  • https://github.com/chriscoyier/Fluid-Width-Video
  • https://developers.google.com/youtube/iframe_api_reference

Custom Addthis Social Media Sharing Buttons for Shopify (for free)

The process is:

  1. Create a Google Analtyics account and get your site ID
  2. Sign-up to Addthis and get your profile ID
  3. Sign-up to Bitly for URL shortening on Tweets (and get your API username and key)
  4. Add the Shopify Theme settings to your settings_schema.js
  5. Add the javascript to your Shopify theme layout file
  6. Add HTML for sharing buttons to your Shopify pages
  7. Add custom icon font and CSS to style your buttons
  8. Configure the Addthis Custom HTML Email Template
  9. Create a Facebook App and add the id to the settings

Addthis theme settings

Add this code to your Shopify settings_schema.json then click on “customise theme” to enter the right values.

  {
    "name": "Addthis Sharing Settings",
    "settings": [
      {
        "type": "checkbox",
        "id": "addthis_use",
        "label": "Use Addthis?"
      },
      {
        "type": "text",
        "id": "addthis_id",
        "label": "AddThis ID"
      },
      {
        "type": "text",
        "id": "google_analytics_id",
        "label": "Google Analytics ID"
      },
      {
        "type": "text",
        "id": "addthis_twitter_id",
        "label": "Twitter name"
      },
      {
        "type": "text",
        "id": "addthis_twitter_string",
        "label": "Twitter string",
        "default": "*title* Coming Soon. #signup #exclusiveaccess"
      },
      {
        "type": "checkbox",
        "id": "addthis_bitly_use",
        "label": "Use Bitly?"
      },
      {
        "type": "checkbox",
        "id": "addthis_email_template_use",
        "label": "Use custom email template?"
      },
      {
        "type": "text",
        "id": "addthis_email_template_name",
        "label": "Add this email template name",
        "default": "product_template"
      },
      {
        "type": "text",
        "id": "addthis_facebook_app_id",
        "label": "Facebook App ID"
      },
      {
        "type": "text",
        "id": "addthis_facebook_redirect_url",
        "label": "Facebook Redirect URL"
      }
    ]
  }

Addthis Javascript

Create a new snippet called “addthis.liquid” and add it to the end of your theme (before end of body tags) using {% include ‘addthis’ %}

{% if settings.addthis_use %}
<script>
  jQuery(function($) {
    initAddThis();
    jQuery('.sharenulify').on('click', function (e) {
      return false;
    });
  });
  function initAddThis() 
  {
    if ( typeof( window[ 'addthis' ] ) != "undefined" ) {
      addthis.init()
    } 
  }
</script> 

{% capture addthis_title %}{% endcapture %}
{% capture addthis_description %}{% endcapture %}
{% capture addthis_image %}{% endcapture %}
{% if template contains 'product' %}
  {% capture addthis_title %}{{ product.title | strip_html | escape }}{% endcapture %}
  {% capture addthis_description %}{{ product.description | strip_html | strip_newlines | truncatewords: 30, '' | escape }}{% endcapture %}
  {% capture addthis_image %}https:{{ product.featured_image | img_url: 'large' }}{% endcapture %}
{% elsif template contains 'article' %}
  {% capture addthis_title %}{{ article.title | strip_html | escape }}{% endcapture %}
  {% capture addthis_description %}{{ article.excerpt_or_content | strip_html | strip_newlines | truncatewords: 30, '' | escape }}{% endcapture %}
  {% if article.image %}
    {% capture addthis_image %}https:{{ article.image.src | img_url: 'large' }}{% endcapture %}
  {% endif %}
{% elsif template contains 'page' %}
  {% capture addthis_title %}{{ page.title | strip_html | escape }}{% endcapture %}
  {% capture addthis_description %}{{ page.content | strip_html | strip_newlines | truncatewords: 30, '' | escape }}{% endcapture %}
  {% assign img_tag = '<' | append: 'img' %}
  {% if page.content contains img_tag %}
    {% assign src = page.content | split: 'src="' %}
    {% assign src = src[1] | split: '"' | first | remove: 'https:' | remove: 'http:' | replace: '_small.', '_large.' %}
    {% capture addthis_image %}https:{{ src }}{% endcapture %}
  {% endif %}
{% else %}
  {% capture addthis_title %}{{ page_title | escape }}{% endcapture %}
  {% if page_description %}{% capture addthis_description %}{{ page_description | escape }}{% endcapture %}{% endif %}
{% endif %}

{% capture addthis_twitter_string_calculated %}{{ settings.addthis_twitter_string | replace: '*title*', addthis_title }}{% endcapture %}  
<script type="text/javascript">
  var addthis_config = {
    {% if settings.google_analytics_id.size > 0 %}
    data_ga_property: '{{ settings.google_analytics_id }}',
    data_ga_social : true,
    {% endif %}
    "data_track_addressbar":false,
    ui_use_css : true,
    image_include: "at_include",
    image_exclude: "at_exclude"
  };
  addthis_share = {
    {% if settings.addthis_bitly_use %}
    url_transforms : {
      shorten: {
        twitter: 'bitly',
        facebook: 'bitly'
      }
    }, 
    shorteners : {
      bitly : {} 
    },
    {% endif %}
    url: "{{ canonical_url }}",
    title: "{{ addthis_title }}",
    description: "{{ addthis_description }}",
    passthrough : {
      twitter: {
        {% if settings.addthis_twitter_id.size > 0 %}via: "{{ settings.addthis_twitter_id }}",{% endif %}
        text: "{{ addthis_twitter_string_calculated }}"
      }{% if settings.addthis_facebook_app_id.size > 0 %},
      facebook: {
        app_id: '{{ settings.addthis_facebook_app_id }}',
        redirect_uri: '{{ settings.addthis_facebook_redirect_url }}',
      }{% endif %}
    }
    {% if settings.addthis_email_template_use and addthis_image.size > 0 %},
    email_template: "{{ settings.addthis_email_template_name }}",
    email_vars: { 
      thisTitle: "{{ addthis_title }}" ,
      thisDescription: "{{ addthis_description }}", 
      thisImage: "{{ addthis_image }}" ,
    }
    {% endif %}
  }
</script>        
<script type="text/javascript" src="https://s7.addthis.com/js/300/addthis_widget.js#pubid={{ settings.addthis_id }}" async="async"></script>
{% endif %}

HTML for share buttons

Create a new snippet called “addthis-share-buttons.liquid” and add it on any page you like using {% include ‘addthis-share-buttons’ %}

<div class="product-share">
  <a class="product-share-button" href="#">Share</a>
  <div class="share">
    <ul>
      <li><a class="tooltip sharebutton addthis_button_facebook" id="share_facebook" title="Share {{ mysharetitle }} on Facebook"><i class="fa fa-facebook"></i></a></li>
      <li><a class="tooltip sharebutton addthis_button_twitter" id="share_twitter" title="Share {{ mysharetitle }} on Twitter"><i class="fa fa-twitter"></i></a></li>
      <li><a class="tooltip sharebutton addthis_button_tumblr" id="share_tumblr" title="Share {{ mysharetitle }} on Tumblr"><i class="fa fa-tumblr"></i></a></li>
      <li><a class="tooltip sharebutton sharenulify addthis_button_pinterest_share" id="share_pinterest" title="Share {{ mysharetitle }} on Pinterest"><i class="fa fa-pinterest"></i></a></li>
      <li><a class="tooltip sharebutton addthis_button_email" id="share_email" title="Send  {{ mysharetitle }} to a friend by Email"><i class="fa fa-envelope-o"></i></a></li>
      <li><a class="tooltip sharebutton addthis_button_compact" id="share_other" title="More share options"><i class="fa fa-bookmark"></i></a></li>
    </ul>
  </div>
</div>

Use CSS to style your buttons

For Fontawesome icons, remember to add the font css to your theme file.

.product-share-button, .share { display:inline-block; }
.share ul { display:inline-block; list-style:none; margin:0; padding:0; }
.share li {  margin:0; padding:0; display:inline-block; }
.share li a { display:inline-block; margin:0; padding:10px; font-size:18px; line-height: 38px;}

Media Queries for iPhone

/* iPhone 6 in portrait & landscape */
@media only screen 
and (min-device-width : 375px) 
and (max-device-width : 667px) { /* STYLES GO HERE */}

/* iPhone 6 in landscape */
@media only screen 
and (min-device-width : 375px) 
and (max-device-width : 667px) 
and (orientation : landscape) { /* STYLES GO HERE */}

/* iPhone 6 in portrait */
@media only screen 
and (min-device-width : 375px) 
and (max-device-width : 667px) 
and (orientation : portrait) { /* STYLES GO HERE */ }

/* iPhone 6 Plus in portrait & landscape */
@media only screen 
and (min-device-width : 414px) 
and (max-device-width : 736px) { /* STYLES GO HERE */}

/* iPhone 6 Plus in landscape */
@media only screen 
and (min-device-width : 414px) 
and (max-device-width : 736px) 
and (orientation : landscape) { /* STYLES GO HERE */}

/*  iPhone 6 Plus in portrait*/
@media only screen 
and (min-device-width : 414px) 
and (max-device-width : 736px) 
and (orientation : portrait) { /* STYLES GO HERE */ }

/* iPhone 5 & 5S in portrait & landscape */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 568px) { /* STYLES GO HERE */}

/* iPhone 5 & 5S in landscape */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 568px) 
and (orientation : landscape) { /* STYLES GO HERE */}

/* iPhone 5 & 5S in portrait */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 568px) 
and (orientation : portrait) { /* STYLES GO HERE */ }


/* iPhone 2G-4S in portrait & landscape */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) { /* STYLES GO HERE */}

/* iPhone 2G-4S in landscape */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) 
and (orientation : landscape) { /* STYLES GO HERE */}

/* iPhone 2G-4S in portrait */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) 
and (orientation : portrait) { /* STYLES GO HERE */ }

Fontawesome for Shopify theme (and asset_url output parameters)

When you use Shopify asset_url filter it outputs caching parameter to the end of the url. For example:

//cdn.shopify.com/s/files/X/XXXX/XXXX/t/X/assets/font-awesome.css?1234

This is great for developing themes sites, and refreshing the cdn cache, but can be hazardous when using external font-face file url’s in Shopify liquid css templates. For example:

url('//cdn.shopify.com/s/files/X/XXXX/XXXX/X/4/assets/fontawesome-webfont.svg?1234?v=4.0.3

If you want to add “Fontawesome” to your Shopify project do the following:

1. Download from “http://fortawesome.github.io/Font-Awesome/

2. Upload the font files to Shopify

  • In admin, go to “Themes > Template Editor”
  • Click on “Assets > Add new asset”
  • Upload each font file found in /fonts/ directory of Fontawesome download package

3. Upload “font-awesome.min.css” to assets folder and rename it as a Shopify liquid file “font-awesome.css.liquid”

4. Add the following to the top of your new Shopify liquid css file to get the correct font file paths for secure (ssl) and non-secure pages

{% capture font_url %}{{ 'fontawesome-webfont.eot' | asset_url | replace: 'http://','https://' }}{% endcapture %}
{% assign words = font_url | split: '?' %}
{% capture font_url_eot %}{{ words.first }}{% endcapture %}

{% capture font_url %}{{ 'fontawesome-webfont.woff' | asset_url | replace: 'http://','https://' }}{% endcapture %}
{% assign words = font_url | split: '?' %}
{% capture font_url_woff %}{{ words.first }}{% endcapture %}

{% capture font_url %}{{ 'fontawesome-webfont.ttf' | asset_url | replace: 'http://','https://' }}{% endcapture %}
{% assign words = font_url | split: '?' %}
{% capture font_url_ttf %}{{ words.first }}{% endcapture %}

{% capture font_url %}{{ 'fontawesome-webfont.svg' | asset_url | replace: 'http://','https://' }}{% endcapture %}
{% assign words = font_url | split: '?' %}
{% capture font_url_svg %}{{ words.first }}{% endcapture %}

5. Replace file paths in the Shopify liquid css file with new variables

  ....
  @font-face{
  font-family:'FontAwesome';
  src:url('{{ font_url_svg }}?v=4.0.3');
  src:url('{{ font_url_eot }}?#iefix&v=4.0.3') format('embedded-opentype'),
    url('{{ font_url_woff }}?v=4.0.3') format('woff'),
    url('{{ font_url_ttf }}?v=4.0.3') format('truetype'),
    url('{{ font_url_svg }}?v=4.0.3#fontawesomeregular') format('svg');
  ....

5. Add the css to your Shopify theme liquid file.

{{ 'font-awesome.css' | asset_url | stylesheet_tag }}

6. Start using it by adding HTML mark-up to your templates.

Smooth scrolling with anchor tags

  function filterPath(string) {
  return string
	.replace(/^\//,'')
	.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
	.replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');
 
  $('a[href*=#]').each(function() {
	var thisPath = filterPath(this.pathname) || locationPath;
	if (  locationPath == thisPath
	&& (location.hostname == this.hostname || !this.hostname)
	&& this.hash.replace(/#/,'') ) {
	  var $target = $(this.hash), target = this.hash;
	  if (target) {
		var targetOffset = $target.offset().top;
		$(this).click(function(event) {
		  event.preventDefault();
		  $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
			location.hash = target;
		  });
		});
	  }
	}
  });
 
  // use the first element that is "scrollable"
  function scrollableElement(els) {
	for (var i = 0, argLength = arguments.length; i <argLength; i++) {
	  var el = arguments[i],
		  $scrollElement = $(el);
	  if ($scrollElement.scrollTop()> 0) {
		return el;
	  } else {
		$scrollElement.scrollTop(1);
		var isScrollable = $scrollElement.scrollTop()> 0;
		$scrollElement.scrollTop(0);
		if (isScrollable) {
		  return el;
		}
	  }
	}
	return [];
  }

CSS for fancy header with border at sides

.fancyheader {
  line-height: 0.5;
  text-align: center;
}
.fancyheader span {
  display: inline-block;
  position: relative;  
}
.fancyheader span:before, .fancyheader span:after {
    border-bottom: 1px solid black;
    content: "";
    height: 5px;
    position: absolute;
    top: 0;
    width: 100%;
}
.fancyheader span:before {
  right: 100%;
  margin-right: 15px;
}
.fancyheader span:after {
  left: 100%;
  margin-left: 15px;
}


Create a responsive WordPress attachment page

Create a new file in your theme folder called “single-attachment.php”.

Replace

with:

<?php 
$image_info = getimagesize($post->guid); var_dump($image_info); 
$imgclass = "";
if ($image_info[0] >  1280) // replace 1280 with your max width
{
	$imgclass = "resposiveattachment";
}
?>
<img class="<?php echo $imgclass; ?>" src="<?php echo $post->guid; ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" <?php echo $image_info[3]; ?> />

Add the following CSS to your site:

.resposiveattachment { width:100%!important; height:auto!important;}