Javascript News

Syndicate content
Pipes Output
Updated: 48 weeks 6 days ago

Document Your JSON API Schema with PRMD

Mo, 2015-08-24 14:00

On a recent project, my team agreed that we needed some way to validate and document the JSON coming in and out of our API. We had already settled on using JSON Schema as the means to describe the API, so determining how to validate (and document) JSON Schema was next on the to-do list. I did tons of research into how to best accomplish such noble tasks. OK, OK, “tons of research” really means “look for gems that do this already”. I also consulted my past experience with things like Grape and Swagger, but we aren't using Grape here and I couldn't find anything that would allow me to easily incorporate Swagger. Even if I did, that's only docs, without and validation.

The long and short of it (that's "old person talk" for TL;DR) is, if you want to document your API, validate requests and responses, and use JSON Schema, it's a bit of an effort. There are approaches, such as iodocs, but I didn't want to have to install Redis, use Node, etc. just to get docs. Also, there are plenty of tools out there to generate docs once you have the schema, but they don't give much help in creating the schema. I quickly learned that, no matter which tool or direction I chose, it was going to be a lot of manual effort to get this done. I am hoping this article gets anyone else with the same goal further up the path.

Continue reading %Document Your JSON API Schema with PRMD%

10 Reasons to Love Google Docs

Fr, 2015-08-21 20:59

Google Docs is like Mary Poppins’ magic purse. Underneath your standard cloud-based word processor fare is a seemingly endless supply of tricks, features and shortcuts. The platform doesn’t immediately bombard you with options – in fact, Google Docs has always been modest in presentation – but it does reward those who do a little digging. […]

Continue reading %10 Reasons to Love Google Docs%

A Guide to Vanilla Ajax Without jQuery

Fr, 2015-08-21 18:00

Short for Asynchronous JavaScript and XML, Ajax is a mechanism for making partial page updates. It enables you to update sections of a page with data that comes from the server, whilst avoiding the need for a full refresh. Making partial updates in this way can be effective in creating fluid user experiences and can decrease the load put on the server.

This is the anatomy of a basic Ajax request:

var xhr = new XMLHttpRequest(); xhr.open('GET', 'send-ajax-data.php'); xhr.send(null);

Here, we are creating an instance of the required class to make an HTTP request to the server. We are then calling its open method, specifying the HTTP request method as the first parameter and the URL of the page we’re requesting as the second. Finally, we call its send method passing null as a parameter. If POST-ing the request (here we are using GET), this parameter should contain any data we want to to send with the request.

And this is how we’d deal with the response from the server:

xhr.onreadystatechange = function () { var DONE = 4; // readyState 4 means the request is done. var OK = 200; // status 200 is a successful return. if (xhr.readyState === DONE) { if (xhr.status === OK) console.log(xhr.responseText); // 'This is the returned text.' } else { console.log('Error: ' + xhr.status); // An error occurred during the request. } } };

The onreadystatechange is asynchronous, which means it gets called at any time. These types of functions are callbacks — one that gets called once some processing finishes. In this case, the processing is happening on the server.

For those wishing to learn more about the basics of Ajax, the MDN network has a good guide.

To jQuery or Not to jQuery?

So, the good news is that the above code will work across all the latest major browsers. The bad news is, well, that it is quite convoluted. Yuck! I am already pining for an elegant solution.

Using jQuery, one could condense the entire snippet to:

$.ajax({ url: 'send-ajax-data.php', }) .done(function(res) { console.log(res); }) .fail(function(err) { console.log('Error: ' + err.status); });

Which is nice. And indeed for many, including yours truly, jQuery has become the de facto standard when it comes to Ajax. But, do you know what? This doesn’t have to be the case. jQuery exists to get around the ugly DOM API. But, is it really that ugly? Or incomprehensible?

In the remainder of this article, I would like to investigate improvements made to the Ajax API in vanilla JavaScript. The entire specification can be found on the W3C. What strikes me about this specification is the name. It is no longer “XMLHttpRequest Level 2” but “XMLHttpRequest Level 1” — a result of a 2011 merger between the two specs. Going forward, it will get treated as a single entity from a standards perspective and the living standard will be called XMLHttpRequest. This shows that there is commitment by the community to stick to one standard, and this can only mean good news for developers who want to break free from jQuery.

So lets get started …

Setup

For this article, I am using Node.js on the back-end. Yes, there will be JavaScript on the browser and on the server. The Node.js back-end is lean, I encourage you to download the entire demo on GitHub and follow along. Here is the meat and potatoes of what’s on the server:

// app.js var app = http.createServer(function (req, res) { if (req.url.indexOf('/scripts/') >= 0) { render(req.url.slice(1), 'application/javascript', httpHandler); } else if (req.headers['x-requested-with'] === 'XMLHttpRequest') { // Send Ajax response } else { render('views/index.html', 'text/html', httpHandler); } });

This checks the request URL to determine how to the app should respond. If the request came from the scripts directory, then the appropriate file is served with the content type of application/javascript. Otherwise, if the request’s x-requested-with headers have been set to XMLHttpRequest then we know we’re dealing with an Ajax request and we can respond appropriately. And if neither of these is the case, the file views/index.html is served.

I will expand the commented out section as we dive into Ajax responses from the server. In Node.js, I had to do some heavy-lifting with the render and httpHandler:

Continue reading %A Guide to Vanilla Ajax Without jQuery%

Watch: The Evolution of Android’s Ecosystem

Fr, 2015-08-21 17:30

In this video I'll outline a history of Android versions, and explain whether we should still support them in our applications and, if so, how.

Loading the player...

Continue reading %Watch: The Evolution of Android’s Ecosystem%

Using the Selenium Web Driver API with PHPUnit

Fr, 2015-08-21 16:00

Previously, we demonstrated using Selenium with PHPUnit and used a user subscription form example throughout the article. In this one, we are going to explore the Facebook package using the web driver API implementation.

It is recommended you go through the previous article first, as it covers some basic concepts mentioned in this one, and sets up the sample application for you.

Let’s get started.

Facebook WebDriver API Implementation

PHPUnit partially supports the Selenium WebDriver API and the work is still in progress. One of the most popular WebDriver API implementations is the Facebook/webdriver package. We will try to accomplish the same validation tests from the previous article using this package. Let’s start by installing:

composer require facebook/webdriver --dev

Then, we create the file:

// tests/acceptance/UserSubscriptionTestFB.php class UserSubscriptionTestFB extends PHPUnit_Framework_TestCase { /** * @var RemoteWebDriver */ protected $webDriver; }

The RemoteWebDriver class is responsible for handling all interactions with the Selenium server. We use the create method to create a new instance.

// tests/acceptance/UserSubscriptionTestFB.php public function setUp() { $this->webDriver = RemoteWebDriver::create('http://localhost:4444/wd/hub', DesiredCapabilities::firefox()); }

The first parameter is the Selenium server host address, and it defaults to http://localhost:4444/wd/hub. The second parameter notes the desired capabilities. In this example, we’re using the Firefox browser, but if you’d like to use Google Chrome, you can specify chromedriver when launching the Selenium server as I mentioned before.

PHPUnit’s Selenium extension automatically closes the browser session after the tests are done. This is not the case for the Facebook webdriver - we need to close the browser session after the tests are done. We do that inside the tearDown method.

Continue reading %Using the Selenium Web Driver API with PHPUnit%

Create your own Content Provider in Android

Fr, 2015-08-21 15:00

Android Provides multiple ways for different apps to communicate amongst themselves on the platform. An Android app can share data with other apps that can be used by other apps to build their own logic around. To give an example, you might need to query contact details on the phone. In Android the recommended way to share data is through content providers. A content provider is an owner of particular content, it provides well defined APIs to read, insert, update and delete that data. The content provider can internally use any place to store its data like a local file, local database or some remote service. In this article we are going to learn how we can create our own content provider and access the data from an another app.

Continue reading %Create your own Content Provider in Android%

Boost Your Skills With These Fun Typography Games

Fr, 2015-08-21 14:30

Here's some fun. We’ve compiled a collection of entertaining typography games sure to test your knowledge. Pair typefaces at rapid speed, identify fonts in the blink of an eye, improve your kerning and ragging, and learn the history behind some of your favorite typefaces.

Best of all? Nearly all these games are free to play!

1. The Rather Difficult Font Game

Learn to eyeball fonts fast with The Rather Difficult Font Game. The concept is simple: text will appear for each round and you’re tasked with identifying it. Beware… it’s harder than it looks!

2. TypeConnection

TypeConnection – the “typographic dating game” – helps designers fuel their font-pairing powers with split-second decisions that are sure to get designers at every level up to speed. A nice touch is the roll-over feature, which display each font’s historical significance, unique attributes and letter structure, including cap height, x-height and baseline.

3. Kerntype

Still working on your kerning skills? Kerntype will make you a pro in no time! Simply drag the middle letters to their rightful place by using your arrow keys or your mouse. When you’ve finished, hit “compare” to see how your work measures up.

4. Typewar

Similar to The Rather Difficult Font Game, Typewar ups the ante by challenging you to identity fonts using only a single letter. See what level you can achieve and compare yourself to fellow players to gage how well you’re doing.

5. Shoot the Serif

I Shot the Serif” may be a silly play on words, but it’s a valuable lesson for beginner designers. Set yourself straight by taking aim at serif letters and avoiding the sans serif letters at all costs!

6. RagTime

Creating clean rags can be a real pain for any level designer. Enter: Rag Time – a fun way to speed up your typography skills as you hack away at paragraphs of text to the tune of cheesy ragtime music.

7. Type:Rider

This award-winning phone game has generated a lot of buzz for its stunning visuals and font integration. Focused on the historical significance of type, you’ll explore 10 themed worlds that echo the period of the world’s most famous fonts – including Garamond, Helvetica, and many more.

Take a sneak peek at the trailer here, then download it on iOS or Android (starting at $2.99USD).

Continue reading %Boost Your Skills With These Fun Typography Games%

How to Network When You Live in the Middle of Nowhere

Do, 2015-08-20 21:49

  me: “Networking is key to success!”  And I definitely believe that. However, when I first started building my career, I was an 18-year-old going to school in a lovely but secluded spot on the central Californian coast. We were five minutes from the beach—but an hour and 45 minutes from the closest “big city.” […]

Continue reading %How to Network When You Live in the Middle of Nowhere%

Getting Started with Angular 2 using TypeScript

Do, 2015-08-20 20:00

The current stable version of Angular (i.e, Angular 1.x) was built using the features of ES5 and was meant to work on most of the browsers including some of the older versions of IE. The framework was designed based on the features available in JavaScript. So, it had to create a module system of its own, abstract away some of the language features and provide a highly abstracted and configuration based interface to work on.

All good things of Angular 1 are still available in Angular 2 and the framework is made simpler as well. Angular 2 is built with features of ES6 (and ES7), Web Components in mind and targeting evergreen browsers.

TypeScript is a typed super set of JavaScript which has been built and maintained by Microsoft and chosen by the Angular team at Google for development. The presence of types makes the code written in TypeScript less prone to run-time errors. In recent times, the support for ES6 has been greatly improved and a few features from ES7 have been added as well.

In this article, we’ll see how to use Angular 2 and TypeScript to build a simple application. As Angular 2 is still in alpha, syntax of the code snippets shown in this article may change before it reaches RTM.

Basics of Angular 2

As already mentioned, Angular 2 was built with simplicity in mind. The team removed a number of recipes of Angular 1 that made us think “Why are we doing this?” (if you want to know what has been removed, I suggest you to take a look at this video titled Angular 2.0 Core session by Igor and Tobias). Now the framework is comprised of a small set of building blocks and some conventions to be followed.
The building blocks which are present in Angular 2 are:

  1. Components: A component is similar to directives in Angular 1. It is built with features of HTML5 Web Components. Every component has a view and a piece of logic. It can interact with services to achieve its functionality. The services can be “Dependency Injected” into the component. Anything that has to be used in view of the component has to be a public member on the instance of the component. The components use property binding to check for changes in the values and act on the changes. The components can handle events and event handlers are the public methods defined in the component’s class.
  2. Services: A service is a simple ES6 class with some annotations for Dependency Injection.

As in Angular 1.x, Angular 2 uses Dependency Injection to get references of the objects. As scope has been removed from the framework, we don't have digest cycle running and hence we don't need to keep calling scope.$apply while working in non-Angular world. Angular 2 uses Zone.js to kick the changes and zones know when to act.

An Angular 2 application starts with a component and the rest of the application is divided into several components which are loaded inside the root component.

If you want to learn more about the basics of Angular 2, please check Victor Savkin's blog post about Core Concepts in Angular 2.

Continue reading %Getting Started with Angular 2 using TypeScript%

Watch: Singleton Patterns in Swift

Do, 2015-08-20 17:30

No, the singleton pattern isn't an odd dating technique. It's a powerful construct that lets you utilize classes without creating new instances each time. It's a fairly basic construct to explain and implement but can reap tons of benefit. In this short video, we'll see how it is implemented in Swift.

Loading the player...

Continue reading %Watch: Singleton Patterns in Swift%

Remotely Debug and Test JavaScript with New Vorlon.js Plug-ins

Do, 2015-08-20 16:30

In April 2015, our team of engineers and tech evangelists at Microsoft launched Vorlon.js, an open source, extensible, platform-agnostic tool for remotely debugging and testing your JavaScript.

When we launched the project during the Microsoft Build Developer Conference keynote, we had only three plugins: the DOM Explorer, the Interactive Console and Modernizr. We knew at this time that the key to the success for a project such as Vorlon is the quantity and quality of plugins. When you want to debug your website, you do not want to do much complicated things. You just want to pick the correct plugin and get the correct information.

This is why we made this project open source. We know you have a lot of ideas to provide great debug experiences to web developers.

So two months, 66 pull requests, 78 issues and 547 commits later: we are proud to announce that we (YOU and the team) just released Vorlon.js version 0.0.15! You can get it by either cloning our GitHub repository or installing it using npm command tool (npm install –g vorlon).

Note: if you are still wondering what Vorlon.js is, please read this article from David Catuhe first:_ http://blogs.msdn.com/b/eternalcoding/archive/2015/04/30/why-we-made-vorlon-js-and-how-to-use-it-to-debug-your-javascript-remotely.aspx).

Let’s have a look at what is new in this version.

New Plugins

XHR Panel is here to help you get the list of requests done through XMLHttpRequest. You can choose to enable or disable the recording using the play button.

XHR panel

Network Monitor is bringing the ability for you in Vorlon to see all the network exchanges that are done between the browser and the web server. It provides the resource name, the server domain, the type of request, the duration in milliseconds and a nice visual timeline!

Resource Explorer gives you information about what is stored locally on the client browser instance. There is data about Sessions , Cookies , and Local Storage. This can be really useful when you want to debug local cache or login / persistent user data issues.

Continue reading %Remotely Debug and Test JavaScript with New Vorlon.js Plug-ins%

Deploy Your Rails App to AWS

Do, 2015-08-20 14:00

As developers, we are usually concerned about the development part of any application. We don't think much about the deployment part as we consider it to be a responsibility of the SysAdmins. But many times, we don't have a dedicated SysAdmin available, so we have to put on the SysAdmin hat and get things done. There are many options to deploy your Rails application. Today, I will cover how to deploy a Rails application to Amazon Web Services (AWS) using Capistrano.

We will use the Puma + Nginx + PostgreSQL stack. Puma will be the application server, Nginx the reverse proxy, and PostgreSQL is the database server. This stack can be used on MRI Ruby or JRuby as well. Most of the steps remain same for both rubies, but I'll highlight where they differ as well.

Continue reading %Deploy Your Rails App to AWS%

Why Do We Love Scratchy Records, Halftone Dots & Other Flaws?

Do, 2015-08-20 03:09

It's funny how it's almost always the imperfections in a technology that become its signature - the bit that we celebrate.

What am I talking about?

  • The hiss and crackle of a vinyl record
  • The sprocket holes on movie film reels
  • The clicks, whistles and squeals of dial-up internet
  • The linear brush stroke in a painting

Each is not much more than an accidental side-effect of their creation process. For instance, dialup modems hacked audio phone tech to make data connections work. It was never a great system to send data so we moved away from it. Yet that tinny sound can still make people smile.

Similarly, we rarely rely on moving mechanical reels to drive today's digital video. Yet perforated film reels are still easily the most common visual motif in logos for film companies and photographers.

Which brings us to the 'halftone pattern'.

The Halftone

The 'halftone' – those little dots that you see in most printed photographs – are another side-effect of an imperfect process. A case of 'this is the best we can do with what we have'.

Before the invention of the halftone, almost all color imagery was hand-painted, and skilled painters might hand mix hundreds of different colors to recreate what their eyes were seeing.

Obviously hand mixing hundreds of colors for each image wasn't an option for the print process. Unlike painters, printing presses can only print solid ink in a limited set of colors at any one time.

Halftones changed the game by giving printers a lot more tones out of a smaller number of inks. Glass screens with grids of tiny lenses allowed print houses to convert tonal imagery into differently sized dots. While it wasn't a perfect, mirror-like reproduction – early screens were very coarse - it was a revolution for color printing.

[caption id="attachment_113070" align="alignright" width="250"] Roy Lichtenstein[/caption]

But halftones can't help but have their own 'look', and artists and designers picked up an that.

1960's Pop Art master Roy Lichtenstein adopted the halftone dot (Ben-Day dots) in all of his most iconic works. His bold, comic-inspired work vibrates with hand-stencilled dots which you'll find on everything from canvas to tiles to cups and crockery.

Khoi Vin Introduces a Wildcard

Khoi Vin (formerly design extraordinaire at NYT) has also adopted the halftone effect in a big way for his new Wildcard iPhone App.

Bored with the blurred background photo effect that has become common in the past two years, Khoi uses halftones in two ways:

  • Color feature images in the browse view use a subtle newspaper-like halftone.
  • -Upon opening a 'card', the feature image transforms into a dark, monotone version that becomes the background.

Continue reading %Why Do We Love Scratchy Records, Halftone Dots & Other Flaws?%

Deploying a Django App with mod_wsgi on Ubuntu 14.04

Mi, 2015-08-19 22:00

Django is a free, open-source, Python-based web framework. Django follows the MVC architectural pattern, with special emphasis on creating your applications rapidly. In recent times, Django has become a popular choice for creating web applications. Popular services like Instagram, Bitbucket and Pinterest were developed using Django.

In development mode, Django has a development server, which is sufficient for testing purposes. Once you complete a web application and it's ready for production, the process of setting up the application on a server might be overwhelming for some, especially if you're doing it for the first time. This article provides a step-by-step guide on how to deploy Django-based web applications using mod_wsgi.

mod_wsgi

WSGI, or Web Server Gateway Interface, is a Python standard for web servers. Python was traditionally developed as a programming language, so WSGI provides a way for web servers to serve applications developed in Python. It enables web applications in Python to interact with web servers, acting as a link between the two.

Apache is one of the most popular web servers, and mod_wsgi is an Apache module that's used to host Python applications on Apache. It's also a relatively simple way of deploying a Django application.

Python comes installed by default in Ubuntu 14.04. Let us now look at the step by step guide to deploy a Django application using mod_wsgi.

1. Creating a Django Application

In this section, we're going to install the required packages and set up a hello world Django application to be served by mod_wsgi. We'll assume that you've logged in to a newly created virtual machine.

1.1 Create a New User (Optional)

If you create a VM using AWS or Microsoft Azure, you're logged in as a user that you specified while creating the VM, so you can skip this step.

There are some extra steps if you're first logged in as a root user (if you create a new VM with Digital Ocean). Although you can perform all functions using the same user, it's generally advised to create a new user. Here are detailed instructions for creating users and adding them to the sudoers list on Ubuntu 14.04.

1.2 Install a Python Package Manager

In this tutorial, we're going to use the Ubuntu package manager, apt-get, for installing packages. However, on a fresh VM, you must update packages first by running the following command:

sudo apt-get update

Pip is a Python package manager that helps us install, modify or remove Python packages. The easiest way to install pip in Ubuntu is by using the Ubuntu package manager apt-get:

sudo apt-get install python-pip

apt-get installs the latest stable version of pip. Alternatively, if you require a specific version of pip, you can install it from the source code. However, for the purposes of deploying a Django application, installing it through the package manager should suffice.

You can also use easy_install as an alternative to pip. However, in this tutorial, we'll use pip to install packages.

1.3 Install Django

If you're creating a project form scratch, you just need the Django package. In this example, we wouldn't require any further packages:

sudo pip install Django

If you want to install a specific version of the package, you can specify it in the command as shown below (in case your application was coded in an older version of Django):

sudo pip install Django==1.5.5

You can also install Django through the package manager apt-get. Caution must be exercised when following this step as apt-get might not be updated with the latest stable version as compared to pip.

Continue reading %Deploying a Django App with mod_wsgi on Ubuntu 14.04%

Introducing Four: It’s WebGL, but Easier

Mi, 2015-08-19 20:00

WebGL has been around for a few years now and we have watched it mature into the reliable and widely supported graphics technology it is today. With big companies like Google, Mozilla, and Microsoft advocating for its use, it’s hard not being curious about it.

Since its specifications were finalized in 2011, it has gained a lot of attraction. With the help of frameworks like ThreeJS, BabylonJS and Play Canvas, this area has become less daunting. Thanks to them it’s much easier to pick up, but it still requires a good learning effort as it is a different discipline altogether.

This article will briefly introduce you to what WebGL is and then I’ll cover Four, a framework I created to help developers delve quickly into the WebGL world. In case you want to see what Four and WebGL can do for you, take a look at this simple demo I built.

What is WebGL?

WebGL is a graphics API based on the Open Graphics Library for Embedded Systems (OpenGL ES 2.0). This allows browsers that support it to render three dimensional elements in the HTML canvas element. OpenGL ES 2.0 was chosen because it was a reputable open-standard for computer graphics and, more importantly, it was designed to perform optimally on embedded devices, such as mobiles and tablets. This was crucial given the broad device accessibility of modern browsers.

The API itself is exposed through JavaScript. The API is low level, so its use can result in a lot of repetitive and complex code. In addition, the nature of typical OpenGL-based applications imposed programming design paradigms and data structures this language was not prepared for, such as object-oriented programming and unary operators that enabled fast matrix manipulation. This can be problematic for physical simulations dependent on the manipulation of large matrix structures. This is where Four comes in.

Continue reading %Introducing Four: It’s WebGL, but Easier%

What’s New in WordPress 4.3

Mi, 2015-08-19 18:30

WordPress 4.3 was released today, including more than 100 changes. If you're running WordPress on any of your websites, you might have already seen the following message on your dashboard.

By now, we all know that WordPress doesn’t stand still for too long. Just four months after the release of WordPress 4.2, the newest version is out: WordPress 4.3.

Codenamed Billie, after jazz legend Billie Holiday, this release was lead by Konstantin Obenland. According to WordPress, this update “makes it even easier to format your content and customize your site”. Version 4.3 sees plenty of new features that users will appreciate.

Updating to WordPress 4.3

As a responsible website owner, we should all be maintaining our sites regularly. For a more detailed background on the topic, I'd recommend checking out our Definitive Guide to WordPress Maintenance.

Continue reading %What’s New in WordPress 4.3%

Building a Style Switcher with Pure CSS Using :checked

Mi, 2015-08-19 18:00

A few years ago, web developers were unable to implement and build so many things using CSS only and without relying on JavaScript. But today CSS is mature enough that it is capable of doing powerful things without writing a single line of JavaScript. You might have also read a couple of articles about “CSS only approaches” that demonstrates the power of CSS.

When it comes to CSS-only approaches, we can’t ignore the :checked pseudo-class selector, which I’m going to use in this post. Of course, I am not the first one to write about this technique, and there have been other more extensive discussions regarding using form elements as JavaScript replacements. For example this Adobe article by Louis Lazaris and this great slideshow by Ryan Seddon.

Using :checked

In short, the :checked pseudo-class selector represents (selects) any radio or checkbox element that is checked or selected. The user can change the state of these elements by checking a checkbox or selecting a different value in a set of radio buttons.

Before we dive deeper, take a look at the final demo to get a sense of what we will be building throughout this tutorial:

See the Pen A Style Switcher with Pure CSS using :checked by SitePoint (@SitePoint) on CodePen.

Now we let's get started.

Building the Settings Box

In the demo, you should have noticed the gear icon and how, when clicked, a box with some options appears. Before we go on explaining the HTML and CSS that makes up that box, take a look at the following code:

[code language="css"]
/* we don't want the input fields to appear, all we need is the labels */
input[type="checkbox"], input[type="radio"] {
position: absolute;
visibility: hidden;
}

.settings-box-element {
z-index: 10;
}
[/code]

Since we are only interested in showing the labels, the above code is used to hide the checkboxes and radio buttons. Moreover, all the labels have a class of settings-box-element with a z-index property just to make sure the labels will stay on top of any other elements on the page.

Now we can break down the code that makes up the settings box. Let’s start with the gear button. Here is the HTML:

[code language="html"]
<!-- the gear icon that opens the box when you click on it -->
<input id="settings-btn" class="settings-btn" type="checkbox">
<label for="settings-btn" class="settings-box-element"></label>
[/code]

And the CSS:

[code language="css"]
.settings-btn + label {
position: fixed;
top: 130px;
right: 0;
display: block;
width: 35px;
color: #e83737;
text-align: center;
background: #fff;
cursor: pointer;
}
[/code]

If you have read an article or two about using form elements as JavaScript replacements, then you should already know that we need to use input and label elements together, so that if one of the two was removed, nothing would work. So we have a checkbox input with an id="settings-box" and a label with a for attribute that matches the id value. I’ve also added a class of settings-btn to use for our CSS hook.

In the CSS, the label is given a position: fixed declaration with the appropriate direction properties/values (top and right).

Next is the white box that will virtually contain the buttons:

The HTML first:

[code language="html"]
<!-- the white box that contains the buttons -->
<div class="buttons-wrapper settings-box-element"></div>
[/code]

And the CSS:

[code language="css"]
.buttons-wrapper {
position: fixed;
top: 130px;
right: -200px; /* should match element width */
width: 200px;
height: 240px;
background: #fff;
}
[/code]

The box is a single div element with classes “buttons-wrapper” and “settings-box-element”. As I said earlier, the latter class is mainly used to give the elements a z-index value. The “buttons-wrapper” is used to style the div element. And as you can see, the div was given a width of 200px and a height of 240px to accommodate the 5 buttons you see in the demo. Also, the div is given a position value of fixed and the appropriate right and top properties. The only thing you need to keep in mind here is that the right property should have the same value as the width but in the negative (in order to make it disappear from the viewport).

Continue reading %Building a Style Switcher with Pure CSS Using :checked%

Watch: Capturing Time in React

Mi, 2015-08-19 17:30

Today we're taking the first steps to building a Stopwatch component from scratch! Over the next couple videos we'll build this stopwatch feature by feature. Today, we're focusing on capturing time with setInterval.

Loading the player...

Continue reading %Watch: Capturing Time in React%

Look, Ma! No NodeJS! – a PHP front end workflow without Node

Mi, 2015-08-19 16:00

If you’re intimidated, exhausted or irritated by Gulp, Grunt, NPM, Yeoman, and all the other NodeJS tools that aim to help but often do the opposite, a good asset management workflow is possible in PHP, and this tutorial aims to prove it. In this article, we’ll go through a NodeJS-free PHP front end asset management setup.

What we’ll be doing

We’ll be adding asset management into a Slim 3 project. We’ll be using Rob Allen’s Slim3 Skeleton as a base “app”, along with:

  • BowerPHP instead of Bower for installing assets
  • markstory/mini-asset for minification
  • Robo for resource tracking (watching for changes) and executing a rebuild (minification) when a change is detected

Why mini-asset and not Munee or Assetic? Because it’s dead simple - configure with an .ini file, run, and it executes. No server alterations, no in-depth configuration, ready to go OOTB.

Note that Slim 3 is used here only as a base app, and doesn’t really matter in the whole picture - we won’t be using any of Slim’s particular functionality. As such, you can use any framework you want, or skip using a framework altogether. We’ll be using Homestead Improved as usual to set up a local dev environment.

Getting Started git clone https://github.com/swader/homestead_improved hi_assets cd hi_assets sed -i '' "s@map\: \.@map\: $PWD@g" Homestead.yaml sed -i '' "s@Laravel@test@g" Homestead.yaml vagrant up vagrant ssh

Continue reading %Look, Ma! No NodeJS! – a PHP front end workflow without Node%

The Great Icon Debate: Fonts Vs SVG

Mi, 2015-08-19 15:30

We all know the feeling: just as you feel like you've finally achieved 'ninja-level' mastery with some great web technique... it's time to switch to something new and better.

It has certainly happened to me many times, and it happened again recently with icons. After a long period where icon fonts seemed the natural, best-practice solution, SVG (and its increasing browser support) has introduced some useful innovations that may have changed the rules of the game.

Choosing any technique is a task that involves weighing up many topics. When we deal with icons we need to consider:

  • Accessibility: are there some issues with text-only browsers or screen readers?
  • Semantic meaning: an icon is a glyph used to represent something else (this the simplest definition of this concept I've found; it comes from the Semantic-UI framework docs), so, are we creating a useful relationship between signs and the things to which they refer?
  • Browser compatibility: do we need to ensure a large browser compatibility?
  • HTTP issues: does our icon system unnecessarily tax our server (HTTP requests) and contribute to longer page load times? Can icon files be cached?
  • CSS styling & animation: can we arrange and animate our icons using CSS?

So, what is the best choice now? Should we try to get by with icon fonts – or it is time to turn to SVG?

A Brief History

I realized that when we talk about icons, it's easy to take for granted some topics which we have been dealing with in the past. They can help us to better frame the debate, but not everyone knows them. So, I've put together a very brief 'history of icons techniques in web authoring' to help clarify the debate. (If you feel you're ok with the history part, jump ahead).

Back in the mid-90's – a time when browsers had little to no CSS support – icons were managed with the classic <img> tag. This technique brought with it a lot of accessibility and semantic issues. Furthermore, pages that used lots of icons had to fire off a barrage of performance-crushing HTTP requests: one for each icon in the page.

And if you intended to introduce a :hover effect, you had to load these secondary images with JavaScript.

Happily, things got significantly better with CSS Sprites (or Image Sprites). This technique consists in arranging all icons in a single, unique file (typically GIF or PNG) to be loaded as a CSS background image. The needed portion of the image can be shown by adjusting the background-position property, as in the scheme below (I've also made a pen, if you want to see a running example):

See the Pen CSS sprites example by Massimo Cassandro (@massimo-cassandro) on CodePen.

This technique is still used by many huge sites like Youtube and Google and it solved a lot of problems:

  • Only one image file is required, regardless of how many icons you have (including :hover effects), so HTTP requests can be significantly reduced.
  • Many accessibility (and semantic) issues are resolved, since background images and CSS pseudo elements are invisible to text browser or screen reader (while images are content).

I've prepared a little test that creates two lists: one with sprite icons and one using <img> tags. On the left side of the image below, you can see how the two lists are close to identical (except that the second one required much more code).

The right side is a screenshot of the same lists rendered with Lynx viewer (a web emulator of the text-only web browser Lynx) and it can give you some idea of how your web page may appear using assistive technologies (though A.T. output can vary widely).

You can see that the second list containing the images alt texts (green highlighted), which in this case are perfectly useless, since they confuse the content rather than adding meaning to it. True, we can avoid this by using empty alt attributes (as in the last two items), but we are still have content elements (the images) being used as presentational attributes.

[caption id="attachment_112855" align="aligncenter" width="780"] Lynx Text Browser[/caption]

Of course, there are many cases which require meaningful icons, and the above CSS sprites example doesn't represent the best solution. We'll come back to this topic later.

Icon Fonts

Although they represented a big step forward, CSS sprites are bitmap images. As such, if you need to represent the same glyph in different colors or resolutions, you need a different images for each version.

This problem was resolved by font icons: since fonts are vectors, they are resolution independent and can be easily colored through CSS.

The most common way to apply icon fonts to a page is through a pseudo element – just like we did with CSS sprites. Unfortunately this doesn't resolve the issue of meaningful icons, since this technique still leaves them invisible to screen readers.

Let's look at the example below (using Erik Flowers's Weather Icons):

The first part of the screenshot represents a common icon implementation (using a pseudo element). In this case the icon is part of the content and has a very specific meaning. Unfortunately Lynx can't see the icon, producing a nonsense sentence. You can see the result in the second part of the image.

Luckily there is an easy workaround for this issue: you can add a description inside the icon element (in this case an <i> tag). The description is wrapped inside a <span> that is styled to make its content invisible to browsers (it has usually a big text-indent value), but not to screen readers, that don't take care about this tricks:

The icon <i class="wi wi-umbrella"> <span class="sr-only">"umbrella"</span> </i> means that it's raining

Now, a screenreader can make sense of this as a meaningful sentence:

Continue reading %The Great Icon Debate: Fonts Vs SVG%