Christian Heilmann

You are currently browsing the Christian Heilmann blog archives for August, 2015.

Archive for August, 2015

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:

<?php
  $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 ' +
 sound);
// => "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>
</ul>';
 
// This does, but urgh… 
var list = '<ul>\
  <li>Buy Milk</li>\
  <li>Be kind to Pandas</li>\
  <li>Forget about Dre</li>\
</ul>';
 
// 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>' +
'</ul>';

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',
}
alert(`
  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) {
  console.log(strings);
  console.log(values);
  console.log(strings[1]);
}
 
tag `you ${3+4} it`;
/* =>
 
Array [ "you ", " it" ]
7
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) {
  console.log(strings);
  console.log(values);
  console.log(strings[1]);
  console.log(string.raw[1]);
}
 
tag `you ${3+4} \nit`;
/* =>
 
Array [ "you ", "  it" ]
7
 
it
 \nit
*/

Conclusion

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:

Rock, Meats, JavaScript – BrazilJS 2015

Tuesday, August 25th, 2015

BrazilJS audience

I just got back from a 4 day trip to Brazil and back to attend BrazilJS. I was humbled and very happy to give the opening keynote seeing that the closing was meant to be by Brendan Eich and Andreas Gal – so, no pressure.

The keynote

In my keynote, I asked for more harmony in our community, and more ownership of the future of JavaScript by those who use it in production.

Keynote time

For quite some while now, I am confused as to who we are serving as browser makers, standards writers and library creators. All of the excellent solutions we have seem to fall through the cracks somewhere when you see what goes live.

That’s why I wanted to remind the audience that whatever amazing, inspiring and clever thing they’ll hear about at the conference is theirs to take to fruition. We have too much frustration in our market, and too much trying to one-up one another instead of trying to solve problems and making the solutions easily and readily available. The slides are on Slideshare, and a video will become available soon.

Can we make es6 the baseline of the “modern web”? – BrazilJS 2105 from Christian Heilmann

About Brazil

There are a few things to remember when you are going to Brazil:

  • When people are excited about something, they are really excited about it. There’s a lot of passion.
  • Personal space is as rare as an affordable flat in central London – people will affectionately touch strangers and there is a lot of body language. If that’s not your thing, make it obvious!
  • You will eat your body weight in amazing meat and food is a social gathering, not just fuel. Thus, bring some time.
  • Everybody will apologise for their bad English before having a perfectly comprehensible conversation with you
  • People of all ages and backgrounds are into heavy music (rock, metal, hardcore…)

About the event

VR ride about the history of JavaScript

BrazilJS was a ridiculous attempt at creating the biggest JavaScript event with 1,300 people. And it was a 100% success at that. I am fascinated by the professionalism, the venue, the AV setup and all the things that were done for speakers and attendees alike. Here are just a few things that happened:

  • There was a very strong message about diversity and a sensible and enforced code of conduct. This should not be a surprise, but when you consider Brazilian culture and reputation (think Carnival) it takes pride and conviction in those matters to stand up for them the way the organisers did.
  • The AV setup was huge and worked fine. There were no glitches in the audio and every presentation was live translated from English to Brazilian Portuguese and vice versa. The translation crew did a great job and we as presenters should do more to support them. I will write a post soon about this.
  • Wireless was flaky, but available when you needed it. It is pretty ridiculous to assume in a country where connectivity isn’t cheap and over a thousand people with two devices each try to connect that you’d have a good connection. As a presenter, I never rely on availability – neither should you.
  • There was always enough coffee, snacks and even a huge cake celebrating JavaScript (made by the mom of one of the organisers – the cake, not JavaScript)
  • The overall theme was geek – as geek as it can get. The organisers dressed up as power rangers, in between talks we saw animated 90s TV series, there as a Virtual Reality ride covering the history of JavaScript built with Arduinos and there were old-school arcade machines and consoles to play with.
  • It was a single track conference over two days with lots of high-class speakers and very interesting topics.
  • As a speaker, everything was organised for me. We all took a hired bus from and to the venue and we had lunch catered for us.
  • The conference also had a minority/diversity scholarship program where people who couldn’t afford to come got a sponsored ticket. These people weren’t grandstanded or shown up but just became a part of the crowd. I was lucky to chat to a few and learned quite a few things.
  • The after party was a big “foot in mouth” moment for me as I kept speaking out against bands at those. However, in Brazil and choosing a band that covers lots of rock anthems, it very much worked. I never thought I see an inclusive, non-aggressive mosh pit and people stage diving at a JavaScript event – I was wrong.

action shot
Me, stagediving at the BrazilJS after party – photo by @orapouso

So, all I can say is thank you to everyone involved. This was a conference to remember and the enthusiasm of the people I met and talked to is a testament to how much this worked!

Personal/professional notes

BrazilJS was an interesting opportunity for me as I wanted to connect with my Microsoft colleagues in the country. I was amazed by how well-organised our participation was and loved the enthusiasm people had for us. Even when one of our other speakers couldn’t show up, we simply ran an impromptu Q&A on stage abut Edge. Instead of a sales booth we had technical evangelists at hand, who also helped translating. Quite a few people came to the booth to fix their web sites for Microsoft Edge’s standard compliant rendering. It’s fun to see when fixing things yields quick results.

Other short impressions:

  • I had no idea what a machine my colleague Jonathan Sampson is on stage. His talk in adventurous Portuguese had the audience in stitches and I was amazed by the well-structured content. I will pester him to re-record this in English.
  • Ju Gonçalves (@cyberglot) gave a great, detailed talk about reduce(). If you are a conference organiser, check her out as a new Speaker() option – she is now based in Copenhagen.
  • It was fun to catch up with Laurie Voss after a few years (we worked in Yahoo together) and it was great of him to point to his LGBTQ Slack group inviting people to learn more about that facet of diversity in our community.
  • It warmed me to see the Mozilla Brazil community still kicking butt. Warm, affectionate and knowledgable people like the ones you could meet at the booth there are the reason why I became a Mozillian in the first place.

And that’s that

Organisers on stage

Thank you for everyone involved. Thank you to everybody asking me lots of technical questions and giving non-filtered feedback. Thank you for showing that a lot of geeks can also be very human and warm. Thank you for embracing someone who doesn’t speak your language. I met quite a few people I need to follow up with and I even had a BBQ at the family of two of the attendees I met before I went to my plane back home. You rock!

Always bet on JavaScript cake

The ES6 conundrum – new article on SitePoint

Tuesday, August 11th, 2015

conundrum

I just released an article over on Sitepoint called The ES6 conundrum. In it, I am discussing the current issues we’re facing with using ES6:

  • We can’t use it safely in the wild – as ES6 is a syntax change to the language, legacy browsers will see it as a JavaScript error and give our end users a broken experience. This violates the Priority of Constituencies design principle of HTML5
  • We can use TypeScript or transpile it – which means we don’t debug the code we write but generated code. This can also lead to a lot of code bloat.
  • We can feature test for it – which that can get complex quickly and we can’t assume that support for one features means others are supported
  • Browser support for ES6 only makes a difference internally – as we transpile, we never send any ES6 to the browser
  • The performance of ES6 is bad right now which is normal, as we have no way to tweak and test it in the browser and it offers much more complexity than ES5

All in all, we need to have a good think about ES6, and – to me – it feels we are at a turning point in web development. I will talk in more detail about this in my BrazilJS keynote in two weeks.

Read “The ES6 conundrum” on Sitepoint

Erase and Rewind – a talk about open web enthusiasm at Open Web Camp

Tuesday, August 4th, 2015

I just flew from San Francisco to Seattle still suffering from the aftermath of the after party of Open Web Camp 7, a gathering of enthusiasts of the web that lasted for seven years and showed that you can teach, inspire and meet without having to pay a lot. The ticket prices were $10 and even those were mostly to avoid people getting tickets and not coming. All the money left over was then donated to a great cause. Thank you for everyone involved, especially John Foliot for seven years of following a dream and succeeding. And also for moving on whilst you are still happy with what you do.

My presentation at the event, “Erase and rewind – a tale of innovation and impatience” discussed the problems I found with advocating for the open web I encountered over the years. The problems we found, the gaps I see in our storytelling and the loss of focus we suffered when smartphones became a new form factor that seemed great for the web, but became its biggest problem very soon.

There’s a screencast of the presentation on YouTube

The slides are available on Slideshare

Erase and Rewind – Open Web Camp 2015 from Christian Heilmann

I got a bit into a rant, but I think there is a big problem that the people who advocate about great ideas of the web clash with those who want to innovate it. There are a lot of events going on right now that want to achieve the same goal, but keep violating the best practices of others. We need to rally to keep the web relevant and alive. Not define that what we do is the one true way.