Javascript News

Syndicate content
Pipes Output
Updated: 48 weeks 6 days ago

Bootstrap 4 Alpha: Super Smart Features to Win You Over

Di, 2015-09-01 18:00

After months of anticipation, anxious tweets asking for the disclosure of a release date, and a few scattered scraps of news by Mark Otto and Jacob Thornton, having the effect of intensifying rather than quenching our curiosity, Bootstrap 4 alpha is out.

As a designer, I love crafting my own CSS. However, I confess, I find Bootstrap such a well thought-out and strongly supported front-end framework that I’ve immensely enjoyed using it, both to build my projects and to learn more about writing better, modular CSS.

After the much awaited news, as you can probably guess, I downloaded the source files for Bootstrap 4 and spent some time going back and forth between reading the docs and digging into the code to find out more.

I expect the alpha release of Bootstrap 4 will undergo a number of changes in the coming weeks, even months. The curious among you, can keep an eye on the issues section of the project’s GitHub repository. However, the features I’m going to list here are more like broad coding principles and practices that keep improving on each new release of the framework. That’s why I think it’s likely they’re here to stay. If anything, they can only get better.

Here they are. I hope you find them awesome too!

New Interactive Documentation

The Bootstrap documentation has been exemplary since the framework’s early days. It’s always had the crucial role of being a living document, that is, a tool in sync with the collaborative effort of building the framework and communicating it to others:

Abstracting and documenting components became part of our process for building this one tool and Bootstrap in tandem.
Mark Otto in 2012

Mark himself is quite a fan of great documentation. His Code Guide by @mdo is evidence of his approach to high quality documentation as being part and parcel of outstandingly coded projects.

The documentation for version 4 has been rewritten from scratch using Markdown. Understandably, given the alpha stage of this version at the time of writing, it’s still a work in progress.

The Bootstrap docs …

  • are a pleasure to navigate, both using the traditional sidebar navigation and the brand new search form.
  • structure information in a logical manner; content is never overwhelming or confusing.
  • include instructions and how-tos covering all areas of the framework, from different ways of installing Bootstrap to using each component and dealing with browser quirks.

If you take the time, you’ll soon find a few valuable nuggets scattered throughout various sections of the docs. For instance, dealing with over-sized SVG images that use the .img-responsive class in IE9-10, accessibility best practices, enabling the mq4-hover-shim to fix sticky :hover styles on mobile devices, and much more.

Finally, if you’d like to run the Bootstrap docs locally on your computer, install Jekyll, a great website building tool, and follow these instructions.

Top-notch Modular Architecture

Bootstrap has often been the target of complaints about code bloat, too opinionated CSS styling, and a profuse quantity of components. The good news is: Bootstrap 4 has both simplified and further modularized its structure.

To begin with, some components have been eliminated altogether: the Glyphicons icon library is not bundled with the framework any more; panels, wells, and thumbnails are replaced by the Cards component. Also, all CSS reset/normalize code and basic styling are now dealt with in a single brand new module called Reboot.

Further, more than ever before, using Bootstrap now feels like assembling and arranging Lego blocks in different ways. Here are some examples to clarify what I mean.

Continue reading %Bootstrap 4 Alpha: Super Smart Features to Win You Over%

Watch: Create a Bare-bones WordPress Theme from Scratch

Di, 2015-09-01 17:30

Developing WordPress themes is easier than you think. If you know a little bit of HTML and PHP, you can create a very rudimentary but functional, WordPress theme in just a few minutes. In this screencast, I am going to show you how to create a WordPress theme from scratch.

Loading the player...

Continue reading %Watch: Create a Bare-bones WordPress Theme from Scratch%

The 5 Best Resources for Android Developers

Di, 2015-09-01 17:00

Whether you are new to Android or an experienced developer, everyone needs advice on resources or new libraries to improve and simplify development life.

Since Google released the Android Nanodegree on Udacity, I expect more and more new developers to join the Android Developers community.

Continue reading %The 5 Best Resources for Android Developers%

7 Simple Rules for Creating Elegant UI Interactions

Di, 2015-09-01 15:00

'Interaction design' is one of those newish buzzwords that has become strongly tied into the UX design process. In 2015 it's no longer enough for interface elements to instantly switch between two static states. Today words like 'slide' and 'bounce' and 'rebound' have come into the conversation on how good user interfaces work.

However in the world of interactions – as is the case with expensive watches – 'fancy' does not not necessarily mean 'elegant'. While we may be curious about the complexity of the fancy watch below, I suspect that very few of us would want to actually wear it. Natural elegance almost always triumphs over decoration in our interface design too.

If you are creative like me, it's easy to be tempted to create fancy-flying interactions just to make your website feel more modern and engaging. Of course, in our hearts we know this approach can be one of the surest ways to screw up your entire user experience.

As such, I've found that it's important to focus on animations that are so smooth and easy on the eye that our users barely notices them. That's when our animations move out of the spotlight and instead support our what our user is trying to do.

So, why does that matter?

Why does Apple spend so much time and money on packaging that usually gets quickly thrown into the recycling bin? Why do luxury car companies tune the sound of their doors closing?

It's because we find that minor, seemingly unimportant details can have an disproportionate impact on great design, and can lift a UX from "fine" to "awesome".

Enriching your website with beautifully designed 'micro-interactions' not only makes it more usable, but can also trigger positive emotional feelings in your users (like opening that Apple box). Experiencing such emotions means more dopamine is consumed and this literally helps them to become more addicted to your website/application.

So, what defines a 'micro-interaction'?

When a user makes an input (e.g. clicks, drags, types something) your website reacts - well, that's an interaction. This is a way for users to communicate with your website, so it's part of a dialogue. When designing a flow of how users behave on your website, you always have a few different types of interaction you can use:

  1. Navigation interactions: This is when a user ends up in a totally new page/state.
  2. Modal interactions: This is when the current state of website is frozen and some temporary state is displayed on top of it (e.g. "lightbox" gallery or confirmation dialog.)
  3. Micro-interactions: This is when you want only a single element within a page to react to user input – for instance, to show a drop-down menu or reveal more details of a product.
How do we make these reactions elegant?

A website should feel like a concert of interactive interface elements working together to impress you. Elegance is the key criteria to make such impression. Though it's very hard to define elegance in purely technical terms, we can use some logic hacks that helps us to create elegant interactions.

Key Rule #1 - No teleportation

The idea is simple - always use a transition when you are changing an element on page. That means there shouldn't be any instant snap-cuts on your GUI. Every appearing, disappearing or transforming element should be implemented with easing or/and animation.

This helps users to focus their vision on the areas you want them to. And of course this creates a feeling of elegance and consistent flow.

Rule #2: Toggles are better than buttons

At home you would usually use the same switch to turn lights both on and off. The same concept applies to toggle controls on your site. If a control toggle triggers a new state of a given element - that same control should rollback that state.

Furthermore, according to Fitts' law such controls should require close to zero effort to rapidly switch between on and off states.

Rule #3: Triggers should be nearby

Transitions always need some kind of trigger. At the time of the interaction, our user is usually focused on that trigger element. This means it's necessary that the transition begins on or very near the trigger. If you start a transition too far away from your trigger element, user could easily just miss it and the flow will break.

Furthermore a transition should generally propagate from the trigger to the position where you want to focus users' attention. The trick is simple - you lead users eye from trigger to the spot where he should make his next move. This way the user won't lose their focus and will be right on track where you want them.

Rule #4: Use natural transition timing

Transition timings define how long our animation is playing. The major problem with timing is that there is no magic wand to get it right. If you make your transition too long, it will create a pain point for users repeating the same interaction often or rapidly.

On the other hand, if it is too short it will feel unnatural – or the user may miss it entirely. Unfortunately, all you can do is to evaluate the transition by your eagle eye and gut feel. The best advice I've found is not to give all your transitions the same timing. Just play around and find the right balance. Also note that even a difference of 0.05s matters.

Continue reading %7 Simple Rules for Creating Elegant UI Interactions%

jQuery Foundation and Dojo Foundation to Merge

Di, 2015-09-01 14:37
United Foundation to Advance the Open Web by Serving Developers

The jQuery Foundation and Dojo Foundation today announce plans to combine forces to form the largest, most diverse and most comprehensive Foundation committed to building the Open Web by serving developers, their projects and their communities.

“This merger elevates Web accessibility, openness and developer education, and will advance the Open Web and improve the developer experience significantly,” said Kris Borchers, jQuery Foundation Executive Director. “Every Open Source project needs community, governance and technical resources to succeed. By joining forces, we make growing community easier, we streamline and simplify processes and we offer unrivaled resources to projects and developers alike.”

“The Dojo Foundation project leads and I are all very excited to be joining up with the jQuery Foundation,” said the Dojo Foundation President Dylan Schiemann, who will join the jQuery Foundation board with the merger. “We share a common mission, purpose and approach, and our combined ability to serve the needs of the JavaScript development community is going to take the Open Web to new heights.”

Timmy Willison, jQuery Core Project Lead, agreed, adding, “I’m a big fan of Dojo projects and the Dojo Foundation. I am excited and honored to work alongside such capable, talented developers and I look forward to discovering what we can achieve together.”

“Some of the most innovative developer ideas are coming out of the JavaScript community and our clients see a great deal of value from it,” said Todd Moore, Vice President IBM Open Technology. “We are excited to see the jQuery Foundation and the Dojo Foundation joining forces in an open collaborative developer oriented environment.”?

Said James Burke, Project Lead for RequireJS, “I have contributed to projects that have been under both Foundations, and I appreciate how both make it easy for people to start contributing in a welcoming environment by keeping the legal and mechanical processes as low-friction as possible. Both Foundations are also committed to creating maximally-useful code through very permissive Open Source means. By combining their efforts, I believe it will be easier for new projects to choose this successful approach.”

John-David Dalton, Lo-Dash project lead, added, “Combining the resources of the Dojo and jQuery Foundations is a win for developers. Among the many advantages this merger will bring, consolidating CLAs and streamlining processes will make it much easier for projects to grow and better serve the application developer community.”

With this merger, the jQuery Foundation continues to move toward its mission to make the web accessible to everyone. By adding the projects of the Dojo Foundation to the family of projects it supports, the Foundation is able to reach a larger community of developers in its efforts to increase diversity and accessibility in its projects and the open web as a whole. This is just the first major step in the jQuery Foundation’s plans to further serve developers.

10 Essential SublimeText Plugins for JavaScript Developers

Mo, 2015-08-31 20:00

Sublime Text is a great application for just about any developer to have in their toolbox. It is a cross platform, highly customizable, advanced text editor and sits nicely between full featured IDEs (which are notoriously resource hungry) and command line editors such Vim or Emacs (which have steep learning curves).

One of the things that makes Sublime so great is its extensible plugin architecture. This makes it easy for developers to extend Sublime’s core functionality with new features such as code completion, or the embedding of remote API documentation. Sublime Text doesn’t come with plugins enabled out of the box — they are typically installed through a 3rd party package manager simply called Package Control. To install Package Control in Sublime Text, please follow the installation guide on their website.

In this article, I will outline ten must-have Sublime plugins for JavaScript developers, each of which can improve your workflow and make you more productive. So let’s get to it!

1. Babel

Of course the first one on my list is the Babel plugin. This plugin adds proper syntax highlighting to your ES6/2015 and React JSX code. After installing the plugin, the first thing you should do is set it as the default syntax for .es6, .jsx, and even .js files. However, you should be careful with the last one if you’re working with ES3/5 and not transpiling your code using Babel.

If you have not yet discovered the joy of Babel, I highly suggest it. It allows you to compile ES6/2015 and JSX code to ES5. It integrates well with all popular build tools and the CLI. Obviously, it doesn’t support legacy browsers, but you can follow the tips on their caveats page if you need to support IE10 and below.

Unfortunately, the Babel plugin doesn’t allow you to compile ES6 code on the fly from within Sublime. For those of you wanting to do that, I suggest you check out Compile Selected ES6.

2. JSHint

Next up is the JSHint plugin for Sublime. JSHint is a JavaScript Linter, which will look over your code and verify it has proper styling, proper syntax, and is free of common errors related to these. No matter if you’re a beginner or have been programming for most of your life, JSHint is a must have. Check out the JSHint about page for more information on what it can do for you.

For the JSHint SublimeText plugin to work, you need to have JSHint installed globally via npm:

npm install -g jshint

If you’re unsure how to do this, check out our tutorial on getting started with the Node Package manager.

Once the JSHint npm module and the JSHint SublimeText plugin are installed, you can simply invoke JSHint by opening your JavaScript file and pressing Ctrl + J (or Alt + J on Linux/Windows). Alternatively, you can access JSHint via the context menu.

If you've installed the plugin but would like a more explicit warning as to where the error occurred, check out JSHint Gutter. Or, if you’d like to try JSHint before installing the NPM package or the plugin, JSHint.com has a great online interactive tool into which you can paste your code for instant feedback.

3. JsFormat

JsFormat is based on JS Beautifier and can help you automatically format JavaScript and JSON. If you only use it for the JSON formatting alone, it’s worth having. But for me, the biggest advantage comes when I’m working with other developers’ code, or even on code I wrote a long time ago.

Such code can often be hard to read and following a common code formatting style really helps. While formatters may not be for everyone, they can really help the developer read code by introducing a common structure. Linters take care of some of this, but they don’t necessarily hit everything and do not automatically fix formatting. Code formatters save a lot of time and a lot of headaches.

Once installed, to use JSFormat, go to your JS file and hit Ctrl + Alt + f on Windows/Linux or Ctrl + ⌥ + f on Mac. Alternatively, use the context menu.

You may be thinking: “But I what if I don’t like the way they style JavaScript?”

Good news! JsFormat is highly configurable and based on the JS Beautifier settings. To adjust these for SublimeText 3, go to: Preferences -> Package Settings -> JsFormat -> Settings - Default

Then edit the JSON settings there to your liking.

Continue reading %10 Essential SublimeText Plugins for JavaScript Developers%

Automating LIFX Lights With The LightBlue Bean and IFTTT

Mo, 2015-08-31 18:00

The LightBlue Bean is a small low energy Bluetooth Arduino microcontroller with a built in 3-axis accelerometer and temperature sensor. It's quite an interesting way to add connectivity to objects via Bluetooth connectivity instead of Wi-Fi. It has digital and analog pins like a typical Arduino, so you can expand what it can do by adding new elements to the set up.

In order to add new elements, a bit of soldering is required. For this article, I wanted a solder-free demo that anyone with a LightBlue Bean can follow along with, so we'll be focusing on the built in accelerometer. A few months ago, I put together an IFTTT demo here on SitePoint which automatically turns off my LIFX light when I set my Jawbone UP24 to sleep mode. It is a nice touch but I still need to get my smartphone out to turn on my lights each night. I'd prefer something more automatic and decided to try out a few technology experiments to turn the lights on in convenient ways too. In this article, I'll cover the first of my prototypes - I'll be using a LightBlue Bean to detect my door movements and turn my lights on or off depending on if my door is opened or closed.

For those who are a fan of the LightBlue Bean, there is a newer version of the LightBlue Bean on Kickstarter right now called the LightBlue Bean+ which looks pretty neat! It has a rechargable battery, solderless connectors and plenty more useful features. There are only a few days left to put in your pledge!

How This Will Work

Our demo will work like so:

  1. Stick the LightBlue Bean on the door we want to track.
  2. Upload an Arduino sketch which watches for accelerometer changes (the door swinging one way or the other) and sends a message via the Bean Loader Virtual Serial.
  3. Set up a Node server watching for the serial messages coming through.
  4. Set the responses to those messages in the Node server to send a HTTP request to IFTTT's Maker channel to tell it to turn on the light.
  5. Set the LightBlue Bean to Virtual Serial mode.
  6. Run the Node server and close your door to see your light turn on!

Additional rules could be included in our Node server later on to ensure that the code only runs during certain times of day too (to avoid the light going on when it really doesn't need to be). Or even better - add on a photo resistor to detect automatically if the light is needed!

Setting Up Your LightBlue Bean

If you are completely new to using the LightBlue Bean, you'll need to have both the latest Arduino software and the Bean Loader software installed on your Windows 8.1 or Mac computer (apparently the Bean Loader software does not work on older Windows PCs). The guides to getting your LightBlue Bean connected up to your Mac or PC are pretty thorough on the LightBlue Bean website:

This demo has all been set up on Mac OSX but should theoretically work on Windows too.

The steps in this article will assume you are comfortable with the basics of putting a sketch onto your LightBlue Bean, if not, run through the "Getting Started" link for your OS above first.

Our Arduino Sketch Code

All the code is available on GitHub for you to use and adapt for any purpose you choose!

Our Arduino sketch contains most of the brains behind the door watching and looks like so:

[code language="c"]
int minXVal = 0;
int maxXVal = 0;
int minYVal = 0;
int maxYVal = 0;
int minZVal = 0;
int maxZVal = 0;
int movement = 15;
bool ready = false;

void setup() {
Serial.begin();
}

void loop() {
AccelerationReading acceleration = Bean.getAcceleration();

if (!ready) {
for (int i = 0; i < 100; i++) {
if (acceleration.xAxis > maxXVal) {
maxXVal = acceleration.xAxis;
} else if (acceleration.xAxis < minXVal) {
minXVal = acceleration.xAxis;
}

if (acceleration.yAxis > maxYVal) {
maxYVal = acceleration.yAxis;
} else if (acceleration.yAxis < minYVal) {
minYVal = acceleration.yAxis;
}

if (acceleration.zAxis > maxZVal) {
maxZVal = acceleration.zAxis;
} else if (acceleration.zAxis < minZVal) {
minZVal = acceleration.zAxis;
}

delay(10);
}

ready = true;
} else {
if (acceleration.zAxis < minZVal - movement) {
String stringToPrint = "CLOSED";
Serial.println(stringToPrint);
} else if (acceleration.zAxis > maxZVal + movement) {
String stringToPrint = "OPEN";
Serial.println(stringToPrint);
}
}

Bean.sleep(1000);
}
[/code]

Our Sketch Code Explained

To start with, you'll see a range of variables called minXVal, maxXVal, minYVal, maxYVal, minZVal and maxZVal. These track our LightBlue Bean's initial accelerometer readings. Within my demo code, we only really use the z values, however I've left the others in here as you may need to use their values for your own implementations (e.g. if you place the Bean in a different orientation on the door or have a different sort of door, like a sliding door). The accelerometer tracks the force of gravity on each side of the Bean. We only want to know about the changes in these forces, so we need to know the range of forces acting on the Bean originally when it is stationary on our open door. This is where we store those values:

[code language="c"]
int minXVal = 0;
int maxXVal = 0;
int minYVal = 0;
int maxYVal = 0;
int minZVal = 0;
int maxZVal = 0;
[/code]

Next we set a variable called movement which is the level of movement we'll accept before triggering the action. You'll need to adjust this to suit your own situation (your door may move a lot more subtly whilst open than mine). In the sample code, we're allowing for movement of about -15 to +15 from our min and max values before we trigger anything:

[code language="c"]
int movement = 15;
[/code]

We will need time to run the initial test of the min and max values, so we use the ready variable to tell our loop whether we are ready to start watching for door movements within our min and max ranges:

[code language="c"]
bool ready = false;
[/code]

In our setup() Arduino function, we set the serial connection to start running when the Arduino is ready:

[code language="c"]
void setup() {
Serial.begin();
}
[/code]

Within our loop, we perform all our watching of our accelerometer values from the Bean. This will all be readable via the acceleration variable we set up at the start of the loop() function:

[code language="c"]
void loop() {
AccelerationReading acceleration = Bean.getAcceleration();

// Our accelerometer tests
}
[/code]

Continue reading %Automating LIFX Lights With The LightBlue Bean and IFTTT%

Why Agile is a Competitive Advantage in a Digital Age

Mo, 2015-08-31 16:30

This article was sponsored by Atlassian. Thank you for supporting the sponsors who make SitePoint possible.

Atlassian, the company behind the popular project and issue tracking software JIRA, recently partnered with Harvard Business Review Analytic Services to write a report on the successes of agile software development. The report outlines the recent shift in development trends, and how the increase in competition requires software teams to meet deadlines faster than ever. Moving to an agile workflow is the key to rapid development and release cycles, but there’s a trick to doing agile the right way. Let’s go over a few key points highlighted in the report in order to gain a better understanding of the best way to do agile.

The History of Agile

As it turns out, the agile process has been around for some time. Nearly two decades in fact. But only recently has the method of software development gained acceptance as a mainstream best practice. Although its taken a while to grow in popularity, the report from Atlassian and Harvard states that “IDC estimates the market size for agile lifecycle management tools will surpass $1 billion in worldwide revenues by 2017.” This means that agile’s popularity shows no signs of slowing down. Isn’t it time your team took notice?

So what makes agile so special? As the report outlines, agile differs from the traditional waterfall approach to programming. This waterfall method breaks down programming into several iterative steps, including planning, design development, testing, and implementation. Each step is designed to take place in succession, with no overlap occurring between the next. As you may be aware, this approach has its difficulties. Each step can take a long time to be completed, and often gets delayed due to changing business requirements. Of course the most important reason to choose agile over the waterfall approach is communication. With the traditional waterfall approach, it becomes difficult to create an environment of teamwork and collaboration, since each phase of the project needs to happen successively.

With agile, the waterfall approach is broken up into a much smaller scale, so that incremental parts of the project are can be iterated on at a much faster pace. This in turn promotes teamwork and communication, since all team members are encouraged to work with each other in order to deliver a smaller piece of the whole project.

Continue reading %Why Agile is a Competitive Advantage in a Digital Age%

Writing PHP Git Hooks with Static Review

Mo, 2015-08-31 16:00

If you’ve been using Git for more than a short length of time, you’ll hopefully have heard of Git hooks. If not, Git hooks, as Andrew Udvare introduced here on SitePoint back in August of last year, are scripts which run, based on certain events in the Git lifecycle, both on the client and on the server.

There are hooks for pre- and post-commit, pre- and post-update, pre-push, pre-rebase, and so on. The sample hooks are written in Bash, one of the Linux shell languages. But they can be written in almost any language you’re comfortable or proficient with.

As Tim Boronczyk pointed out in September 2013, there are a wide range of meaningful purposes which hooks can be put to. These include linting, spell-checking commit messages, checking patches against accepted coding standards, running composer, and so on.

Now, PHP’s a great language, don’t get me wrong, but it’s not necessarily the best language for shell scripting. Admittedly, it’s gotten a lot better than it once was. But compared to languages such as Bash, Python, and Ruby, it hasn’t been quite as suitable for creating Git hooks; that is, until now.

Thanks to Static Review, by Samuel Parkinson, you can now write Git hooks with native PHP, optionally building on the existing core classes. In today’s post, I’m going to give you a tour of what’s on offer, finishing up by writing a custom class to check for any lingering calls to var_dump().

Installing the Library

Like most, if not all modern PHP libraries and packages, StaticReview is installable via Composer. To install it in your project, run composer require sjparkinson/static-review in the root of your project. With that, let’s get going.

Continue reading %Writing PHP Git Hooks with Static Review%

JSON Validation by Committee

Mo, 2015-08-31 14:00

In my previous post, I went through the paces of creating a JSON Schema to describe the JSON that my service will accept and return. The process leans on the prmd gem to supply the initial JSON Schema templates, as well as validation and document generation. All in all, it's a process that feels like it should be more automated. I went through a fair amount of pain to get the schema created, manually defining types and links in my text editor. At the end of the effort, I have a .json file that describes what my API will accept and return, as well as matching Markdown documentation to boot.

In that post, I made promise of something better. A land where writing unit tests that verify the JSON returned by my Rails API is possible. A land where the production application will reject requests that do not conform to our JSON schema. Does that sound like a wonderful place? It does to me.

This post will build that land, showing you how to feed the schema into tools provided by the committee gem, using those tools to verify tests and application requests.

Continue reading %JSON Validation by Committee%

Five Fantastic Editorial Calendars For Content Makers

So, 2015-08-30 12:55

He who controls the spice controls the universe. Now swap spice for content and universe for Internet, and you'll begin to understand just how important content has become in the digital age. Planning, assigning, creating, scheduling and publishing content – the five major stages of content production – can quickly get out of hand if […]

Continue reading %Five Fantastic Editorial Calendars For Content Makers%

Build a Countdown Timer in Just 18 Lines of JavaScript

Fr, 2015-08-28 18:00

Sometimes in life, you’re going to need a JavaScript countdown clock for something other than a doomsday device. Whether you have an event, a sale, a promotion, or a game, you can benefit from building a clock in raw JavaScript rather than reaching for the nearest plugin. While there are many great clock plugins, here are the benefits you’ll get from using raw JavaScript:

  • Your code will be lightweight because it will have zero dependencies.
  • Your website will perform better because you won’t need to load external scripts and style sheets.
  • You’ll have more control because you will have built the clock to behave exactly the way you want it to (rather than trying to bend a plugin to your will).

So, without further ado, here’s how to make your own countdown clock in a mere 18 lines of JavaScript.

Basic Clock: Count down to a Specific Date or Time

Here’s a quick outline of the steps involved in creating a basic clock:

  • Set a valid end date.
  • Calculate the time remaining.
  • Convert the time to a usable format.
  • Output the clock data as a reusable object.
  • Display the clock on the page, and stop the clock when it reaches zero.
Set a Valid End Date

First, you’ll need to set a valid end date. This should be a string in any of the formats understood by JavaScript’s Date.parse() method. For example:

The ISO 8601 format:

var deadline = '2015-12-31';

The short format:

var deadline = '31/12/2015';

Or, the long format:

var deadline = 'December 31 2015';

Each of these formats allows you to specify an exact time (in hours minutes and seconds), as well as a time zone (or an offset from UTC in the case of ISO dates). For example:

var deadline = 'December 31 2015 23:59:59 GMT+02:00';

You can read more about date formatting in JavaScript in this article.

Calculate the Time Remaining

The next step is to calculate the time remaining. To make that happen, we need to write a function that takes a string representing a given end time (as outlined above), and calculate the difference between that time and the current time. Here’s what that looks like:

function getTimeRemaining(endtime){ var t = Date.parse(endtime) - Date.parse(new Date()); var seconds = Math.floor( (t/1000) % 60 ); var minutes = Math.floor( (t/1000/60) % 60 ); var hours = Math.floor( (t/(1000*60*60)) % 24 ); var days = Math.floor( t/(1000*60*60*24) ); return { 'total': t, 'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds }; }

First, we’re creating a variable t, to hold the remaining time until the deadline. The Date.parse() function is native JavaScript that converts a time string into a value in milliseconds. This allows us to subtract two times from each other and get the amount of time in between.

var t = Date.parse(endtime) - Date.parse(new Date()); Convert the Time to a Usable Format

Now we want to convert the milliseconds to days, hours, minutes, and seconds. Let’s use seconds as an example:

var seconds = Math.floor( (t/1000) % 60 );

Let’s break down what’s going on here.

  1. Divide milliseconds by 1000 to convert to seconds: (t/1000)
  2. Divide the total seconds by 60 and grab the remainder—you don’t want all of the seconds, just the ones remaining after the minutes have been counted: (t/1000) % 60
  3. Round this down to nearest whole number—because you want complete seconds, not fractions of seconds: Math.floor( (t/1000) % 60 )

Repeat this logic to convert the milliseconds to minutes, hours, and days.

Output the Clock Data as a Reusable Object

With the days, hours, minutes, and seconds prepared, we’re now ready to return the data as a reusable object:

return { 'total': t, 'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds };

This object allows you to call your function and get any of the calculated values. Here’s an example of how you’d get the remaining minutes:

getTimeRemaining(deadline).minutes

Convenient, right?

Display the Clock and Stop It When It Reaches Zero

Now that we have a function that spits out the days, hours, minutes, and seconds remaining, we can build our clock. First we’ll create the following HTML element to hold our clock:

<div id="clockdiv"></div>

Then we’ll write a function that outputs the clock data inside our new div:

function initializeClock(id, endtime){ var clock = document.getElementById(id); var timeinterval = setInterval(function(){ var t = getTimeRemaining(endtime); clock.innerHTML = 'days: ' + t.days + '<br>' + 'hours: '+ t.hours + '<br>' + 'minutes: ' + t.minutes + '<br>' + 'seconds: ' + t.seconds; if(t.total<=0){ clearInterval(timeinterval); } },1000); }

This function takes two parameters: the id of the element that will contain our clock and the end time of the countdown. Inside the function, we’ll declare a variable called clock and use it to store a reference to our clock container div so that we don’t have to keep querying the DOM.

Continue reading %Build a Countdown Timer in Just 18 Lines of JavaScript%

Watch: Combining Dynamic Strings with Python

Fr, 2015-08-28 17:30

Imagine we've been tasked with creating a company slogan. To allow some parts to change, we'll use variables. Combining all of these parts into a great looking slogan will be done using string concatenation. Let's jump in and see how its done.

Imagine we've been tasked with creating a company slogan. To allow some parts to change, we'll use variables. Combining all of these parts into a great looking slogan will be done using string concatenation. Let's jump in and see how its done.

Loading the player...

Continue reading %Watch: Combining Dynamic Strings with Python%

Logging with Monolog: From Devtools to Slack

Fr, 2015-08-28 16:00

Logging is an important part of the app development/maintenance cycle. It’s not just about the data you log, but also about how you do it. In this article, we are going to explore the Monolog package and see how it can help us take advantage of our logs.

Installation

Monolog is available on Packagist, which means that you can install it via Composer.

composer require 'monolog/monolog:1.13.*'

However, there is a great chance that you’re using a framework for your app. Monolog provides a list of integrations for most popular frameworks. I’m using Silex for this demo, but I won’t be using the provided integration to show how you can configure Monolog for any of your apps.

The Logger

When you create a new logger, you should give it a channel name. This is how you distinguish your list of loggers. I will bind my logger to the app container.

// app/bootstrap/container.php $logger = new \Monolog\Logger('general'); $app->container->logger = $logger;

Because Monolog is PSR-3, you can be sure that you are adhering to the PHP-FIG standards. This will allow you to switch to any other implementation if you don’t feel comfortable with Monolog (I don’t see any reason why you wouldn’t). You can now start logging using one of the following methods, depending on your log level. (log, debug, info, warning, error, critical, alert, emergency).

Continue reading %Logging with Monolog: From Devtools to Slack%

Generating a Useful Style Guide with Sketch App

Fr, 2015-08-28 15:00

When it comes to designing large multi-artboard websites in Sketch App, Shared Styles, Text Styles and Symbols are your biggest allies. Nobody wants to keep recreating those call-to-action buttons over and over.

And while we could simply group (command+g) these button layers together and duplicate (command+d), what happens when we decide that these buttons actually need to be another colour? Styles and Symbols allow us to make mighty artboard-wide changes to a specific element.

Classing Reusable Styles

I’m going to start off with a rather cliché “here’s one we did earlier”; if you want to follow along step-by-step you can download the sample .sketch file here.

Start by selecting the middle body of text under the heading. On the right-hand side (The Inspector), click the dropdown box that says “No Text Style”, and then “Create New Text Style”.

Give this style a name - I chose “Header Text”. If you ever want to reuse this style anywhere else in the design, you can simply click on that dropdown box again and select “Header Text”.

If you code any CSS, then you’ll already know that this is exactly how we use CSS classes, and it should feel re-assuringly familiar.

You might find what we just did incredibly boring, but I swear to you, its true beauty will be much more apparent later on.

Defining Entire Elements with Reusable Symbols

Now…Symbols.

Symbols can be applied to Groups of layers only (select multiple layers, then hit command+g), which comes in handy when you need to reuse elements containing multiple layers but you’re not willing to “flatten” them.

Lets try it out on the yellow button - click the same dropdown box that now says “No Symbol” and then “Create New Symbol”. Let's call it “Yellow Button”.

Again, we’ll only experience the true magic of this later on.

Explaining Your Styles with the Sketch Notebook

Knowing why a given style was originally created is often the biggest challenge in returning to project files/graphics. At the time it was probably abundantly clear that the 'red buttons are for sale items' – but 7 months later someone is staring at those red buttons with a furrowed brow. What does it all mean??

Sketch Notebook is an add-on that’s going to let us leave comments on our artboards. For those that use our .sketch file afterwards, they’ll need to refer to these comments as a style guide when building upon the design or developing it with code.

First, navigate to PluginsReveal Plugins Folder, and then download the Sketch Notebook Plugin into that folder. If you use a plugin management interface such as Sketch Toolbox, you’ll find Sketch Notebook is downloadable from there too.

When you’re all set, click on the yellow button once again and run the keyboard shortcut; command+option+control+9.

Your comment should already have a title and it’ll be referenced by the number one. Add your comment, something along the lines of “Should be used as a call-to-action in the green header only.”

You'll notice that Sketch Notebook will automatically append a sidebar to the right-hand side of your artboard; the yellow button will have a “1” next to it that references your notebook comment.

Bonus: Creating a Separate Style Guide Artboard

Press “A” to begin choosing a new artboard. It doesn’t really matter what size the artboard is because this’ll only be an artboard for housing our reusable user interface elements as a separate style guide that can be referred to later on. You can declare sizes and a background colour in The Inspector.

Now we’ll start clicking on the elements that we want to copy over to our style guide artboard, in our case this is the “Header Text” and “Yellow Button”. Right-click and choose “Copy”, and then right-click again on our new artboard and choose “Place Here”. In the Layers Panel (on the left), double-check that we’re copying into the correct artboard; a simple drag and drop from the Layers Panel will do the trick.

As you can see from the screenshot image above, I’ve used The Inspector to change the background colour of the button. Since the (imaginary) client has requested that all buttons now be black, it’s highly convenient that all of our buttons are linked by a common Symbol - “Yellow Button” - which triggers a document-wide change.

Continue reading %Generating a Useful Style Guide with Sketch App%

Push Notifications in Ionic Apps with Google Cloud Messaging

Fr, 2015-08-28 15:00

In this tutorial we're going look at how to implement push notifications in an Android App using the Google Cloud Messaging Platform. We will be using the Ionic framework and Cordova to create the app. The server component will be implemented using Node. You can checkout all the code for the project that we will be building from Github.

Continue reading %Push Notifications in Ionic Apps with Google Cloud Messaging%

Phoenix for Railsies: Form Helpers and Models

Fr, 2015-08-28 14:00

Phoenix is a web framework built for Elixir, an awesome language that’s built on the Erlang Virtual Machine. Coming from a Rails background, Phoenix seems immediately familiar. Although it is missing a few of the niceties that Rails gives us, Phoenix has excellent support for technologies such as WebSockets, which makes it a great candidate […]

Continue reading %Phoenix for Railsies: Form Helpers and Models%

Laugh Your Way to More Sales: How to be Funny

Fr, 2015-08-28 03:24

If you can make someone laugh, you can make them do anything. Likability matters – in business, in love, basically, everything in life requires you to be likable by other people. One easy way to be likable is to make people laugh. Yes, there are some anomalies, who don’t like to laugh, and I’d recommend […]

Continue reading %Laugh Your Way to More Sales: How to be Funny%

Introduction to the MEAN Stack

Do, 2015-08-27 20:00

It was a long time ago since the acronym LAMP (Linux Apache MySql PHP) was created. Today another very common stack is the MEAN stack. Probably not all of you know what that the acronym “MEAN” stands for, so let's start with the basic. MEAN stands for MongoDB, Express, AngularJS and Node.js. It deals with a full stack JavaScript solution for building websites and web applications. From the database to the back-end code and the front-end code, everything is written using JavaScript. In case you aren’t familiar with the technologies used by the MEAN stack, you can find a short introduction about these technologies in the following section.

MEAN

M stands for MongoDB, the world’s leading NoSQL database. That’s a kind of document type database that stores its data into a JSON-like formatted binary file called BSON (Binary JSON). It’s easy to use, and for JavaScript developers it should be as simple as working with JSON.

E stands for Express, a lightweight, minimalist framework built for Node.js. It’s been created for web applications and APIs, and comes with a myriad of HTTP facilities for the developer.

A stands for AngularJS, the Model-View-Whatever JS framework build by Google. AngularJS makes API consuming as simple as it could be, so using it as the client-side of MEAN is very helpful for every developer. Moreover, AngularJS is optimized for mobile development, so by using the same code base on the browser, you have already built a mobile app for the web application you’re developing.

N stands for Node.js, the foundation of Express. It runs on Chrome’s V8 engine and is capable of non-blocking, event-driven I/O. The Node.js application will handle multiple requests on a single service without them blocking each-other (hence non-blocking).

Continue reading %Introduction to the MEAN Stack%

An Editable Grid with jQuery, Bootstrap, and Shield UI Lite

Do, 2015-08-27 18:30

In this short tip, I provide a few easy steps to set up an editable grid (or table) using Bootstrap and Shield UI Lite.

Shield UI Lite is an open source jQuery library that includes, among other components, a jQuery grid. The grid supports editing out-of-the-box, as well as sorting, grouping, and different column editors.

About Shield UI Lite

Shield UI is a web component development company that specializes in the design, development, and marketing of UI widgets for pure JavaScript development, as well as for development in ASP.NET, ASP.NET MVC, and Java Wicket. The company offers Data Visualization components, as well as a whole array of standard web development components, such as grids, barcodes – one and two dimensional, extended input components – such as numeric and masked textboxes, and many more.

The Shield UI Lite Suite is one of the newest open source libraries on the market and what is specific about it is that it contains a wealth of components, all of which are feature rich and mature. This includes the jQuery Grid, which supports all important web grid operations out-of-the-box. The component supports editing with either inline or standard edit form editing, as well as editing with an external form. Also supported is cell editing.

In addition to this, the Shield UI Grid has a built-in datasource component, which facilitates the binding to all types of data – from local JSON structures, to remote web services; the built-in DataSource also takes care of all delete, update and insert operations.

For data-heavy applications, the Shield UI jQuery widget offers an enhanced virtual scrolling feature significantly improves performance, even when working with millions of real data records. To see more examples of the component and its options, you can refer to the online demos or the documentation.

Using the Code

For the editable grid that we’ll be creating, I’m using a local data source in order to keep things simple. The source code for the libraries can be found on GitHub. The full sample code, along with all sample data used, as well as additional CSS is available in the CodePen demo.

The first step in setting up the layout is to use a standard Bootstrap container. In our case, this is a div with a Bootstrap panel nested inside. Since any standard web grid component usually hosts a lot of data, our layout spans the full width of the screen.

The code for this step is straightforward and looks like this:

[code language="html"]
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="text-center">Bootstrap Editable jQuery Grid
<span class="fa fa-edit pull-right bigicon"></span></h4>
</div>
<div class="panel-body text-center">
<div id="grid"></div>
</div>
</div>
</div>
[/code]

This is all the HTML needed to set up the sample. The next step is adding references to all the resources used in the sample, such as stylesheets, JavaScript files, and data.

The data used for the example is a standard JSON collection, which is loaded separately in order to be passed to the grid component. Using a local data source simplifies the setup. Additionally we need the stylesheet for the grid and the JavaScript for initializing it.

The inclusion of these resources is demonstrated below:

The CSS:

[code language="html"]
<link rel="stylesheet" href="shieldui-lite.min.css">
[/code]

The scripts:

[code language="html"]
<script src="shieldui-lite-all.min.js"></script>
<script src="shortGridData.js"></script>
[/code]

Setting up the Grid

The next step in the process is setting up the Shield UI Lite grid component. Once we have included the necessary resources, we can initialize it with some JavaScript in the document.ready handler.

There are two logical parts in describing the component. The first is handling the datasource for the data that will be visualized in the grid, and the other one is setting up the columns, which will be actually rendered, as well as any additional settings, such as sorting, hover effects, etc.

Continue reading %An Editable Grid with jQuery, Bootstrap, and Shield UI Lite%