Monthly Archives: August 2015

What happened to Web Components?

By Axel Rauschmayer

Three years ago, there was a lot of excitement surrounding Web Components: everybody talked about them, the frameworks Ember and Angular planned to integrate them or even be based on them, etc.

By now, that excitement seems to have died down. This blog post examines what happened to Web Components. Spoiler: they are alive and well and slowly being adopted across browsers.

Refresher: Web Components

Web Components are a suite of specifications that help with implementing custom HTML elements:

  • Custom elements: an API for registering your own implementations for HTML elements.
  • Shadow DOM: Encapsulates and hides the innards of a custom element inside a nested document. The most important part of Web Components and hardest to polyfill.
  • Templates: enable you to store HTML templates inside an HTML document without interpreting their content (no loading of images etc.).
  • HTML Imports: let you import other HTML documents into the current one. That way, HTML documents become bundles of HTML, CSS and JavaScript. You need such bundles to distribute custom elements and all of their dependencies.

For more information on how Web Components work, you can read the introduction “Bringing componentization to the web: An overview of Web Components” by Travis Leithead and Arron Eicholz.

Status quo

For a long time, it was mainly Google (and, to some degree, Mozilla) that pushed Web Components. In recent months, other parties became more involved. There were two face-to-face meetings on 2015-04-24 and on 2015-07-21 that were attended by employees from Mozilla, Microsoft, Google, Apple and others. During those meetings, two Web Component specifications moved closer to a cross-browser consensus:

  • Shadow DOM: There is now broad agreement on how to standardize the Shadow DOM, which is great, because, as mentioned before, it is the spec that is most difficult to polyfill.

  • Custom elements: Everyone agrees that custom elements are important, but getting the details right is difficult, especially when to activate a custom implementation – while creating the custom element in the DOM or later.

HTML Imports are still controversial, because there is much overlap with ES6 module loading. Especially Mozilla and Microsoft argue that further work on HTML Imports should wait until ES6 module loading is finished.

More information:

Web Components versus React

When Sebastian Markbage (one of React’s creators) was asked about Web Components, he answered:

Sebastian: We’re not going to use it at all at Facebook. We’re not going to build React on it because there’s a strong model difference – imperative in Web Components to declarative in React. Web Components doesn’t have an idiomatic way to define things like where events go. How do you pass data when everything is a string? We see it more as an interop layer that lets various frameworks talk to each other.

In talking to the Atom team, this doesn’t solve different framework idioms as it doesn’t have an opinion on how they relate.

This sounds like React and Web Components are at odds with each other. However, in the talk “The complementarity of React and Web Components”, Andrew Rota disagrees:

  • Web Components can be used as leaves in the tree of React Components, instead of native DOM elements.

  • React is getting better at supporting Web Components:

    • Custom elements already work (elements with lowercase names are interpreted as DOM, replacing a whitelist of names).
    • Support for custom attributes and custom events is work in progress.
  • Andrew argues that Web Components should be:

    • Small: atomic, not compound. React and other frameworks can be used to assemble Web Components.
    • Completely encapsulated: For example, a Web Component should not put script tags into the surrounding document.
    • As stateless as possible: avoid internal state, use events to communicate changes.

      These rules for designing Web Components help React, but they make sense in general.

  • Using React inside a Web Component makes less sense, it goes against Web Components being as minimal as possible.

Further information

The Web Platform Podcast episode 54 (2015-07-28) asks a panel of experts: “Are Web Components Ready Yet?” (80min video). Watch that video to get more information and context on Web Components.

Mentioned in the podcast, the work of the CSS Houdini Group will help with implementing Web Components in the future:

The objective of the CSS-TAG [Technical Architecture Group] Houdini Task Force (CSS Houdini) is to jointly develop features that explain the “magic” of Styling and Layout on the web.

Styling and layouting are currently mostly black boxes. The Houdini Group plans to expose the internals of those boxes and to let you customize what is going on there.

Source:: 2ality

Logging variables via an ES6 tagged template

By Axel Rauschmayer

This blog post shows how you can use a tagged template to log variables more efficiently.

In order to understand it, you should be familiar with ECMAScript 6 template literals and tagged templates. For an introduction, consult chapter “Template literals and tagged templates” of “Exploring ES6”.

The problem

If you want to log both name and value of a variable in a traditional manner, there is redundancy:

    let tmp = 123;
    console.log('tmp='+tmp);
    // Output:
    // tmp=123

Even a template literal doesn’t help:

    console.log(`tmp=${tmp}`);

The solution: a tagged template

The solution is to implement a custom tag function called vars. A template tagged with that function eliminates the redundancy:

    console.log(`${{tmp}}`)

The object literal {tmp} inside the substitution ${} is an abbreviation for (a so-called “property value shorthand”):

    {tmp: tmp}

Accordingly, the tag function vars expects its substitutions to be objects:

    function vars(templateStrings, ...substitutions) {
        let result = templateStrings[0];
        for (let [i, obj] of substitutions.entries()) {
            let propKeys = Object.keys(obj);
            for (let [j, propKey] of propKeys.entries()) {
                if (j > 0) {
                    result += ', ';
                }
                result += propKey+'='+obj[propKey];
            }
        }
        return result;
    }

You can put multiple variable names inside a substitution:

    let foo = 123;
    let bar = 'abc';
    let baz = true;
    console.log(vars`Variables: ${{foo, bar, baz}}`);
    
    // Output:
    // Variables: foo=123, bar=abc, baz=true

Source:: 2ality

How to Control YouTube’s Video Player with JavaScript

By Danny Markov

controlling-youtubes-player

YouTube has become the standard way for delivering high quality video on the web. Sometimes, when you embed a video in your web application or landing page, you need a great deal of control on what and how is displayed. This is why we are going to show you how you can use the YouTube JavaScript Player API.

Initializing the player

The first step is to add a placeholder for the player and include the YouTube API.

<div id="video-placeholder"></div>

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

When the API is fully loaded, it looks for a global function called onYouTubeIframeAPIReady() which you should define. Inside it we will create a new instance of YouTube player. The first argument is the id of an HTML element we want to be replaced by the player, in our case that’s video-placeholder. The second one is an object containing the player options:

  • The width and height of the player. These can be overwritten by applying CSS to #video-placeholder.
  • The id of the video we want to be embedded when the player loads. You can get this id from any YouTube link by taking the string after ?v= (e.g. youtube.com/watch?v=WwoKkq685Hk)
  • The playerVars object is a set of parameters. We made the color of the player white and created a playlist by providing two additional videos ids, separated by a coma. You can see a list of all available properties here.
  • The events object consists of event listeners and the functions they call. The API passes down an event object as the only attribute, containing the target and data. You can read more about events here.

The whole code look something like this:

var player;

function onYouTubeIframeAPIReady() {
    player = new YT.Player('video-placeholder', {
        width: 600,
        height: 400,
        videoId: 'Xa0Q0J5tOP0',
        playerVars: {
            color: 'white',
            playlist: 'taJ60kskkns,FG0fTKAqZ5g'
        },
        events: {
            onReady: initialize
        }
    });
}

The initialize() function will be called when the player fully loads. It will start an interval, updating some of our controls every second.

function initialize(){

    // Update the controls on load
    updateTimerDisplay();
    updateProgressBar();

    // Clear any old interval.
    clearInterval(time_update_interval);

    // Start interval to update elapsed time display and
    // the elapsed part of the progress bar every second.
    time_update_interval = setInterval(function () {
        updateTimerDisplay();
        updateProgressBar();
    }, 1000)

}

Displaying current time and video duration

This is done by the updateTimerDisplay(), one of the function called every second. It takes advantage of the API’s methods to give us adequate information about the video length.

// This function is called by initialize()
function updateTimerDisplay(){
    // Update current time text display.
    $('#current-time').text(formatTime( player.getCurrentTime() ));
    $('#duration').text(formatTime( player.getDuration() ));
}

function formatTime(time){
    time = Math.round(time);

    var minutes = Math.floor(time / 60),
    seconds = time - minutes * 60;

    seconds = seconds < 10 ? '0' + seconds : seconds;

    return minutes + ":" + seconds;
}

Methods are called using the player object we created in the begging. We can get how many seconds into the video we are in with getCurrentTime(), and the total duration of the video with getDuration(). Both function will return second which we format correctly to look like time and then write into the DOM.

Progress Bar

This is done using the player.seekTo(sec) function, which jumps the video to the seconds provided in the parameter.

To demonstrate this we’ve made our own version of YouTube’s progress bar, using an input field of type range. When we click anywhere on it, we take the inputs value, witch gives us a percentage. We then use this percentage to calculate what progress we want made to the video and skip to the according seconds.

$('#progress-bar').on('mouseup touchend', function (e) {

    // Calculate the new time for the video.
    // new time in seconds = total duration in seconds * ( value of range input / 100 )
    var newTime = player.getDuration() * (e.target.value / 100);

    // Skip video to new time.
    player.seekTo(newTime);

});

The code above allows us to control the video, but we also want the progress bar to move automatically as the video progresses. To understand how we do this, go back to the initialize() function and more specifically its every-second interval and updateProgressBar().

// This function is called by initialize()
function updateProgressBar(){
    // Update the value of our progress bar accordingly.
    $('#progress-bar').val((player.getCurrentTime() / player.getDuration()) * 100);
}

Playback Controls

Nothing out of the ordinary here. Just make two buttons and call the needed method on click.

$('#play').on('click', function () {
    player.playVideo();
});

$('#pause').on('click', function () {
    player.pauseVideo();
});

Sound Options

We can create a mute toggle button using the provided getter and setter methods of the player.

$('#mute-toggle').on('click', function() {
    var mute_toggle = $(this);

    if(player.isMuted()){
        player.unMute();
        mute_toggle.text('volume_up');
    }
    else{
        player.mute();
        mute_toggle.text('volume_off');
    }
});

If we want to set the volume using a percentage we can use a number input field and the setVolume() method. It will automatically validate the provided parameter, so we don’t have to worry about passing it floating values or numbers out of the [0 : 100] interval.

$('#volume-input').on('change', function () {
    player.setVolume($(this).val());
});

Other Player Settings

Changing Playback Speed

The player.setPlaybackRate() method expects one of the following as its parameter:

  • 0.25
  • 0.5
  • 1
  • 1.5
  • 2

Create a element in the HTML and set the speeds as it children. User interaction with the select will result in change of the speed rate only for the currently playing video and will be reset to the default (speed of 1) when the next one starts.

$('#speed').on('change', function () {
    player.setPlaybackRate($(this).val());
});

Changing Video Quality

Altering the video quality works in a very similar way to altering the speed. The method for this is setPlaybackQuality() and the argument it expects is one of these strings:

  • highres
  • hd1080
  • hd720
  • large
  • medium
  • small

Note that this function only suggest what quality should be used as that highly depends on the internet connection and video itself.

$('#quality').on('change', function () {
    player.setPlaybackQuality($(this).val());
});

Playlists

We can play the next or previous video in a playlist using these methods form the API.

$('#next').on('click', function () {
    player.nextVideo()
});

$('#prev').on('click', function () {
    player.previousVideo()
});

If you want to play a specific video from the playlist, use player.playVideoAt(index), where index is an integer specifying which video to play, 0 being the first one.

Queue Video Dynamically

The last thing we are going to demonstrate, is how to dynamically add new videos to the player. If you check our our demo, in the bottom you’ll see three thumbnails for cat videos. We added their YouTube links as data-attributes and when any of them gets clicked, the chosen video will be loaded into the player.

$('.thumbnail').on('click', function () {

    var url = $(this).attr('data-video-id');

    player.cueVideoById(url);

});

Conclusion

This wraps up our tutorial! We hope that you found this tutorial useful. If you wish to learn more about the YouTube API, check out these resources:

  • YouTube Iframe Player API Reference – here.
  • YouTube Player supported parameters – here.
  • YouTube Developers Live: Embedded Web Player Customization – here.

Source:: Tutorialzine.com

Is “Isomorphic JavaScript” a good term?

By Axel Rauschmayer

A recent trend in the web development world is to use JavaScript on the server to assemble pages there, with the same code that is used to manage them in the client. That lets you initially see content faster, especially on mobile devices and helps with search engines.

How are we supposed to call code that runs on either server or client? Michael Jackson doesn’t like a recent proposal:

So Charlie Robbins suggested that the term “Isomorphic JavaScript” might be used to describe JavaScript code that “can execute both on the client and the server”. And nobody knew what the hell it meant, but now instead of just writing JavaScript the people were writing Isomorphic JavaScript.

Michael proposes the term “Universal JavaScript”. In a comment to his blog post, Matti Schneider defends “Isomorphic JavaScript”:

No. “Isomorphic”, in terms of topology, describes the relationship between a transformation applied to an element in one set, and another transformation applied to another element in another set, and how these transformations are “as comparable” as the sets on which they are applied are comparable.

I like that “Universal JavaScript” is descriptive, but it is also a relatively generic and bland term. Additionally, the adjective “universal” has been used for modules (Universal Module Definition).

Can we come up with something that has more bite? Rodrigo Medeiros proposes “Full Stack JavaScript”. Any other ideas? Maybe “Vertical JavaScript”? But that is less descriptive than “Universal JavaScript” and “Full Stack JavaScript”.

Source:: 2ality

Five little-known facts about ES5 object literals

By Axel Rauschmayer

This blog post describes five little known facts about ECMAScript 5 (ES5) object literals:

  1. ECMAScript 5 has getters and setters
  2. Trailing commas are legal
  3. You often don’t have to quote property keys
  4. You can use reserved words as unquoted property keys
  5. Using objects as dictionaries is surprisingly tricky

ECMAScript 5 has getters and setters

ECMAScript 6 supports getters and setters. You can create them either via property descriptors or via object literals:

    var obj = {
        get foo() {
            return Math.random();
        },
        set foo(value) {
            console.log('SET foo = '+value);
        },
    };

Let’s use obj in a REPL:

    > obj.foo
    0.6029663002118468
    > obj.foo
    0.99780507478863
    > obj.foo = 123;
    SET foo = 123

Trailing commas are legal

Starting with ES5, it is legal to put a comma after the last property. That helps whenever you want to rearrange properties, especially if there is one property per line:

    var translations = {
        yes: 'ja',
        no: 'nein',
        perhaps: 'vielleicht',
    };

You often don’t have to quote property keys

In object literals, a property name is either:

  • An identifier
  • A string literal
  • A numeric literal

String literals as property names

You can use arbitrary text as a property key if you quote it:

    var obj = {
        '#§$%': true,
        " tn": true,
    };

Identifiers as property names

If the property key is an identifier, it doesn’t have to be quoted in object literals. Identifiers must start with a Unicode letter, an underscore or a dollar sign.

The ES5 spec describes Unicode letters as:

Any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”, “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”.

Thus, the following property names don’t have to be quoted:

    var obj = {
        π: true,
        привет: true,
        café: true,
        $$$: true,
    };

Numbers as property names

You don’t have to quote property names in object literals if they are numeric literals. Numeric literals include the hexadecimal notation, but not a leading minus (-, a dash), because that is not part of a numeric literal in JavaScript, it is an operator.

    var obj = {
        1e2: true,
        1e-2: true,
        .234: true,
        0xFF: true,
    };

The numbers represented by these numeric literals are converted to strings before they become property keys:

    > Object.keys(obj)
    [ '100', '255', '0.01', '0.234' ]

In contrast to identifiers, numeric literals cannot be used after the dot operator:

    > obj.0xFF
    SyntaxError: Unexpected token
    > obj[0xFF]
    true

Recommendations

My recommendations (for ES5 and later):

  • For objects holding code, I only use identifiers as property names and never quote.
  • For objects holding data, I often quote property names.
  • The JSON data format requires you to quote property names – with double quotes!

        > JSON.parse('{ hello: 3 }')
        SyntaxError: Unexpected token h
        > JSON.parse("{ 'hello': 3 }")
        SyntaxError: Unexpected token '
        > JSON.parse('{ "hello": 3 }')
        { hello: 3 }
    

You can use reserved words as unquoted property keys

In ECMAScript 3, you had to quote reserved words such as instanceof or new if you wanted to use them as property names. In ECMAScript 5, that is not necessary, anymore:

    > var obj = { new: 123 };
    > obj.new
    123

Using objects as dictionaries is surprisingly tricky

ECMAScript 5 does not have a built-in data structure for dictionaries (which are also known as maps). Therefore, the programming construct object is a abused as a dictionary from strings to arbitrary values. In addition to keys having to be strings, that causes three problems.

First, You cannot invoke methods on objects-as-dictionaries. The name of any method you invoke might be a key in the data:

    > var data = { hasOwnProperty: true };
    > data.hasOwnProperty('someKey')
    TypeError: boolean is not a function

Second, you must be careful about inheritance. Getting the value of a property and the in operator include inherited properties, which is not what you want in this case:

    > var data = {}; // empty dictionary
    > 'toString' in data
    true
    > data.toString
    [Function: toString]

Third, the property key __proto__ triggers special behavior in many engines, which is why you can’t use it as a key for data. One work-around is to escape such keys (and their escaped versions):

    function escapeKey(key) {
        // Escape '__proto__', its escaped version etc.
        if (key.indexOf('__proto__') === 0) {
            return key+'%';
        } else {
            return key;
        }
    }
    function getValue(obj, key) {
        return obj[escapeKey(key)];
    }
    function setValue(obj, key, value) {
        obj[escapeKey(key)] = value;
    }

The dict pattern

An object works best as a dictionary if its prototype is null (the so-called dict pattern). That fixes problem 2:

    > var dict = Object.create(null);
    > dict.foo = 123;
    > 'toString' in dict
    false
    > dict.toString
    undefined
    > 'foo' in dict
    true

Problems 1 and 3 remain: you can’t invoke any methods on dict (it doesn’t inherit any, anyway, because it has no prototypes) and you must escape '__proto__'.

ECMAScript 6 has the built-in data structure Map which you should always use for data, especially if it has arbitrary keys.

More information on the dict pattern: section “The dict Pattern: Objects Without Prototypes Are Better Maps” in “Speaking JavaScript”.

Further reading on object literals

Source:: 2ality

Converting ES6 Maps to and from JSON

By Axel Rauschmayer

When you have key-value data whose keys you don’t know in advance, it’s generally better to store it in an ES6 Map than in an object. But how do you convert Maps to and from JSON? This blog post tells you.

Background knowledge:

  • More information on ES6 Maps: chapter “Maps and Sets” in “Exploring ES6”.
  • More information on JSON: chapter “JSON” in “Speaking JavaScript”.

Arbitrary Maps as JSON via Arrays of pairs

If a Map contains arbitrary (JSON-compatible) data, we can convert it to JSON by encoding it as an Array of key-value pairs (2-element Arrays).

Converting a Map to and from an Array of pairs

The spread operator lets you convert a Map to an Array of pairs:

    > let myMap = new Map().set(true, 7).set({foo: 3}, ['abc']);
    > [...myMap]
    [ [ true, 7 ], [ { foo: 3 }, [ 'abc' ] ] ]

The Map constructor lets you convert that an Array of pairs to a Map:

    > new Map([[true, 7], [{foo: 3}, ['abc']]])
    Map {true => 7, Object {foo: 3} => ['abc']}

The conversion to and from JSON

Let’s use this knowledge to convert any Map with JSON-compatible data to JSON and back:

    function mapToJson(map) {
        return JSON.stringify([...map]);
    }
    function jsonToMap(jsonStr) {
        return new Map(JSON.parse(jsonStr));
    }

The following interaction demonstrates how these functions are used:

    > let myMap = new Map().set(true, 7).set({foo: 3}, ['abc']);
    > mapToJson(myMap)
    '[[true,7],[{"foo":3},["abc"]]]'
    > jsonToMap('[[true,7],[{"foo":3},["abc"]]]')
    Map {true => 7, Object {foo: 3} => ['abc']}

String Maps as JSON via objects

Whenever a Map only has strings as keys, you can convert it to JSON by encoding it as an object.

Converting a string Map to and from an object

The following two function convert string Maps to and from objects:

    function strMapToObj(strMap) {
        let obj = Object.create(null);
        for (let [k,v] of strMap) {
            // We don't escape the key '__proto__'
            // which can cause problems on older engines
            obj[k] = v;
        }
        return obj;
    }
    function objToStrMap(obj) {
        let strMap = new Map();
        for (let k of Object.keys(obj)) {
            strMap.set(k, obj[k]);
        }
        return strMap;
    }

Let’s use these two functions:

    > let myMap = new Map().set('yes', true).set('no', false);
    > strMapToObj(myMap)
    { yes: true, no: false }
    > objToStrMap({yes: true, no: false})
    [ [ 'yes', true ], [ 'no', false ] ]

The conversion to and from JSON

With these helper functions, the conversion to JSON works as follows:

    function strMapToJson(strMap) {
        return JSON.stringify(strMapToObj(strMap));
    }
    function jsonToStrMap(jsonStr) {
        return objToStrMap(JSON.parse(jsonStr));
    }

This is an example of using these functions:

    > let myMap = new Map().set('yes', true).set('no', false);
    > strMapToJson(myMap)
    '{"yes":true,"no":false}'
    > jsonToStrMap('{"yes":true,"no":false}');
    Map {'yes' => true, 'no' => false}

Source:: 2ality

The 40 Best Free WordPress Themes, Plugins and Tips For Summer 2015

By Danny Markov

best-wordpress-themes-plugins-tips-summer-2015

WordPress is a powerful tool for building everything from a simple blog to a full-blown ecommerce website. There is a huge community of developers which is constantly creating new themes and plugins and writing articles about it. Here are some of the best resources that we’ve come across this summer.

Themes

1. Ambition

A trendy theme rocking a clean, responsive flat design. It works equally well both for landing pages and for full featured blogs. Ambition offers many customization options such as different page and post templates, widget areas and sidebars that will help you create the perfect layout for your needs.

Ambition Demo

2. Perth

A business theme targeted towards companies and freelancers. It comes with two page templates, one for a front page and another for a full width layout. The theme gives users the option to present professional information via custom, built-in widgets for employees, services, skills, and more.

Perth Demo

Perth Demo

3. Stone

A Bootstrap powered theme for interior and furniture design. It’s packed with awesome features including a slider, a parallax scrolling effect, and cool JavaScript animations. A page created with Stone, looks astonishing and can be easily differentiated from the average WordPress website.

Stone Demo

Stone Demo

4. Optimizer

A heavily customizable theme with an advanced options panel and 12 unique presets, all interchangeable with the click of a button. The theme is fully responsive, retina ready and optimized for faster page load times.

Optimizer Demo

Optimizer Demo

5. Rowling

A theme designed and built with magazines in mind. It it focused on presenting content the best possible way using single post templates and a nicely integrated related posts archive section, that will keep your visitors reading. Rowling also supports custom logos, accent colors and widgets.

Rowling Demo

Rowling Demo

6. Abito

A beautiful theme packed with superb animations and fancy effects. The design of all page layouts is very modern, making it suitable for websites about trendy topics such as design, fashion, and technology. Other unique bonuses of Abito are the page transition preloader and an infinite scroll to show all your posts in one page.

Abito Demo

Abito Demo

7. Founder

A theme with a minimalist look that focuses on your content and makes it look more professional. It is fully responsive and should load quickly on both mobile and desktop devices.

Founder Demo

Founder Demo

8. Quidus

Quidus is a free blog theme with a sharp, smart look. It is highly customizable from the colors to the layout. Although this theme isn’t premium and won’t cost you anything, it’s creators offer great support and will answer your questions if you have any difficulties.

Quidus Demo

Quidus Demo

9. LandingSumoWP20

A supreme Bootstrap based landing page theme. It comes with a drag and drop builder and other custom options and widgets for quick development. It’s creators have also provided a YouTube video, to help you get the theme up and running.

LandingSumoWP20

LandingSumoWP20 Demo

10. Proper Lite

A very stylish, mostly black and white theme with smooth animations and fonts for grown-ups. It’s developers offer additional free plugins that you can use to further expand the theme’s capabilities.

Proper Lite Demo

Proper Lite Demo

11. Brasserie

A theme for restaurant websites. The free version features 4 different layouts, an image slider and nice Bootstrap like responsive design.

Brasserie Demo

Brasserie Demo

12. Author

Author is a theme mainly for blogs. The page layout consists of a sidebar with various widgets on the left and a wide space reserved for your content on the right.

Author Demo

Author Demo

13. Woodley

A lightweight WordPress theme that allows you too quickly setup a great looking website with minimal effort. Just like the previous theme on our list, this one places all sorts of information in a sidebar with widgets, while leaving the content more space on the right.

Woodley Demo

Woodley Demo

14. Sydney

A free, powerful business theme that provides lots of functionality we would normally find in premium versions. Sydney brings of customization possibilities like access to all Google Fonts, full color and layout control. It also features a full screen image slider and a background parallax.

Sydney Demo

Sydney Demo

15. Gridsby

As the name suggests, Gridsby presents content in the form of a Pinterest-like image grid. It also includes a bunch of shortcodes with useful functionality such as sliders and lightboxes. The perfect theme for photography bloggers.

Gridsby Demo

Gridsby Demo

16. Colormag

ColorMag is a responsive theme suitable for news, newspapers and magazines. It looks really professional and you wouldn’t be able to tell the demo isn’t an actual news website if you didn’t know. A cool feature here is the support it’s creators offer, even though it is a free theme.

Colormag Demo

Colormag Demo

17. Unlimited

Unlimited is a theme designed to improve the performance of your website. It doesn’t offer too many features, but in exchange for that it’s fast and simple to build with, while still looking great.

Unlimited Demo

Unlimited Demo

18. GridBlog

GridBlog is a modern grid-based theme with a ton of free features. It is fully responsive, SEO optimized and offers a plethora of widgets for added functionality. The theme is also completely customizable, allowing you to choose the colors and background to suite your style.

GridBlog Demo

GridBlog Demo

19. Discovery

Discovery is a business oriented theme built with a focus on simple customization. It allows you to add your own logo, header, featured areas, social media links and much more without any coding.

Discovery Demo

Discovery Demo

20. BLDR

BLDR is a great WordPress theme that gives your pages that premium full width look. It is bundled up with plugins such as a drag and drop page builder, which will make developing websites easier and quicker.

Bldr Demo

BLDR Demo

Tutorials, Tips and Tricks

1. Increasing The Maximum Upload Size In WordPress – Tutorial

A well written article, presenting different ways of overcoming the exceeds the maximum upload size for this site error. Solving this problem requires modifying server settings via PHP or the .htaccess file to increase the maximum memory limit.

2. An Introduction to the WordPress Filesystem API

A tutorial on how to use the WordPress Filesystem API for accessing local file systems in a secure way, with proper file permissions. To give you an applicable example, this lesson goes through each step of building a simple plugin, that saves the content of a textarea to a file.

3. Building a WordPress Theme in 60 Seconds

In this minute long video you can see the simplified process of creating a basic WordPress theme by using HTML/CSS templates and a bit of PHP. If watching the video gives you enough courage, you can read this follow-up series of lessons and start developing your first WP theme.

4. How to Build a Membership Site on WordPress

This comprehensive tutorial will show you how to transform a blank WordPress website into a full featured membership site. Creating custom user roles, managing locked content, handling registration and logins – everything you need to know is explained in great detail with easy to follow screenshots.

5. Stupid WordPress Tricks

Over 70 highly useful shortcodes that you can copy and paste right into your WordPress project. Includes awesome snippets for adding functionality, such as Custom Content to Search Engine Visitors, Display Posts for a Specified Time Period and Highlight Author Comments.

6. The Ultimate WordPress Cheatsheet

Bookmark this article if you often find yourself wondering “What is page.php for?”, or “How do i add a footer?”. This cheatsheat allows you to quickly look up basic WordPress commands and concepts. It covers the purpose of each file in a WP theme, how to create a post loop and how to use bloginfo and include tags.

7. Mastering Image Optimization in WordPress

Reducing the file size of the images on your WordPress site is the easiest way to improve load times and performance. Here are a handful of different techniques to decrease the footprint of images without compromising too much on the quality.

8. How (and Why) to Convert WordPress Tags from ‘Flat’ to ‘Hierarchical’

This is a lesson on how to transform the Tag system of your WordPress site to a parent/child hierarchy for easier organizing of topics. Even if you are not interested in this experiment, the article offers a lot of great insight on categories, tags and categorizing data.

9. How to Create a WordPress Back End That’s Safe for Clients

A number of good practices and principles to have in mind when constructing a WordPress website for somebody else. The tips offered here will add more safety and stability to your project, making it harder for clients to mess about and break the website’s features.

10. What Happens When You Switch Your WordPress Theme?

Have you ever found a great looking theme (like the ones above) and wanted to implement it on your website, replacing the old style entirely? This article will help you keep track of the things that might get lost when swapping themes.

Plugins

1. Shortcodes Ultimate

With this plugin you can browse a library of 50+ shortcodes and use them to easily create buttons, sliders, responsive videos and many more. A lot of the elements in Shorctodes Ultimate provide features that are hard to emulate if they’re not included with the theme you’re using.

Shortcodes Ultimate

Shortcodes Ultimate

2. Share Buttons by AddToAny

Insert customizable share buttons to your pages. Choose from a huge collection of social media, bookmarking and email services such as Twitter, Facebook, Pinterest and 100+ more. You can also bundle up a bunch of buttons and add them to a universal share button, which on click will pop up a menu with the chosen platforms.

Share Buttons by AddToAny

Share Buttons by AddToAny

3. Page Builder by SiteOrigin

Page Builder makes it possible to create responsive column based layouts, which you can then easily fill with content and standard WordPress widgets. It works with all themes, doesn’t require any coding skill and turns WP page development into child’s play.

Page Builder by SiteOrigin

Page Builder by SiteOrigin

4. WP Retina 2x

With WP Retina 2x you can generate Retina (High DPI) versions of the images on your website, that will look amazing on any display. The plugin will also automatically detect what device it’s running on and supply the appropriate image file.

WP Retina 2x

WP Retina 2x

5. Yoast SEO

Although vanilla WordPress itself is very search engine friendly there is always place for optimization. When editing pages and posts, Yoast SEO will add a new panel below the editor. This panel will give you the ability to add a title, keywords and a meta description, while showing you a preview of how the page will look in Google.

Yoast SEO

Yoast SEO

6. WP Google Maps

Adding an instance of Google Maps to your posts and pages is as easy as copy-and-pasting the provided shortcode. After that, the widget allows you to control the zoom and size of the map, add markers, directions, and everything you would normally expect out of Google Maps.

WP Google Maps

WP Google Maps

7. Black Studio TinyMCE Widget

Adds a Visual Editor widget that allows you to insert rich text and media objects. After installing the plugin, you will have the option to add the default WP visual editor as a widget. This is really useful when you want to add content to a sidebar, where normally only the WordPress Text Editor is available.

This plugin also works wonderfully in combination with Page Builder by Site Origins.

Black Studio TinyMCE Widget

Black Studio TinyMCE Widget

8. Akismet

A spam filter that checks your comments against the Akismet Web service to see if they look like spam or not. If can work as a firewall outright blocking the incoming spam, or it can find suspicious comments after they are published and send them to the trash.

9. Meta Slider

An easy to use image slider. Simply select images from your WordPress Media Library, drag and drop them into place, set slide captions and you’re ready to go. There are 4 different slideshows available, each of them can be embedded using the according shortcode.

Meta Slider

Meta Slider

10. EWWW Image Optimizer

This plugin can drastically reduce your pages’ load times by applying compression to your images. It runs automatically, optimizing every image file you upload to the Media Library. EWWW can also reduce the size of the images you’ve already uploaded and convert between file formats.

EWWW Image Optimizer

EWWW Image Optimizer

Hope you like our collection! Did we miss something? Tell us in the comments.

Source:: Tutorialzine.com

Getting started with ECMAScript 6

By Axel Rauschmayer

This blog post helps you to get started with ECMAScript 6 (ES6):

  • It explains how you can interactively try out ES6.
  • It lists ES6 features that are easy to adopt, along with how those features are coded in ES5.

Trying out ECMAScript 6

There are three simple ways to play with ES6:

  1. Web browser: use the online Babel REPL, an interactive playground that compiles ES6 to ES5. There is nothing to install with this option.
  2. Command line: use babel-node, a version of the Node.js executable that understands ES6 (and internally compiles it to ES5). It can be installed via npm.
  3. Various JavaScript engines: check the ES6 compatibility table by kangax to find out which ES6 features are supported natively where.

More details on options 1 and 2 are given next.

The Babel REPL

The Babel REPL has four major sections:

  • The top left pane contains the ES6 source code.
  • The bottom left pane shows syntax errors discovered in the ES6 code.
  • The top right pane contains the ES5 code that the ES6 code is compiled to.
  • The bottom right pane shows output produced via console.log().

babel-node

The babel-node executable can be installed via npm:

    $ npm install --global babel

You can use it in the same way as you would the Node.js executable node. Like node, an interactive REPL is started like this:

    $ babel-node

Once you are in that REPL, you can execute ES6 code:

    > let arr = [1, 2, 3];
    > arr.map(x => x * x)
    [ 1, 4, 9 ]

Note that babel-node does not currently support multi-line input.

The Babel website has more information the Babel CLI tools.

The remaining sections of this post describe ES6 features that are easy to adopt.

From var to let/const

ES6 has two new ways to declare variables:

  • let is (roughly) a block-scoped version of var.
  • const is like let, but creates constants, variables whose values can’t be changed.

You can generally replace each var with a let or a const. But you shouldn’t do so blindly, because the different kind of scoping can change how code behaves. As an example, look at the following ES5 code:

    var x = 3;
    function func(randomize) {
        if (randomize) {
            var x = Math.random(); // (A) scope: whole function
            return x;
        }
        return x; // accesses the x from line A
    }
    func(false); // undefined

That func() returns undefined may be surprising. You can see why if you rewrite the code so that it more closely reflects what is actually going on:

    var x = 3;
    function func(randomize) {
        var x;
        if (randomize) {
            x = Math.random();
            return x;
        }
        return x;
    }
    func(false); // undefined

If you replace var with let in the initial version, you get different behavior:

    let x = 3;
    function func(randomize) {
        if (randomize) {
            let x = Math.random();
            return x;
        }
        return x;
    }
    func(false); // 3

Thus, blindly replacing var with let or const is risky. My advice is:

  • Only use let/const in new code.
  • Leave old code as is or refactor it carefully.

More information: chapter “Variables and scoping” in “Exploring ES6”.

From IIFEs to blocks

In ES5, you had to use an IIFE if you wanted to keep a variable local:

    (function () {  // open IIFE
        var tmp = ···;
        ···
    }());  // close IIFE
    
    console.log(tmp); // ReferenceError

In ECMAScript 6, you can simply use a block and a let declaration:

    {  // open block
        let tmp = ···;
        ···
    }  // close block
    
    console.log(tmp); // ReferenceError

More information: section “Avoid IIFEs in ES6” in “Exploring ES6”.

From concatenating strings to template literals

With ES6, JavaScript finally gets literals for string interpolation and multi-line strings.

String interpolation

In ES5, put the results of expressions into strings by concatenating those results and string fragments:

    function printCoord(x, y) {
        console.log('('+x+', '+y+')');
    }

In ES6 you can use string interpolation via template literals:

    function printCoord(x, y) {
        console.log(`(${x}, ${y})`);
    }

Multi-line strings

Template literals also help with representing multi-line strings.

For example, this is what you have to do to represent one in ES5:

    var HTML5_SKELETON =
        '<!doctype html>n' +
        '<html>n' +
        '<head>n' +
        '    <meta charset="UTF-8">n' +
        '    <title></title>n' +
        '</head>n' +
        '<body>n' +
        '</body>n' +
        '</html>n';

If you escape the newlines via backslashes, things look a bit nicer (but you still have to explicitly add newlines):

    var HTML5_SKELETON = '
        <!doctype html>n
        <html>n
        <head>n
            <meta charset="UTF-8">n
            <title></title>n
        </head>n
        <body>n
        </body>n
        </html>';

ES6 template literals can span multiple lines:

    const HTML5_SKELETON = `
        <!doctype html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
        </head>
        <body>
        </body>
        </html>`;

(The examples differ in how much whitespace is included, but that doesn’t matter in this case.)

More information: chapter “Template literals and tagged templates” in “Exploring ES6”.

From function expressions to arrow functions

In current ES5 code, you have to be careful with this whenever you are using function expressions. In the following example, I create the helper variable _this (line A) so that the this of UiComponent can be accessed in line B.

    function UiComponent {
        var _this = this; // (A)
        var button = document.getElementById('myButton');
        button.addEventListener('click', function () {
            console.log('CLICK');
            _this.handleClick(); // (B)
        });
    }
    UiComponent.prototype.handleClick = function () {
        ···
    };

In ES6, you can use arrow functions, which don’t shadow this (line A, lexical this):

    class UiComponent {
        constructor() {
            let button = document.getElementById('myButton');
            button.addEventListener('click', () => {
                console.log('CLICK');
                this.handleClick(); // (A)
            });
        }
        handleClick() {
            ···
        }
    }

Arrow functions are especially handy for short callbacks that only return results of expressions.

In ES5, such callbacks are relatively verbose:

    var arr = [1, 2, 3];
    var squares = arr.map(function (x) { return x * x });

In ES6, arrow functions are much more concise:

    let arr = [1, 2, 3];
    let squares = arr.map(x => x * x);

When defining parameters, you can even omit parentheses if the parameters are just a single identifier. Thus: (x) => x * x and x => x * x are both allowed.

More information: chapter “Arrow functions” in “Exploring ES6”.

Handling multiple return values

Some functions or methods return multiple values via arrays or objects. In ES5, you always need to create intermediate variables if you want to access those values. In ES6, you can avoid intermediate variables via destructuring.

Multiple return values via arrays

exec() returns captured groups via an Array-like object. In ES5, you need an intermediate variable (matchObj in the example below), even if you are only interested in the groups:

    var matchObj =
        /^(dddd)-(dd)-(dd)$/
        .exec('2999-12-31');
    var year = matchObj[1];
    var month = matchObj[2];
    var day = matchObj[3];

In ES6, destructuring makes this code simpler:

    let [, year, month, day] =
        /^(dddd)-(dd)-(dd)$/
        .exec('2999-12-31');

The empty slot at the beginning of the Array pattern skips the Array element at index zero.

Multiple return values via objects

The method Object.getOwnPropertyDescriptor() return a property descriptors, an object that holds multiple values in its properties.

In ES5, even if you are only interested in the properties of an object, you still need an intermediate variable (propDesc in the example below):

    var obj = { foo: 123 };
    
    var propDesc = Object.getOwnPropertyDescriptor(obj, 'foo');
    var writable = propDesc.writable;
    var configurable = propDesc.configurable;
    
    console.log(writable, configurable); // true true

In ES6, you can use destructuring:

    let obj = { foo: 123 };
    
    let {writable, configurable} =
        Object.getOwnPropertyDescriptor(obj, 'foo');
    
    console.log(writable, configurable); // true true

{writable, configurable} is an abbreviation for:

    { writable: writable, configurable: configurable }

More information: chapter “Destructuring” in “Exploring ES6”.

From for to forEach() to for-of

Prior to ES5, you iterated over Arrays as follows:

    var arr = ['a', 'b', 'c'];
    for (var i=0; i<arr.length; i++) {
        var elem = arr[i];
        console.log(elem);
    }

In ES5, you have the option of using the Array method forEach():

    arr.forEach(function (elem) {
        console.log(elem);
    });

A for loop has the advantage that you can break from it, forEach() has the advantage of conciseness.

In ES6, the for-of loop combines both advantages:

    let arr = ['a', 'b', 'c'];
    for (let elem of arr) {
        console.log(elem);
    }

If you want both index and value of each array element, for-of has got you covered, too, via the new Array method entries() and destructuring:

    for (let [index, elem] of arr.entries()) {
        console.log(index+'. '+elem);
    }

More information: section “The for-of loop” in “Exploring ES6”.

Handling parameter default values

In ES5, you specify default values for parameters like this:

    function foo(x, y) {
        x = x || 0;
        y = y || 0;
        ···
    }

ES6 has nicer syntax:

    function foo(x=0, y=0) {
        ···
    }

An added benefit is that in ES6, a parameter default value is only triggered by undefined, while it is triggered by any falsy value in the previous ES5 code.

More information: section “Parameter default values” in “Exploring ES6”.

Handling named parameters

A common way of naming parameters in JavaScript is via object literals (the so-called options object pattern):

    selectEntries({ start: 0, end: -1 });

Two advantages of this approach are: Code becomes more self-descriptive and it is easier to omit arbitrary parameters.

In ES5, you can implement selectEntries() as follows:

    function selectEntries(options) {
        var start = options.start || 0;
        var end = options.end || -1;
        var step = options.step || 1;
        ···
    }

In ES6, you can use destructuring in parameter definitions and the code becomes simpler:

    function selectEntries({ start=0, end=-1, step=1 }) {
        ···
    }

Making the parameter optional

To make the parameter options optional in ES5, you’d add line A to the code:

    function selectEntries(options) {
        options = options || {}; // (A)
        var start = options.start || 0;
        var end = options.end || -1;
        var step = options.step || 1;
        ···
    }

In ES6 you can specify {} as a parameter default value:

    function selectEntries({ start=0, end=-1, step=1 } = {}) {
        ···
    }

More information: section “Simulating named parameters” in “Exploring ES6”.

From arguments to rest parameters

In ES5, if you want a function (or method) to accept an arbitrary number of arguments, you must use the special variable arguments:

    function logAllArguments() {
        for (var i=0; i < arguments.length; i++) {
            console.log(arguments[i]);
        }
    }

In ES6, you can declare a rest parameter (args in the example below) via the ... operator:

    function logAllArguments(...args) {
        for (let arg of args) {
            console.log(arg);
        }
    }

Rest parameters are even nicer if you are only interested in trailing parameters:

    function format(pattern, ...args) {
        ···
    }

Handling this case in ES5 is clumsy:

    function format() {
        var pattern = arguments[0];
        var args = arguments.slice(1);
        ···
    }

Rest parameters make code easier to read: You can tell that a function has a variable number of parameters just by looking at its parameter definitions.

More information: section “Rest parameters” in “Exploring ES6”.

From apply() to the spread operator (...)

In ES5, you turn arrays into parameters via apply(). ES6 has the spread operator for this purpose.

Math.max()

ES5 – apply():

    > Math.max.apply(null, [-1, 5, 11, 3])
    11

ES6 – spread operator:

    > Math.max(...[-1, 5, 11, 3])
    11

Array.prototype.push()

ES5 – apply():

    var arr1 = ['a', 'b'];
    var arr2 = ['c', 'd'];
    
    arr1.push.apply(arr1, arr2);
        // arr1 is now ['a', 'b', 'c', 'd']

ES6 – spread operator:

    let arr1 = ['a', 'b'];
    let arr2 = ['c', 'd'];
    
    arr1.push(...arr2);
        // arr1 is now ['a', 'b', 'c', 'd']

More information: section “The spread operator (...)” in “Exploring ES6”.

From concat() to the spread operator (...)

The spread operator can also turn the contents of its operand into array elements. That means that it becomes an alternative to the Array method concat().

ES5 – concat():

    var arr1 = ['a', 'b'];
    var arr2 = ['c'];
    var arr3 = ['d', 'e'];
    
    console.log(arr1.concat(arr2, arr3));
        // [ 'a', 'b', 'c', 'd', 'e' ]

ES6 – spread operator:

    let arr1 = ['a', 'b'];
    let arr2 = ['c'];
    let arr3 = ['d', 'e'];
    
    console.log([...arr1, ...arr2, ...arr3]);
        // [ 'a', 'b', 'c', 'd', 'e' ]

More information: section “The spread operator (...)” in “Exploring ES6”.

From constructors to classes

ES6 classes are mostly just more convenient syntax for constructor functions.

Base classes

In ES5, you implement constructor functions directly:

    function Person(name) {
        this.name = name;
    }
    Person.prototype.describe = function () {
        return 'Person called '+this.name;
    };

In ES6, classes provide slightly more convenient syntax for constructor functions:

    class Person {
        constructor(name) {
            this.name = name;
        }
        describe() {
            return 'Person called '+this.name;
        }
    }

Derived classes

Subclassing is complicated in ES5, especially referring to super-constructors and super-properties. This is the canonical way of creating a sub-constructor of Person, Employee:

    function Employee(name, title) {
        Person.call(this, name); // super(name)
        this.title = title;
    }
    Employee.prototype = Object.create(Person.prototype);
    Employee.prototype.constructor = Employee;
    Employee.prototype.describe = function () {
        return Person.prototype.describe.call(this) // super.describe()
               + ' (' + this.title + ')';
    };

ES6 has built-in support for subclassing, via the extends clause:

    class Employee extends Person {
        constructor(name, title) {
            super(name);
            this.title = title;
        }
        describe() {
            return super.describe() + ' (' + this.title + ')';
        }
    }

More information: chapter “Classes” in “Exploring ES6”.

From custom error constructors to subclasses of Error

In ES5, it is impossible to subclass the built-in constructor for exceptions, Error (the chapter “Subclassing Built-ins” in “Speaking JavaScript” explains why). The following code shows a work-around that gives the constructor MyError important features such as a stack trace:

    function MyError() {
        // Use Error as a function
        var superInstance = Error.apply(null, arguments);
        copyOwnPropertiesFrom(this, superInstance);
    }
    MyError.prototype = Object.create(Error.prototype);
    MyError.prototype.constructor = MyError;

In ES6, all built-in constructors can be subclassed, which is why the following code achieves what the ES5 code can only simulate:

    class MyError extends Error {
    }

More information: section “Subclassing built-in constructors” in “Exploring ES6”.

From function expressions to method definitions in object literals

In ES5, methods are properties whose values are functions:

    var obj = {
        foo: function () {
            ···
        },
        bar: function () {
            this.foo();
        }, // trailing comma is legal in ES5
    }

ES6 provides a more compact syntax for creating methods that also enables super (which doesn’t work in functions created via function expressions):

    let obj = {
        foo() {
            ···
        },
        bar() {
            this.foo();
        },
    }

More information: section “Method definitions” in “Exploring ES6”.

From objects to Maps

Using the language construct object as a map from strings to arbitrary values (a data structure) has always been a makeshift solution in JavaScript. The safest way to do so is by creating an object whose prototype is null. Then you still have to ensure that no key is ever the string '__proto__', because that property key triggers special functionality in many JavaScript engines.

The following ES5 code contains the function countWords that uses the object dict as a map:

    var dict = Object.create(null);
    function countWords(word) {
        var escapedWord = escapeKey(word);
        if (escapedWord in dict) {
            dict[escapedWord]++;
        } else {
            dict[escapedWord] = 1;
        }
    }
    function escapeKey(key) {
        if (key.indexOf('__proto__') === 0) {
            return key+'%';
        } else {
            return key;
        }
    }

In ES6, you can use the built-in data structure Map and don’t have to escape keys. As a downside, incrementing values inside Maps is less convenient.

    let map = new Map();
    function countWords(word) {
        let count = map.get(word) || 0;
        map.set(word, count + 1);
    }

Another benefit of Maps is that you can use arbitrary values as keys, not just strings.

More information: chapter “Maps and Sets” in “Exploring ES6”.

From CommonJS modules to ES6 modules

Even in ES5, module systems based on either AMD syntax or CommonJS syntax have mostly replaced hand-written solutions such as the revealing module pattern.

ES6 has built-in support for modules. Alas, no JavaScript engine supports them natively, yet. But tools such as browserify, webpack or jspm let you use ES6 syntax to create modules, making the code you write future-proof.

Multiple exports

In CommonJS, you export multiple entities as follows:

    //------ lib.js ------
    var sqrt = Math.sqrt;
    function square(x) {
        return x * x;
    }
    function diag(x, y) {
        return sqrt(square(x) + square(y));
    }
    module.exports = {
        sqrt: sqrt,
        square: square,
        diag: diag,
    };
    
    //------ main1.js ------
    var square = require('lib').square;
    var diag = require('lib').diag;
    
    console.log(square(11)); // 121
    console.log(diag(4, 3)); // 5

Alternatively, you can import the whole module as an object and access square and diag via it:

    //------ main2.js ------
    var lib = require('lib');
    console.log(lib.square(11)); // 121
    console.log(lib.diag(4, 3)); // 5

In ES6, multiple exports are called named exports and handled like this:

    //------ lib.js ------
    export const sqrt = Math.sqrt;
    export function square(x) {
        return x * x;
    }
    export function diag(x, y) {
        return sqrt(square(x) + square(y));
    }
    
    //------ main1.js ------
    import { square, diag } from 'lib';
    console.log(square(11)); // 121
    console.log(diag(4, 3)); // 5

The syntax for importing modules as objects looks as follows (line A):

    //------ main2.js ------
    import * as lib from 'lib'; // (A)
    console.log(lib.square(11)); // 121
    console.log(lib.diag(4, 3)); // 5

Single exports

Node.js extends CommonJS and lets you export single values from modules, via module.exports:

    //------ myFunc.js ------
    module.exports = function () { ··· };
    
    //------ main1.js ------
    var myFunc = require('myFunc');
    myFunc();

In ES6, the same thing is done via export default:

    //------ myFunc.js ------
    export default function () { ··· } // no semicolon!
    
    //------ main1.js ------
    import myFunc from 'myFunc';
    myFunc();

More information: chapter “Modules” in “Exploring ES6”.

What to do next

Now that you got a first taste of ES6, what should you do next? I have two suggestions:

  • In “Exploring ES6”, each major feature of ES6 has its own chapter, which starts with an overview. Browsing the chapters is therefore a good way of getting a more complete picture of ES6.
  • The chapter “Deploying ECMAScript 6” describes the options you have for deploying ES6 in current JavaScript environments.

Source:: 2ality

Quick Tip: CSS Only Dropdowns With The Checkbox Hack

By Danny Markov

quick-tip-checkbox-hack

In this quick tip, we are going to take a look at a CSS only technique for creating dropdowns. It revolves around the checkbox HTML element and some smart usage of CSS selectors.

You can see the example in action in our editor. Click the “Edit” button to see the code. You can download the full source code from the button above.

(Play with our code editor on Tutorialzine.com)

The Markup

This is what our HTML structure looks like. Here it’s important to note, that the input element has to come first, before the label and before the ul. You will understand why this is needed later, when we check out the CSS.

<div class="dropdown">
    <input type="checkbox" id="checkbox_toggle">
    <label for="checkbox_toggle">Click to Expand</label>
    <ul>
        <li><a href="#">Link One</a></li>
        <li><a href="#">Link Two</a></li>
        <li><a href="#">Link Three</a></li>
        <li><a href="#">Link Four</a></li>
    </ul>
</div>

As you can see, there’s nothing out of the ordinary here, all of elements are in standard, frequently used HTML:

  • The div will serve as a container for the whole thing.
  • The input type=checkbox is needed because of it’s checked/unchecked property. It will be hidden at all times
  • The label will be used to toggle the input and will also serve as the trigger for your dropdown.
  • The ul is simply a list we want to be visible when the dropdown is extended. Can be any other element.

The Checkbox Hack

We only need the checkbox element for its checked state, which we can style using the :checked CSS pseudo selector. Checking and unchecking it is done by clicking the label, which is a basic browser feature. We first hide the checkbox:

input[type=checkbox]{
    display: none;
}

We also hide the UL by default – it is the dropdown menu which should only be visible when the dropdown is extended.

ul{
    display: none;
}

And here is the hack. If we combine the :checked selector with the general siblings selector (~) we can change CSS properties of elements that follow the checkbox. This is the reason we needed the checkbox to come in first, before the ul in the DOM tree.

input[type=checkbox]:checked ~ ul {
    display: block
}

The CSS snippet above will show the unordered list only when the checkbox is checked. Since the possible status of an input of type checkbox is binary, it is perfect for toggling the items between expanded and hidden state.

Hope you enjoyed our quick tip!

Source:: Tutorialzine.com