Christian Heilmann

You are currently browsing the archives for the General category.

Archive for the ‘General’ Category

Mind the gap – State of the Browser 5 was a blast

Sunday, September 13th, 2015

Yesterday was the fifth edition of State of the Browser in London, England. SOTB was always a special kind of event: representatives of all the browsers (and confusion about what Apple might be up to) came, gave short talks about hot new technical topics and then formed a panel to answer people’s questions.

This year, the format changed and instead there were a lot of 25 minute talks by interesting people, regardless of who they work for. There was also no panel.

SOTB still is a lovely, friendly and very affordable event bang in the centre of London and thus very accessible. The organisers also do a monthly meetup and are just good eggs all around.

As there is no space in my tiny new flat I had donated all the swag, books, stickers bags and shirts I collected over the last 10 years to the event and it made an impressive stash. People took the lot (except for a German CSS book).

sotb-swag

All talks are recorded and streamed live and the videos are trickling in on the organiser’s Vimeo feed.

The line-up was great and full of new faces on the speaking circuit, some of which gave their first talks. Here’s my quick notes (talks in chronological order):

  • Seb Lee-Delisle’s “Being grown-up doesn’t have to be boring” was supposed to be a round-up of all his creative projects using laser projection but ended up being situational comedy as none of his videos worked. Yet he explained and entertained and made the audience clap and wave to control sounds and flappy bird animations using kinnect so everybody was happy. Make sure to spot Bruce Lawson and me out-dancing everybody else in the first row in the video.
  • Edd Sowden’s “Accessibility and how to get the most from your screenreader” pivoted into “What U doing with data tables, browsers” and was insightful, very well researched and above all – funny to watch. Edd has a wonderful dead-pan delivery of weird browser workings. Well worth your time to see this video and check his slides.
  • Melinda Seckington’s “Learn. Reflect. Repeat – How We Run Internal Hackdays and Other Events” talked about her overcoming her impostor syndrome and how to teach people and learn from one another. You can see her in the video here.
  • Martin Jakl’s debut talk “Another billion browsers and Internet of Things” kind of went past me as I was preparing for my own talk following his. He did a look back at the problems of WAP and early mobile tech and showed how IoT will mean for us to care much more about low-end memory devices again.
  • My own talk is posted further on here. So far, here are the slides and a screencast.
  • Bruce Lawson’s “Ensuring a Performant Web for the Next Billion People” was a great round-up of opportunities in emerging markets and a reminder what this means to our products. Bruce’s slides are here – some great re-usable information in there.
  • Laura Elizabeth’s “From Pages to Patterns: How Pattern Libraries are Changing the Face of the Web” was my big surprise for the day. A first time speaker and pretty nervous she delivered an absolutely delightful talk about using pattern libraries and making them work for your clients. Well organised, well researched and delivered with a lot of confidence. If you’re looking for a design-oriented presenter with lots of understanding for development needs, Laura is someone fresh and new to consider.
  • Adam Onishi’s “Best viewed with…” was a trip down memory lane how we did things wrong about browser support and progressive enhancement and how we’re repeating these mistakes. Very well argued presentation with a very confident and interesting delivery.
  • Ada Rose Edwards’ “Animation Performance on the Web” was a whirl-wind tour of making animation perform including pretty far out ideas like using shaders to plough through a lot of data without slowing down the main thread. Her slides are here and they link to all the demos she showed. Ada is right now my go-to JavaScript presenter to tell conferences about, so expect more epicness to come from her.
  • Phil Nash’s “The web is getting pushy” once again proved his utter disregard for browsers not doing the things he wants and the horrors of live coding. Clever, well paced and good talk about live updates and notifications on the web.

The Twitter coverage of the event is extensive and still ongoing so be sure to check out the #sotb5 hashtag for more stuff trickling in.

My talk was a quick preview for a longer one I am working on bemoaning and explaining the gap I see between what we advocate as “common knowledge” at events like these and what I see people building on the web. We are a bubble inside a bubble and it is time to burst out and bring the great information we are already getting bored of to those who mess with the web. The slides are here and I recorded a screencast if you want to keep the context. I’m looking forward to the video.

All in all SOTB is well worth your time and money. If you also live by the river, make sure to attend the London Webstandards meetups.

It is a bit of a shame that the format changed, I kind of miss the focus on browsers and wished someone else would take that on or we’ll organise ourselves into monthly hangouts. I’m working on some ideas around this.

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>
  <template>
    <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>
  </template>
</ul>

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
    list.removeChild(t);
    // add the cached content to the parent
    list.innerHTML += contents;
  }
  all = document.body.querySelectorAll('.card').length + 1;
  updatecounter();
});

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>
  </ul>
  <button class="but-nope">X</button>
  <button class="but-yay">✔</button>
</div>

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') {
    t.parentNode.classList.add('nope');
  }
  if (t.className === 'but-yay') {
    t.parentNode.classList.add('yes');
  }
}
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') {
    origin.classList.remove('yes');
  }
  if (ev.animationName === 'nope') {
    origin.classList.remove('nope');
  }
 
  // if any of the card events have 
  // ended…
  if (ev.animationName === 'nope' ||
      ev.animationName === 'yay') {
 
  // remove the first card in the element
    origin.querySelector('.current').remove();
 
  // 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 
      origin.querySelector('.card').
        classList.add('current');
    }
  }
}
document.body.addEventListener(
  '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
  });
  document.body.dispatchEvent(newevent);
}

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') {
    t.parentNode.classList.add('nope');
    fireCustomEvent('nopecard',
      {
        origin: t,
        container: t.parentNode,
        card: t.parentNode.querySelector('.card')
      }
    );
  }
  if (t.className === 'but-yay') {
    t.parentNode.classList.add('yes');
    fireCustomEvent('yepcard',
      {
        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) {
  console.log(
    ev.detail.card,
    ev.detail.card.innerHTML
  );
});
b.addEventListener('yepcard', function(ev) {
  console.log(
    ev.detail.card,
    ev.detail.card.innerHTML
  );
});

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: