Tag: quick-tip

In JavaScript, there is a problem that comes up often. You need a way to update parts of a page in response to certain events, with the data these provide. Say, for example, user input that you then project into one or many components. This leads into a lot of push-and-pull in the code to keep everything in sync.
This is where the observer design pattern can help — it enables one-to-many data binding between elements. This one-way data binding can be event driven. With this pattern, you can build reusable code that solves for your specific needs.
In this article, I’d like to explore the observer design pattern. It will help you solve a common problem you see in client-side scripting. That is one-to-many, one-way, and event-driven data binding. It is a problem that comes up often when you have many elements that must be in sync.
I’ll use ECMAScript 6 to illustrate the pattern. Yes, there will be classes, arrow functions, and constants. Feel free to explore these topics on your own if you are not already familiar. I’ll use parts of ES6 that introduce syntactic sugar only, so it is portable with ES5 if need be.
And I’ll use Test-Driven-Development (TDD) to work on the pattern. This way you have a way knowing how each component is useful.
The new language features in ES6 make for some succinct code. So, let’s get started.
The Event Observer
A high-level view of the pattern looks like this:
EventObserver
│
├── subscribe: adds new observable events
│
├── unsubscribe: removes observable events
|
└── broadcast: executes all events with bound data

After I flesh out the observer pattern I’ll add a word count that uses it. The word count component will take this observer and bring it all together.
To initialize the EventObserver do:
class EventObserver {
constructor() {
this.observers = [];
}
}

Start with an empty list of observed events, and do this for every new instance. From now on, let’s add more methods inside EventObserver to flesh out the design pattern.
The Subscribe Method
To add new events do:
subscribe(fn) {
this.observers.push(fn);
}

Grab the list of observed events and push a new item to the array. The list of events is a list of callback functions.
One way to test this method in plain JavaScript is as follows:
// Arrange
const observer = new EventObserver();
const fn = () => {};

// Act
observer.subscribe(fn);

// Assert
assert.strictEqual(observer.observers.length, 1);

I use Node assertions to test this component in Node. The exact same assertions exist as Chai assertions too.
Note the list of observed events consists of humble callbacks. We then check the length of the list and assert that the callback is on the list.
The Unsubscribe Method
To remove events do:
unsubscribe(fn) {
this.observers = this.observers.filter((subscriber) => subscriber !== fn);
}

The web can seem fast moving. New frameworks, tools, and even languages come and go. Yet many developers feel that they have to move as fast as their slowest user. New browsers are ‘evergreen’ — they auto-update unseen in the background without asking for permission, and they’re making leaps and bounds in terms of progressing new APIs.
Yet even modern browsers implement features at different times. It’s frustrating to read about the bleeding-edge of modern development only to think it’s all unusable for years to come. Maybe you’ve looked through your site’s analytics and spotted users still on IE9? Should you code like it’s 2011 or delegate everything to jQuery or some framework? There is another option. Enter the polyfill.
What Are Polyfills and Why Do We Need Them?
Remy Sharp coined the term in a 2009 book and blog post. If the feature exists in the browser, the polyfill lets the browser do its thing, if not, the polyfill steps in to plug the missing functionality. They fill in the holes of older browsers, the missing features we want to use today. It replicates a native API with non-native code.
What Missing Features Are We Talking About?
In 2009, the 5th Edition of ECMAScript landed. It was a large and radical step forward for the language. ECMAScript 2015 delivered a similarly seismic update. Going forward, improvements to the language will be incremental, happening on a yearly basis. It’s an exciting time, with new features continually making their way into the language. Besides the core language itself, there’s also the DOM and the various APIs of the web platform.
To highlight the discrepancy between a modern and a legacy browser, here’s a comparison of the latest Chrome release versus Internet Explorer 9 (which some companies still sadly mandate support for). And here’s a table showing support for ECMAScript 6. The second table only goes as far back as IE 11, which as you can see supports practically zero ES6 features. That’s a lot of missing features…
Polyfills vs Transpiling
So clearly, from looking at the above tables, we need to transpile our code. It takes your shiny new syntax and spits out plain old-fashioned ECMAScript 5. If you want to utilize arrow functions, async/await, rest and spread parameters, classes, et al in your code, you need to transpile your ES6 code into ES5 with a tool such as Babel.
However, you can’t polyfill the syntax of JavaScript. While Babel will take your arrow functions and turn them into regular functions, a polyfill will add methods to the global scope and to native prototypes. Babel offers its own ES6 polyfill that, in the words of the Babel website, offers “new built-ins like Promise or WeakMap, static methods like Array.from or Object.assign, instance methods like Array.prototype.includes, and generator functions."
So the Babel polyfill can give us all the ES6 features we want. But there’s plenty it leaves out. Maybe you add and remove classes with the classList API or conduct media queries with matchMedia, but you still need to support IE9. Luckily there’s a service that provides everything the Babel polyfill covers, and a whole lot more.
Continue reading %A Beginner’s Guide to HTML5 Cross-Browser Polyfills%

When jQuery was released, one of the main reasons behind its meteoric rise to popularity was the ease with which it could select DOM elements, traverse them and modify their content. But that was way back in 2006. In those days we were stuck with Internet Explorer 7 and ECMAScript 5 was still a couple of years off.

Luckily, a lot has changed since then. Browsers have become considerably more standards compliant and native JavaScript has improved in leaps and bounds. And as things have improved, we have seen people questioning whether we still need jQuery. I’m not going to get into that argument here, rather I’d like to offer some food for thought, as I present six native DOM manipulation methods which were inspired by this great library. These are as follows:

append()
prepend()
after()
before()
replaceWith()
remove()

In this article I want to examine the similarities and the differences between these native DOM manipulation methods and their jQuery counterparts. Then hopefully, the next time you find yourself including jQuery for the sake of a convenience method or two, you might opt to embrace the power of vanilla JavaScript instead.
1. append()
The append method performs an insertion operation, that is, it adds nodes to the DOM tree. As the name indicates, it appends the passed arguments to the list of children of the node on which it is invoked. Consider the following example:
const parent = document.createElement(‘div’)
const child1 = document.createElement(‘h1’)
parent.append(child1)
parent.outerHTML
//

At this point you would be forgiven for asking how this differs from the native appendChild method. Well, a first distinction is that append() can take multiple arguments at once, and the respective nodes will be appended to the list of children, just like the jQuery append method. Continuing the previous snippet:
const child3 = document.createElement(‘p’)
const child4 = document.createElement(‘p’)
const child5 = document.createElement(‘p’)
parent.append(child3, child4, child5)
parent.outerHTML
/* Outputs:
<div>
<h1></h1>
<h2></h2>
<p></p>
<p></p>
<p></p>
</div>
*/

Furthermore, an argument can be even a string. So, while with appendChild() a rather verbose syntax must be employed:
parent.appendChild(document.createTextNode(‘just some text’))

The string is converted to a Text node, so any HTML is not parsed:
parent.append(‘<p>foo</p>’)
parent.outerHTML
/* Outputs:
<div>
<h1></h1>
<h2></h2>
<p></p>
<p></p>
<p></p>
just some text
<p&gt;foo&lt;/p&gt;
</div>
*/

This is in contrast to the jQuery method, where strings of markup are parsed and the corresponding nodes are generated and inserted into the DOM tree.
As is usually the case, if the appended node it is already present in the tree, it is first removed from its old position:
const myParent = document.createElement(‘div’)
const child = document.createElement(‘h1’)
myParent.append(child)
const myOtherParent = document.createElement(‘div’)
const myOtherParent.append(child)
myOtherParent.outerHTML
// <div><h1></h1></div>

myParent.outerHTML
// <div></div>”

A final difference between append() and appendChild() is that the latter returns the appended node, whereas the former returns undefined.
2. prepend()
The prepend method is very similar to append(). Children are added, but this time they are prepended to the list of children of the node on which the method is called, just before the first child:
const parent = document.createElement(‘div’)
const child1 = document.createElement(‘p’)
parent.prepend(child1)
parent.outerHTML
// <div><p></p></div>

The return value of the method is undefined. The corresponding jQuery method is prepend().
3. after()
The after method is another insertion method, but this time it must be called on a child node, that is, a node with a definite parent. Nodes are inserted as adjacent siblings, as can be seen in the following example:
const parent = document.createElement(‘ul’)
const child = document.createElement(‘li’)
child.append(‘First item’)
parent.append(child)
child.after(document.createElement(‘li’))
parent.outerHTML
// <ul><li>First item</li><li></li></ul>

The return value is undefined and in jQuery the similar operation is after().
4. before()
The before method is similar to after(), but now the nodes are inserted before the child node:
const parent = document.createElement(‘ul’)
const child = document.createElement(‘li’)
child.append(‘First item’)
parent.append(child)

Working with dates in JavaScript is a pain. Native date methods are often verbose and occasionally inconsistent — something which also makes them error-prone. But good news is at hand. There are several libraries that exist to take the pain out of date manipulation. These libraries are to JavaScript dates, what jQuery is to the native DOM API.
Let me give you an example. This is the accepted answer to a Stack Overflow question asking how to get last day of the month:
var t = new Date();
alert( new Date(t.getFullYear(), t.getMonth() + 1, 0, 23, 59, 59) );

Of course that works, but it’s not immediately obvious what the numbers after getMonth represent. Now contrast that with the considerably more readable:
const today = new Date();
console.log( lastDayOfMonth(today) );

That lastDayOfMonth method is one provided by date-fns, a self-proclaimed comprehensive toolset for manipulating JavaScript dates in the browser and Node.js.
In this article I’m going to show you how to get up and running with date-fns. After reading you’ll be able to drop it into your projects and take advantage of its many helper methods to manipulate dates with ease. This will make code like t.getMonth() + 1, 0, 23, 59, 59 a thing of the past.
So, Why Not Just Use Moment.js?
The elephant in the room is Moment.js. This library has undoubtedly become the de-facto standard for working with dates in JavaScript. So why not use that? Why do we need another JavaScript date library?
Well, according to Sasha Koss, the creator of date-fns, Moment.js has a few inherent problems which motivated him to create date-fns. Sasha expands on what these problems are on the project’s GitHub page, but in a nutshell:

Moment.js is mutable which can cause bugs.
It has a complex OOP API (which doubles the mutability problem).
It has a performance overhead due to the complex API.
Its build size is large when used with Webpack, as locale files are included as part of the bundle.

Let’s contrast that with date-fns (taken from the project’s homepage):

Date-fns is immutable, always returning a new date instead of changing the one you pass in.
It has a simple API. You always have one function that does one thing.
It is fast. You can be sure that your users will have the best user experience.
It is the perfect companion for Webpack. With the function-per-file style you can pick just what you need and stop bloating your project with useless functionality.

For me, the feature that makes it shine is its ease of use. When using it on a web-based project, you can just grab date-fns from a CDN, drop it into your page and profit. More about that next…
Installation
There are a variety of ways to install the library.
It’s available as an npm package:
npm install date-fns –save

With the introduction of ES2015+, and as transpilation has become commonplace, many of you will have come across newer language features, either in real code or tutorials. One of these features that often has people scratching their heads when they first come across them are JavaScript decorators.
Decorators have become popular thanks to their use in Angular 2+. In Angular, decorators are available thanks to TypeScript, but they are due to be part of the ES2017 language update due out later this year. Let’s take a look at what decorators are, and how they can be used to make your code cleaner and more easily understandable.
Note: If you’re more of a video person, why not sign up for SitePoint Premium and check out some of our popular JavaScript courses?
What is a Decorator?
In its simplest form, a decorator is simply a way of wrapping one piece of code with another – literally “decorating" it.
This is a concept you might well have heard of previously as "Functional Composition", or "Higher-Order Functions".
This is already possible in standard JavaScript for many use cases, simply by calling one one function to wrap another:
function doSomething(name) {
console.log(‘Hello, ‘ + name);
}

This example produces a new function – in the variable wrapped – that can be called exactly the same way as the doSomething function, and will do exactly the same thing. The difference is that it will do some logging before and after the wrapped function is called.
doSomething(‘Graham’);
// Hello, Graham
wrapped(‘Graham’);
// Starting
// Hello, Graham
// Finished

How to use JavaScript Decorators?
Decorators use a special syntax in ES2017, whereby they are prefixed with an @ symbol and placed immediately before the code being decorated.

Note: At the time of writing, the decorators are currently in "Stage 2 Draft" form, meaning that they are mostly finished but still subject to changes.

It is possible to use as many decorators on the same piece of code as you desire, and they will be applied in the order that you declare them.
For example:
@log()
@immutable()
class Example {
@time(‘demo’)
doSomething() {

}
}

This defines a class and applies three decorators: two to the class itself and one to a property of the class:

@log could log all access to the class.
@immutable could make the class immutable – maybe it calls Object.freeze on new instances.
@time will record how long a method takes to execute and log this out with a unique tag.

At present, using decorators requires transpiler support, since no current browser or Node release has support for them yet.
If you are using Babel, this is enabled simply by using the transform-decorators-legacy plugin.

Note: the use of the word "legacy" in this Plugin is because it supports the way that Babel 5 handled Decorators, which might well be different to the final form when they are standardized.

Why use Decorators?
Whilst functional composition is already possible in JavaScript, it is significantly more difficult – or even impossible – to apply the same techniques to other pieces of code (e.g. classes and class properties).
The ES2017 draft adds support for class and property decorators that can be used to resolve these issues, and future JavaScript versions will probably add decorator support for other troublesome areas of code.
Decorators also allow for a cleaner syntax for applying these wrappers around your code, resulting in something that detracts less from the actual intention of what you are writing.
Different Types of Decorator
At present, the only types of decorator that are supported are on classes and members of classes. This includes properties, methods, getters, and setters.
Decorators are actually nothing more than functions that return another function, and that are called with the appropriate details of the item being decorated. These decorator functions are evaluated once when the program first runs, and the decorated code is replaced with the return value.
Continue reading %Exploring ES2017 Decorators in JavaScript%

Event bubbling is a term you might have come across on your JavaScript travels. It relates to the order in which event handlers are called when one element is nested inside a second element, and both elements have registered a listener for the same event (a click, for example).
But event bubbling is only one piece of the puzzle. It is often mentioned in conjunction with event capturing and event propagation. And a firm understanding of all three concepts is essential for working with events in JavaScript — for example if you wish to implement the event delegation pattern.
In this post I will explain each of these terms and demonstrate how they fit together. I will also show you how a basic understanding of JavaScript event flow can give you fine-grained control over your application. Please note that this is not a primer on events, thus a familiarity with the topic is assumed. If you’d like to learn more about events in general, why not check out our book: JavaScript: Novice to Ninja.
What is the Event Propagation?
Let’s start with event propagation. This is the blanket term for both event bubbling and event capturing. Consider the typical markup to build a list of linked images, for a thumbnails gallery for example:

A click on an image does not only generate a click event for the corresponding IMG element, but also for the parent A, for the grandfather LI and so on, going all the way up through all the element’s ancestors, before terminating at the window object.
In DOM terminology, the image is the event target, the innermost element over which the click originated. The event target, plus its ancestors, from its parent up through to the window object, form a branch in the DOM tree. For example, in the image gallery, this branch will be composed of the nodes: IMG, A, LI, UL, BODY, HTML, document, window.

Note that window is not actually a DOM node but it implements the EventTarget interface, so, for simplicity, we are handling it like it was the parent node of the document object.

This branch is important because it is the path along which the events propagate (or flow). This propagation is the process of calling all the listeners for the given event type, attached to the nodes on the branch. Each listener will be called with an event object that gathers information relevant to the event (more on this later).
Remember that several listeners can be registered on a node for the same event type. When the propagation reaches one such node, listeners are invoked in the order of their registration.
It should also be noted that the branch determination is static, that is, it is established at the initial dispatch of the event. Tree modifications occurring during event processing will be ignored.
The propagation is bidirectional, from the window to the event target and back. This propagation can be divided into three phases:

From the window to the event target parent: this is the capture phase
The event target itself: this is the target phase
From the event target parent back to the window: the bubble phase

What differentiates these phases is the type of listeners that are called.
The Event Capture Phase
In this phase only the capturer listeners are called, namely, those listeners that were registered using a value of true for the third parameter of addEventListener:
el.addEventListener(‘click’, listener, true)

If this parameter is omitted, its default value is false and the listener is not a capturer.
So, during this phase, only the capturers found on the path from the window to the event target parent are called.
Continue reading %What Is Event Bubbling in JavaScript? Event Propagation Explained%

When adding a navigation menu to a webpage, there are a lot of things to take into consideration. For example where to position it, how to style it, how to make it responsive. Or maybe you want to add some kind of animation to it (tastefully, of course). At this point you might be tempted to grab a jQuery plugin which does most of that for you. But that needn’t be! It’s actually pretty simple to create your own solution in a few lines of code.
In this post, I will demonstrate how to create an animated, sticky navigation menu with vanilla JavaScript, CSS and HTML. The final product will slide up out of your way as you scroll down the page, then slide back into view (with a stylish see-through effect) when you scroll back up. This is a technique used by such popular sites, such as Medium and Hacker Noon.
After reading you’ll be able to employ this technique in your own designs, hopefully to great effect. There’s a demo at the end of the article for the impatient.
The Basic HTML Structure
The following is the skeleton HTML code that we will be working with. Nothing too exciting going on here.

If you have an array of objects that you need to sort into a certain order, the temptation might be to reach for a JavaScript library. Before you do however, rember that you can do some pretty neat sorting with the native Array.sort function. In this article I’ll show you how to sort an array of objects in JavaScript with no fuss or bother.
To follow along with this article, you will need a knowledge of basic JavaScript concepts, such as declaring variables, writing functions, and conditional statements. I’ll also be using ES6 syntax. You can get a refresher on that here: https://www.sitepoint.com/tag/es6/
Basic Array Sorting
By default, the JavaScript Array.sort function converts each element in the array to be sorted, into a string, and compares them in Unicode code point order.
const foo = [9, 2, 3, ‘random’, ‘panda’];
foo.sort(); // returns [ 2, 3, 9, ‘panda’, ‘random’ ]

You may be wondering why 30 comes before 4… not logical huh? Well, actually it is. This happens because each element in the array is first converted to a string, and “30" comes before "4" in Unicode order.
It is also worth noting that unlike many other JavaScript array functions, Array.sort actually changes, or mutates the array it sorts.
const baz = [‘hello world’, 31, 5, 9, 12];
baz.sort(); // baz array is modified
console.log(baz); // shows [12, 31, 5, 9, "hello world"]

Try it out
JS Bin on jsbin.com
Using Array.sort alone would not be very useful for sorting an array of objects, thankfully the function takes an optional compareFunction parameter which causes the array elements to be sorted according to the return value of the compare function.
Continue reading %Quick Tip: How to Sort an Array of Objects in JavaScript%