• You are currently browsing the archives for the General category.

  • Archive for the ‘General’ Category

    How about we make ES6 the new baseline?

    Wednesday, September 9th, 2015

    Bass strings

    Yesterday night, far too late, I wrote a long article here about making ES6 the new baseline of the web. It wasn’t a good article. It made a lot of assumptions, and it wasn’t thought through. That’s why I removed it.

    I am right now writing my keynote for BrazilJS on this same topic and put more thought into that. And here is the recording of this keynote:

    Quick trick: using template to delay loading of images

    Tuesday, September 8th, 2015

    In addition to this explanation, I also recorded a quick screencast. Feel free to check that one first.

    When it comes to newer elements to play with there are a few that are slightly odd. Canvas is one of them, as it doesn’t do anything without scripting. It is a placeholder for a canvas painting or animation and can contain fallback content when it is not supported. This ailed purists of semantic HTML when it came out, because – to a degree – this was just a rehash of applet or object we used with Java or Flash.

    Template is an even weirder thing. Using template you can define inert content in HTML - this means the content is not rendered by the browser, and anything inside it is not executed (for example script elements). Again, this is something that can annoy purists, as this content only makes sense when JavaScript is available. But, to people who are used to templating in other languages, this is a great opportunity.

    The biggest issue with template is that it can’t really by polyfilled as browsers that don’t know template, treat it like a DIV and render its content. In the past we simulated this functionality with script elements with a type of text/html as those will be skipped by browsers.

    For more info about template itself, check these resources:

    One thing you can do with template is to put content in it that is “nice to have” but would delay the loading of the page and especially the firing of the onload handler.

    I’ve done this in the Cuter demo of Tinderesque. This demo loads a lot of images, and not all of them need to be available right away. That’s why I put five of them in the document and wrapped the rest in a template:

    <ul class="cardlist">
      <li class="card current"><img src="images/a-push-please.jpg" alt=""></li>
      <li class="card"><img src="images/amazing-dog.jpg" alt=""></li>
      <li class="card"><img src="images/awesome-mix-dog.jpg" alt=""></li>
      <li class="card"><img src="images/baby-amardillo.jpg" alt=""></li>
      <li class="card"><img src="images/baby-hippo-nom.jpg" alt=""></li>
        <li class="card"><img src="images/baby-rhino.jpg" alt=""></li>
        <li class="card"><img src="images/barbie-frenchie.jpg" alt=""></li>
        <li class="card"><img src="images/basset-helmet.jpg" alt=""></li>
        <li class="card"><img src="images/bear-dog.jpg" alt=""></li>
        <li class="card"><img src="images/bear-puppy-fluff.jpg" alt=""></li>
        <li class="card"><img src="images/best-day-ever-puppy.jpg" alt=""></li>
        <li class="card"><img src="images/bleh-puppy.jpg" alt=""></li>
        <li class="card"><img src="images/bleh-tapir.jpg" alt=""></li>
        <li class="card"><img src="images/cat-on-stairs.jpg" alt=""></li>
        <li class="card"><img src="images/chocolate-puppy.jpg" alt=""></li>
        <li class="card"><img src="images/corgisquee.jpg" alt=""></li>
        <li class="card"><img src="images/corns-and-penny.jpg" alt=""></li>
        <li class="card"><img src="images/crazy-otter.jpg" alt=""></li>
        <li class="card"><img src="images/cute-brown-puppy.jpg" alt=""></li>
        <li class="card"><img src="images/dalmatian.jpg" alt=""></li>
        <li class="card"><img src="images/derpy-hedgehog.jpg" alt=""></li>

    This allows me to maintain all the info of my images in HTML (rather than having to add all the sources, alternative text, titles and so on in some JSON blob) and only load the first five when the page loads.

    To add the rest, I just use an onload handler, that takes the content of the template and adds it to the parent element.

    window.addEventListener('load', function(ev) {
      // check if template is supported
      // browsers without it wouldn't need to
      // do the content shifting
      if ('content' in document.createElement('template')) {
        // get the template
        var t = document.querySelector('template');
        // get its parent element
        var list = t.parentNode;
        // cache the template content
        var contents = t.innerHTML;
        // kill the template
        // add the cached content to the parent
        list.innerHTML += contents;
      all = document.body.querySelectorAll('.card').length + 1;

    The difference is pretty significant. Without the template trick the 542 KB transferred in 26 requests take 6.43 seconds on a 3G connection. The onload handler fires after that. With the template, onload fires at 2.08 seconds. Here’s a screenshot of both using Chrome Devtools:

    Onload delay with and without template

    Template support is pretty great. The only browsers that don’t support it for now are IE and Microsoft Edge. Opera Mini also doesn’t support it, but that’s due to it’s non-client script nature.

    Browsers that don’t support template will load all the images and delay the onload handler. But all the others can properly benefit from this. Why not give it a go?

    Tinderesque – building a Tinder-like interface with CSS animations and vanilla JS #justcode

    Sunday, September 6th, 2015

    Tinder is a very successful dating app, and one of its features is a way to say yes or no to prospective partners by swiping right or left or pressing a yes or no button. The interface is cards that drop when you press the buttons.

    As with any successful interface, a lot of clones that mimick them happen very fast. One of those is FontFlame – a Tinder for Font Pairings. When I saw this one, I thought the animation isn’t right (it just moves to the right or left and fades, there’s no turning or popping up). I tried to fix the CSS animation to match more closely what Tinder is doing, but to my dismay I found out that whilst Fontflame uses CSS animations, they get over-ridden by jQuery ones. I contacted the author and offered my CSS animation to replace the current one.

    Just for fun, I packed this up into a quick solution consisting of a CSS animation and some JavaScript to control the voting process.

    Tinderesque in action

    I called it Tinderesque. You can see it in action, Get the code and read the instructions how to use it on GitHub.

    Here’s some explanations on how Tinderesque works.

    The Tinderesque animation

    Animating the cards is no rocket science: we rotate the card after setting the transformation origin to the bottom of the card and shift it up a bit to get a “discard” effect.

    First up, we need to define the HTML of the collection of cards we want to vote on. This should be pretty straight forward:

    <div class="cardcontainer list">
      <ul class="cardlist">
        <li class="card current">#1</li>
        <li class="card">#2</li>
        <li class="card">#3</li>
        <li class="card">#4</li>
        <li class="card">#5</li>
        <li class="card">#6</li>
      <button class="but-nope">X</button>
      <button class="but-yay"></button>

    To achieve the animation effect we need to give the card we want to animate some dimensions and set its transform origin to its bottom:

    .card {
      width: 150px;
      height: 200px;
      display: block;
      background: #666;
      transform-origin: 50% 99%;

    This ensures that the card doesn’t get rotated around its centre but the bottom instead.

    For the positive scenario, we rotate the card clockwise and push it up a bit to get the discard effect. This can be done using a rotate and translateY transformation. We also animate the opacity of the card from 1 to 0, effectively hiding it.

    @keyframes yay {
      from {
        transform: rotate(0deg);
        opacity: 1;
      to {
        transform: rotate(40deg) translateY(-80px);
        opacity: 0;

    For the negative use case, we rotate the card counter-clockwise:

    @keyframes nope {
      from {
        transform: rotate(0deg);
        opacity: 1;
      to {
        transform: rotate(-40deg) translateY(-80px);
        opacity: 0;

    We then trigger these animations by adding and removing classes on the parent elmement of the cards:

    .cardcontainer.yes .card {
      animation: yay 0.7s ease-out;
    .cardcontainer.nope .card {
      animation: nope 0.7s ease-out;

    Going through the whole card deck

    In order to go through the card deck two things must happen:

    • We need to animate the current card using the positive or negative animation
    • When the animation is finished, we need to remove the card from the document and show the next one.

    By default, we hide all the cards in the deck. Only the one with the class of current is visible:

    .list .card {
      display: none;
    .list .current {
      display: block;

    This means that we need to shift the class of current to the next card once this one has been approved or discared. But first, we need to trigger the animation. In order to achieve this, we need either a hover or some clever trickery with checkboxes in CSS. It is more extensible though to use JavaScript.

    Triggering the animations

    All we need to trigger the animations is adding an event handler attached to the buttons in the HTML. Depending on which button was pressed we add a yes or nope class to the parent element of the button – in this case, the cardcontainer DIV.

    function animatecard(ev) {
      var t = ev.target;
      if (t.className === 'but-nope') {
      if (t.className === 'but-yay') {
    document.body.addEventListener('click', animatecard);

    We’re using event delegation here with a click handler on the body of the document. We can of course extend this to pointer or touch handlers to allow for touch events and simulating swipe gestures.

    Acting after the animation using events

    Our card has now been animated and is invisible, but it is still in the document and the next card isn’t visible yet. We need to remove the card and shift the current class to the next card in the deck.

    Every CSS animation has an animationend event we can use for that. The event gives us the name of the event, which gives us the name of the class to remove.

    function animationdone(ev) {
      // get the container
      var origin = ev.target.parentNode;
      // remove the appropriate class
      // depending on the animation name
      if (ev.animationName === 'yay') {
      if (ev.animationName === 'nope') {
      // if any of the card events have 
      // ended…
      if (ev.animationName === 'nope' ||
          ev.animationName === 'yay') {
      // remove the first card in the element
      // if there are no cards left, do nothing
        if (!origin.querySelector('.card')) {
          // no more cards left - 
          // TODO other functionality
        } else {
      // otherwise shift the 'current' class to 
      // the next card 
      'animationend', animationdone

    That’s more or less all we need to do. Except that Safari still hasn’t joined us in the year 2015. That’s why we need to repeat both the CSS animation definitions in our CSS with –webkit– prefixes and add an event handler for webkitAnimationEnd. I refuse to do so here, as this is depressing, but you can see it in the tinderesque source code.

    Extending the functionality using Custom Events

    The functionality now is pretty basic, which means we want to make it as easy as possible to extend it. The simplest way to do that is to add Custom Events that fire when things happen to our card deck. This is as easy as using this function:

    function fireCustomEvent(name, payload) {
      var newevent = new CustomEvent(name, {
        detail: payload

    Custom events can get a payload – you can define what the listener gets as parameters. In the case of tinderesque, the animatecard function has been extended to send a reference to the button that was clicked, its container element (in case you have several decks) and a copy of the current card.

    function animatecard(ev) {
      var t = ev.target;
      if (t.className === 'but-nope') {
            origin: t,
            container: t.parentNode,
            card: t.parentNode.querySelector('.card')
      if (t.className === 'but-yay') {
            origin: t,
            container: t.parentNode,
            card: t.parentNode.querySelector('.card')

    This allows you to read the content of the card before it gets removed from the document.

    Reading cards before they get discarded

    var b = document.body;
    b.addEventListener('nopecard', function(ev) {
    b.addEventListener('yepcard', function(ev) {

    Tinderesque also fires a custom event called deckempty when the last card got removed from the list. In the demo page this is used to re-stack the deck:

    var b = document.body;
    b.addEventListener('deckempty', function(ev) {
      var container = ev.detail.container;
      var list = container.querySelector('.cardlist');
      var out = '<li class="card current">#1</li>';
      for (var i = 2; i < 6; i++) {
        out += '<li class="card">#' + i + '</li>';
      list.innerHTML = out;

    This should get you well on the way to build your own Tinder-like interface. If I find the time, I will record a screencast doing exactly that.

    Cuter – a quick demo using Tinderesque

    As a demo, I put together Cuter – a way to say yes or no to cute animal pictures and end up with a list of the ones you chose.
    You can see it on YouTube:

    Quickie: Fading in a newly created element using CSS

    Sunday, August 30th, 2015

    Update: I got an email from James at VIDesignz who found another solution to this problem using the :empty selector. I added it at the end of the article.

    As part of our JSFoo workshop today I was asked to look into an issue a team had that you can not apply a CSS transition to a newly created element when you change the CSS settings in JavaScript. As I was dealing with professionals, they created a simple JSFiddle to show the problem:

    As you see just changing the property (in this case the opacity) is not enough to have a transition. There are a few solutions to this shown in the Fiddle, too, like forcing a reflow, which of course could be a terrible idea.

    I played with this and found the solution to be to not change the properties in JavaScript (which is kind of dirty anyways) but leave it all to CSS instead. The biggest part of the solution is not to use a transition but an animation instead and trigger it by applying a class to the newly created element right after adding it to the DOM:

    Update: As mentioned by Kyle Simpson on Twitter, there is a way to do the same with a transition, but you need to wrap the creation and applying the class into requestAnimationFrame calls which in turn means some polyfilling:

    Update2 You can also use the :empty selector in CSS to achieve the same when you add the new element as a child:

    ES6 for now: Template strings

    Friday, August 28th, 2015

    ES6 is the future of JavaScript and it is already here. It is a finished specification, and it brings a lot of features a language requires to stay competitive with the needs of the web of now. Not everything in ES6 is for you and in this little series of posts I will show features that are very handy and already usable.

    If you look at JavaScript code I’ve written you will find that I always use single quotes to define strings instead of double quotes. JavaScript is OK with either, the following two examples do exactly the same thing:

    var animal = "cow";
    var animal = 'cow';

    The reason why I prefer single quotes is that, first of all, it makes it easier to assemble HTML strings with properly quoted attributes that way:

    // with single quotes, there's no need to 
    // escape the quotes around the class value
    var but = '<button class="big">Save</button>';
    // this is a syntax error:
    var but = "<button class="big">Save</button>";
    // this works:
    var but = "<button class=\"big\">Save</button>";

    The only time you need to escape now is when you use a single quote in your HTML, which should be a very rare occasion. The only thing I can think of is inline JavaScript or CSS, which means you are very likely to do something shady or desperate to your markup. Even in your texts, you are probably better off to not use a single quote but the typographically more pleasing ‘.

    Aside: Of course, HTML is forgiving enough to omit the quotes or to use single quotes around an attribute, but I prefer to create readable markup for humans rather than relying on the forgiveness of a parser. We made the HTML5 parser forgiving because people wrote terrible markup in the past, not as an excuse to keep doing so.

    I’ve suffered enough in the DHTML days of document.write to create a document inside a frameset in a new popup window and other abominations to not want to use the escape character ever again. At times, we needed triple ones, and that was even before we had colour coding in our editors. It was a mess.

    Expression substition in strings?

    Another reason why I prefer single quotes is that I wrote a lot of PHP in my time for very large web sites where performance mattered a lot. In PHP, there is a difference between single and double quotes. Single quoted strings don’t have any substitution in them, double quoted ones have. That meant back in the days of PHP 3 and 4 that using single quotes was much faster as the parser doesn’t have to go through the string to substitute values. Here is an example what that means:

      $animal = 'cow';
      $sound = 'moo';
      echo 'The animal is $animal and its sound is $sound';
      // => The animal is $animal and its sound is $sound
      echo "The animal is $animal and its sound is $sound";
      // => The animal is cow and its sound is moo

    JavaScript didn’t have this substitution, which is why we had to concatenate strings to achieve the same result. This is pretty unwieldy, as you need to jump in and out of quotes all the time.

    var animal = 'cow';
    var sound = 'moo';
    alert('The animal is ' + animal + ' and its sound is ' +
    // => "The animal is cow and its sound is moo"

    Multi line mess

    This gets really messy with longer and more complex strings and especially when we assemble a lot of HTML. And, most likely you will sooner or later end up with your linting tool complaining about trailing whitespace after a + at the end of a line. This is based on the issue that JavaScript has no multi-line strings:

    // this doesn't work
    var list = '<ul>
      <li>Buy Milk</li>
      <li>Be kind to Pandas</li>
      <li>Forget about Dre</li>
    // This does, but urgh… 
    var list = '<ul>\
      <li>Buy Milk</li>\
      <li>Be kind to Pandas</li>\
      <li>Forget about Dre</li>\
    // This is the most common way, and urgh, too…
    var list = '<ul>' +
    '  <li>Buy Milk</li>' +
    '  <li>Be kind to Pandas</li>' +
    '  <li>Forget about Dre</li>' +

    Client side templating solutions

    In order to work around the mess that is string handling and concatenation in JavaScript, we did what we always do – we write a library. There are many HTML templating libraries with Mustache.js probably having been the seminal one. All of these follow an own – non standardised – syntax and work in that frame of mind. It’s a bit like saying that you write your content in markdown and then realising that there are many different ideas of what “markdown” means.

    Enter template strings

    With the advent of ES6 and its standardisation we now can rejoice as JavaScript has now a new kid on the block when it comes to handling strings: Template Strings. The support of template strings in current browsers is encouraging: Chrome 44+, Firefox 38+, Microsoft Edge and Webkit are all on board. Safari, sadly enough, is not, but it’ll get there.

    The genius of template strings is that it uses a new string delimiter, which isn’t in use either in HTML nor in normal texts: the backtick (`).

    Using this one we now have string expression substitution in JavaScript:

    var animal = 'cow';
    var sound = 'moo';
    alert(`The animal is ${animal} and its sound is ${sound}`);
    // => "The animal is cow and its sound is moo"

    The ${} construct can take any JavaScript expression that returns a value, you can for example do calculations, or access properties of an object:

    var out = `ten times two totally is ${ 10 * 2 }`;
    // => "ten times two totally is 20"
    var animal = {
      name: 'cow',
      ilk: 'bovine',
      front: 'moo',
      back: 'milk',
      The ${animal.name} is of the 
      ${animal.ilk} ilk, 
      one end is for the ${animal.front}, 
      the other for the ${animal.back}
    // => 
      The cow is of the 
      bovine ilk, 
      one end is for the moo, 
      the other for the milk

    That last example also shows you that multi line strings are not an issue at all any longer.

    Tagged templates

    Another thing you can do with template strings is prepend them with a tag, which is the name of a function that is called and gets the string as a parameter. For example, you could encode the resulting string for URLs without having to resort to the horridly named encodeURIComponent all the time.

    function urlify (str) {
      return encodeURIComponent(str);
    urlify `http://beedogs.com`;
    // => "http%3A%2F%2Fbeedogs.com"
    urlify `woah$£$%£^$"`;
    // => "woah%24%C2%A3%24%25%C2%A3%5E%24%22"
    // nesting also works:
    var str = `foo ${urlify `&&`} bar`;
    // => "foo %26%26 bar"

    This works, but relies on implicit array-to-string coercion. The parameter sent to the function is not a string, but an array of strings and values. If used the way I show here, it gets converted to a string for convenience, but the correct way is to access the array members directly.

    Retrieving strings and values from a template string

    Inside the tag function you can not only get the full string but also its parts.

    function tag (strings, values) {
    tag `you ${3+4} it`;
    /* =>
    Array [ "you ", " it" ]

    There is also an array of the raw strings provided to you, which means that you get all the characters in the string, including control characters. Say for example you add a linebreak with \n you will get the double whitespace in the string, but the \n characters in the raw strings:

    function tag (strings, values) {
    tag `you ${3+4} \nit`;
    /* =>
    Array [ "you ", "  it" ]


    Template strings are one of those nifty little wins in ES6, that can be used right now. If you have to support older browsers, you can of course transpile your ES6 to ES5, you can do a feature test for template string support using a library like featuretests.io or with the following code:

    var templatestrings = false;
    try {
      new Function( "`{2+2}`" );
      templatestrings = true;
    } catch (err) {
      templatestrings = false;
    if (templatestrings) {
    	// …

    More articles on template strings: