Javascript News

Syndicate content
Pipes Output
Updated: 48 weeks 6 days ago

Deploy Your Rails to OpenShift

Do, 2015-09-17 14:00

OpenShift is Red Hat's Platform-as-a-Service (PaaS that allows developers to quickly develop, host, and scale applications in a cloud environment. With OpenShift you have choice of offerings, including online, on-premise, and open source project options.

With Git, developers can deploy web applications in different languages on the platform. OpenShift makes deployment hassle-free and it is also a free and open source software.

In this tutorial, I'll make a rails app with a static page and deploy it to the OpenShift platform. The purpose of this tutorial is to see how the deployment process works.

Continue reading %Deploy Your Rails to OpenShift%

Validating Input in Sass Mixins and Functions

Do, 2015-09-17 13:00

When you write Sass and others use it, it’s quite possible for them to make mistakes with your code. Actually, let’s be honest, when I write Sass and use it days later (or even hours later), I make mistakes with my code. You might too. Fortunately, Sass has a number of functions that help us validate the input that developers put in to the Sass we write.

These techniques are especially useful for teams that share Sass mixins or maintain a starter kit or set of mixins and functions. Developers have two options when using a shared Sass library: either they can email, chat, ping, or otherwise interrupt each other for help with custom mixin, or use detailed documentation including code validation to help each other easily troubleshoot code. (For what it’s worth, this isn’t just a Sass thing: any shared code requires communication through interruption or documentation.) Let’s learn about a few of the most useful Sass validation methods now.

Validating Single Values

Mixins and functions take parameters. If you’re passing code off to another developer at work or releasing an open source library, you’ll want to make sure the arguments match your intentions. These functions are useful for validating variables in arguments.

Making sure variables exist: variable-exists()

If your function or mixin relies on a developer-defined variable, make sure the variable exists by using the aptly-named variable-exists() function. This function returns true or false based on whether or not a variable has been created and defined.

[code language="sass"]
@mixin create-font-size() {
@if global-variable-exists(base-font) {
font-size: $base-font;
} @else {
@error "Please define the variable `$base-font`.";
}
@if global-variable-exists(line-height) {
line-height: $line-height;
} @else {
@error "Please define the variable `$line-height`.";
}
}

// developer's code
$base-font: 18px;
$line-height: 1.5;
.element {
@include create-font-size;
}
[/code]

However, a better option than relying on developers’ correctly setting global variables is to include these default variables in your library:

[code language="sass"]
// Your plugin:
$base-font: 18px !default;
$line-height: 1.5 !default;

@mixin create-font-size() {
// etc...
}

// developer's code:
$base-font: 16px;
p {
@include create-font-size();
}
[/code]

Checking a value’s data type: type-of()

If you need to know what type of value a variable represents, use type-of(). This function will return one of the following strings:

  • string
  • color
  • number
  • bool
  • null
  • list
  • map

This is useful for validating certain kinds of input. You can ensure that a developer only passes a numerical value to a mixin that creates sizes:

[code language="sass"]
@mixin size($height, $width: $height) {
@if type-of($height) == number {
height: $height;
} @else {
@warn "Make sure that `$height` is a number.";
}
@if type-of($width) == number {
width: $width;
} @else {
@warn "Make sure that `$width` is a number.";
}
}
[/code]

You can also use type-of() to ensure that color mixins only deal with colors:

[code language="sass"]
@function color-fade($color) {
@if type-of($color) == 'color' {
@return rgba($color, .8);
} @else {
@warn "Make sure you pass a valid color to the color-fade() function.";
}
}
[/code]

If you need a developer to create a map of config settings for a theme, you can make sure they have a valid map:

Continue reading %Validating Input in Sass Mixins and Functions%

Indiana Jones and the Lost SVG Map Editor

Do, 2015-09-17 01:01

Maps are great devices for telling stories.

Game of Thrones famously uses a map in the title sequence to help set the epic tone of their universe. Casablanca sets up its opening scenes with a map centered on Paris that traces a thick black line south to Morocco.

Forty year later in ‘Raiders of the Lost Ark’, Steven Spielberg was using a similar trick to help us track Indiana Jones’ Boeing seaplane on a map below.

Maps can be powerful on the web too, letting us tie important ideas and numbers to specific geographical areas. This could be anything including:

  • Sales
  • Subscribers/viewers
  • Paid Members
  • Regional Offices

But where do you start with creating maps? Screen capturing Google Earth isn’t going to cut it. You could draw a map from scratch, but coastlines are finicky, time-consuming things to create.

Using AMCharts to Make for SVG Maps

AMCharts offers a bunch of really cool JavaScript charting tools, including pie charts, line graphs and bar graphs. But they also have a rather nifty map creation tool in beta called Pixel Map Generator.

The tool is easy to get started with. Controls at the bottom of the app let you zoom, position and frame the map to your liking, so if you only need a small area, that’s fine. A dropdown lets you select individual countries.

A toolbar on the left lets you add routes, re-color elements, annotate and label your map. Pulling together the basic components of a useful map takes minutes.

I think the really cool part are the export options. PNG, HTML (JS) or SVG. That last option is the one I like. Typically SVG written by graphics editors can be very messy and unwieldy. AMChart seems to write clean, well-structured SVG files. You can save that file and embed it straight into your next site/web app.

But you can also do more.

You could open this SVG map directly in Adobe Illustrator, but I wouldn’t advise it – the file will get rewritten and you’d lose a lot of its elegance.

[author_more]

[/author_more]

A more interesting idea is to copy the SVG code and paste it straight into a Codepen HTML panel. Even if you know zero about SVG markup, you’ll recognise it as a ‘HTML-like file’ that you can start manipulating and styling with CSS.

Here’s one I prepared earlier.

See the Pen dYGxPE by SitePoint (@SitePoint) on CodePen.

Like HTML, you can add classes and IDs to elements and then target those elements with CSS - even transforms, animations and transitions.

That’s a lot of design freedom to play with and AMCharts does all the hard map-drawing bits.

Continue reading %Indiana Jones and the Lost SVG Map Editor%

How I Became a Resident of Estonia

Mi, 2015-09-16 22:00

I’ve lived in three countries in my life, and I travel on a regular basis. I wouldn’t go as far as to say that we should have global open borders, but there are ways that the life of the new breed of global entrepreneurs could be easier.

One of those is registering a business. Registering a business outside of your country of residence has historically been reserved for those who have big businesses or those up to no good (or both). I would guess that many of you reading this live in one country, have perhaps lived in (or have strong connections to) another, and work for clients in others—paid in a variety of currencies.

A Game Changer from Estonia

Enter Estonia’s e-Residency program, an intriguing idea with big aims.

e-Residency offers to every world citizen a government-issued digital identity and the opportunity to run a trusted company online, unleashing the world’s entrepreneurial potential.

I think it’s a fantastic concept, and I love that many smaller countries around the world have decided to try these sorts of ideas. They have nothing to lose, so are trying ideas that larger or older countries either wouldn’t or couldn’t ever try.

One of the main advantages of Estonia’s program is that Estonia is an EU member, which opens your business to the EU trading zone and gives you access to bank accounts and financial tools (e.g. PayPal) in Euros—a globally recognized currency.

I’m a British citizen, but lived in Australia for seven years (where my business is currently registered), and I’ve been living in Germany for the past year. Much of my contract and freelance work is undertaken with clients outside of Germany, and I remain uncertain what my best approach is.

To me, and many like me, Estonia’s e-Residency program seems a dream come true, and I was keen to give it a try. I was aware of the program already, and then met some of its representatives at an event in Finland who encouraged me to sign up on the spot. I wanted to research more first (and write this article), but the fact it was even possible was amazing.

This Is Not Citizenship

As an e-Resident of Estonia, your rights are purely for business. So for anyone looking for a loophole to EU citizenship, this isn’t it. You get no extra rights to entry that you’re not entitled to already.

Continue reading %How I Became a Resident of Estonia%

How to Use SSL/TLS with Node.js

Mi, 2015-09-16 20:00

Using HTTPS is becoming more and more prevalent, therefore we should know how to implement SSL/TLS in our Node.js applications - either for accessing HTTPS resources or for providing resources with encryption. What does HTTPS actually mean? What does it imply? Are there any constraints and restrictions? We will try to find an answer for all of these questions.

Additionally, we should not only try to protect our clients by providing HTTPS, but we should also demand encrypted connections from the servers we are talking to. We will see that possibilities exist to activate the SSL/TLS layer even if it wouldn’t be enabled by default. Let’s start with a short review of HTTPS’s current state.

HTTPS Everywhere

On February the 17th 2015 the HTTP/2 protocol was approved by the IESG to be published as a proposed standard. This was a major milestone. Now we can all upgrade our servers to use HTTP/2. One of the most important aspects is the backwards compatibility with HTTP 1.1 and negotiation mechanism to choose a different protocol. Although the standard does not specify mandatory encryption, most browsers will only support HTTP/2 over TLS. This gives HTTPS another boost. Finally HTTPS everywhere!

What does our stack actually look like? From the perspective of a website running in the browser (application level) we have roughly the following layers to reach the IP level:

  1. Client Browser
  2. HTTP
  3. SSL/TLS
  4. TCP
  5. IP

HTTPS is nothing more than the HTTP protocol on top of SSL/TLS. Hence all the rules of HTTP still have to apply. What does this additional layer actually give us? There are multiple advantages. We get authentication by having keys and certificates. Also a certain kind of privacy and confidentiality is guaranteed, as the connection is encrypted in an asymmetric manner. Last but not least data integrity is also preserved, i.e. that transmitted data cannot be changed during transit.

One of the most common myths is that using SSL/TLS requires too many resources and slows down the server. This is certainly not true anymore. We also do not need any specialized hardware with cryptography units. Even for Google, the SSL/TLS layer accounts for less than 1% of the CPU load. Furthermore the network overhead of HTTPS as compared to HTTP is below 2%. All in all it would not make sense to forgo HTTPS for having a little bit of overhead.

Continue reading %How to Use SSL/TLS with Node.js%

WordPress Hybrid Client: WordPress Powered iOS/Android Apps

Mi, 2015-09-16 19:00

WordPress Hybrid Client (WPHC) is an Open Source project available on GitHub that lets you easily create iOS and Android versions of your WordPress website for free.

WPHC is based on the Open Source hybrid stack Ionic SDK, Cordova, and Crosswalk .

Features
  • Push notifications
  • Bookmarks (offline mode)
  • Google Analytics support
  • Automatic content updates
  • Social buttons
  • Accessibility (post font size)
  • Multi languages (English, French, Chinese)
  • Infinite scroll
  • Syntax highlighter for tech blogs
  • Image cache
  • App rate
Built with WPHC

Here are a few examples of projects built using WPHC:

Continue reading %WordPress Hybrid Client: WordPress Powered iOS/Android Apps%

Syncing CSS Animations with HTML5 Audio

Mi, 2015-09-16 18:00

CSS and HTML have opened a rich playing field for adding multimedia content to your web page, web app, and e-book projects. One innovative way of combining these two technologies is adding sound effects to your CSS animations using <audio> elements and triggering them with a little bit of JavaScript.

Although sound on the web isn’t universally welcome, there are cases when it can enrich the user experience without being an unnecessary annoyance. Examples are artist and gaming websites or content for children. Sound can even be useful in certain cases to visitors with disabilities.

The most important part of the sound animation process is adjusting your CSS animation to the audio to achieve an accurate in-sync audio-visual experience. In this article I’ll go through the steps of syncing animation keyframes to audio timing data using an interesting example of a beating stylized heart.

See the Pen CSS Animation with Sound: Heartbeat by SitePoint (@SitePoint) on CodePen.

Constructing the Heart

The first ingredient we need is a heart we want to animate. We will construct one using CSS pseudo-elements. Having it constructed in HTML rather than using an image, even if only through pseudo-elements, gives us the opportunity to animate various CSS properties to create a more interesting animation.

We can often find more than one way to build a shape this way, but if we plan to animate it it’s worth thinking about geometry and how different structural choices affect movement and simplify the keyframes code.

In this case the simplest technique is to use two vertical rectangles rounded on top, rotated, and positioned to overlap to form a heart shape. Their size is set using percentages and they’re absolutely positioned with a bit of geometry consideration so it’s easy to scale the original shape by changing the container size. The rectangles are rotated 45 degrees clockwise and counterclockwise to form the left and right parts of the heart.

[code language="css"]
.heart::before,
.heart::after {
background-color: red;
content: "";
height: 80%;
left: 25%;
position: absolute;
top: 2%;
transform: translateZ(0) rotate(-45deg);
width: 50%;
}

.heart::after {
transform: translateZ(0) rotate(45deg);
}
[/code]

Rounded sides are set with two radii values to get an elliptic rather than circular curve, and therefore a more natural heart shape. Because rectangle side lengths have a 5/8 ratio, the ellipsis radii calculate to 50%/37.5% to round off only the corners that don’t overlap.

[code language="css"]
.heart::before,
.heart::after {
border-radius: 50% 50% 0 0 / 37.5% 37.5% 0 0;
}
[/code]

Now what remains is to adjust the transform-origin point for the rectangles so the points line up at the center of the square area where the rectangles do overlap. The same look can be achieved by adjusting the absolute position declarations instead of using the transform-origin approach. But that would later complicate the keyframes code because it would force us to control the position in more detail instead of relying on the transform scale function to do the work for us.

The transform-origin point should be calculated with regards to the coordinate system before any transforms are applied (because transforms can affect the coordinate system, for example, the rotate() function rotates the coordinate system along with the element it is applied to). Again the sides length ratio dictates the position of that point: it is easy to see that the X position is at 50%, at the center of the rectangles, but the Y position is calculated at 68.75% of the rectangle height measured from the top (55*100%/80=68.75%). Going with the specific symmetry approach pays off here too, as both rectangles share the same transform-origin point position.

[code language="css"]
.heart::before,
.heart::after {
transform-origin: 50% 68.75% 0;
}
[/code]

And now we have a beautiful symmetric heart shape. We can add an inset box-shadow, different for each rectangle, to make it all plump and 3D.

[code language="css"]
.heart::before {
box-shadow: -8px -14px 10px 0 black inset;
}

.heart::after {
box-shadow: -15px 10px 14px 0 black inset;
}
[/code]

The Sound of the Heart

To introduce audio into the page, we use the <audio> element with the path to the audio file and without the controls attribute because we don’t want the internal browser audio player to appear (read more in Using HTML5 audio and video on MDN).

[code language="html"]
<audio id="heartbeat" src="heartbeat.mp3" preload="auto">
Your browser does not support the <code>audio</code> element.
</audio>
[/code]

Instead of the controls, we use JavaScript to manipulate the playback. This example uses buttons to start and reset the track, but with a little bit more work we could do without the buttons and start and reset the audio when the heart element is clicked or hovered.

Our sound is the sound of a heartbeat repeated four times and it will serve as the sound our CSS animation will follow.

Flex that Muscle

To make our heart tick, we need to change its shape from original, resting heart, to the state when the muscle is flexed. To flex the heart we scale it down a bit and change its shape with border-radius.

Here is how the flexed styles would read if we needed them static, outside of the animation:

Continue reading %Syncing CSS Animations with HTML5 Audio%

Watch: Getting Started with Grunt

Mi, 2015-09-16 17:30

Getting started with GruntJS aims to help simplify some of the concepts that people sometimes have trouble comprehending. Throughout this screencast, I will provide an in depth explanation on the core components of Grunt and take you through the process of configuring a gruntfile from start to completion so that you can truly understand how GruntJS works.

Code sample for this screencast is available on GitHub.

Loading the player...

Continue reading %Watch: Getting Started with Grunt%

The Ultimate Guide to Landing Page Builders for Startups

Mi, 2015-09-16 16:00

In a world that moves this fast, ideas must be prototyped, tested and launched in as little time as possible. Gone are the days when companies and individuals could afford to spend months designing a page only to find out that buyers weren’t even interested in the product it featured. Reaching product-market fit, or the […]

Continue reading %The Ultimate Guide to Landing Page Builders for Startups%

Build a Superfast PHP Server in Minutes with Icicle

Mi, 2015-09-16 16:00

Event-based programming is a strange topic for PHP developers. In a language as procedural; events are little more than function calls. Nothing happens between events, and all meaningful code is still blocking.

Languages like JavaScript show us what PHP could be like if event loops were at the center. Some folks have taken these insights and coded them into event loops and HTTP servers. Today we’re going to create an HTTP server, in PHP. We’ll connect it to Apache to serve static files quickly. Everything else will pass through our PHP HTTP server, based on Icicle.

You can find the example code at https://github.com/sitepoint-editors/icicle-http-server

Continue reading %Build a Superfast PHP Server in Minutes with Icicle%

The Full Stack Overflow Developer

Mi, 2015-09-16 15:30

This article is part of a web development series from Microsoft. Thank you for supporting the partners who make SitePoint possible.

In a few talks and interviews I lamented about a phenomenon in our market that’s always been around, but seems to be rampant by now: the one of the Full Stack Overflow developer. Prompted by Stephen Hay on Twitter, I shall now talk a bit about what this means.

Full Stack Overflow developers work almost entirely by copying and pasting code from Stack Overflow instead of understanding what they are doing. Instead of researching a topic, they go there first to ask a question hoping people will just give them the result.

[author_more]

In many cases, this works out. It is amazing what you can achieve by pasting things you don’t understand, that people who know what they are doing put out there.

I am not having a go at Stack Overflow here. It is an incredible resource and it is hard to create a community like this and not drown in spam and mediocrity (trust me, I am an admin on several technical Facebook groups).

We had that problem for a long time. I challenge anyone learning PHP to not simply copy the code examples in the notes. For years, code reference sites have given us answers we wanted, but didn’t need. Heck, even Matt’s Script Archive is probably the source for many a spam mailer as people used formmail.pl without knowing what it does.

I am, however, worried about how rampant this behaviour is today. Of course, it is understandable:

  • Creating something is more fun than reading up on how to create something.
  • Using something that works immediately, even if you don’t know how it does it, feels better than encountering the frustration of not being able to fix something.
  • You feel like you cheated the system – shortcuts are fun, and makes you feel like you’re cleverer than all those chumps who spend all this time learning.
  • Our job is mainstream and there is a massive need for developers. The speed of how we are asked to deliver has massively increased. People want results quicker, rather than cleaner.

We, as a community, are partly to blame for breeding this kind of developer:

  • When we answer questions, we tend to give the solution instead of analysing what the person really needs. This is much more work, so we tend to avoid it.
  • Posting the "one true solution" and winning a thread on Stack Overflow feels great – even if we have no plan whatsoever to come back to it later if it turns out not to be such a good idea any longer as the environment changed.
  • Getting recognition, Karma and upvotes for giving the solution is much easier than getting it for being the person who asks the right questions to get to the source of the problem.
  • It is easy to lose patience with getting the same questions over and over again and a "just use jQuery" is easy to paste.
So what? Why is it a problem if people are faster and more effective in releasing products?

Of course, you can call me a grumpy old so-and-so now and tell me that the concept of learning the basics in software is an outdated concept. The complexity of today’s products makes it almost impossible to know everything and in other, highly successful environments using lots of packages and libraries is par for the course. Fine, although we seem to be understanding that software as a whole might be more broken than we care to admit, and this might be one of the causes.

There are several problems with Full Stack Overflow development:

Continue reading %The Full Stack Overflow Developer%

Scanning a QR Code with Cordova

Mi, 2015-09-16 15:00

A barcode is a machine readable image that encapsulates some data about the object to which it’s attached to. A Quick Response Code (QR Code) is a popular type of barcode for mobile use due to its fast readability and greater storage capacity compared to ordinary barcodes.

In this tutorial I will create a Cordova app which can scan QR Codes and store data obtained from decoding the QR Codes. To scan the barcode I will use the BarcodeScanner Cordova plugin.

Continue reading %Scanning a QR Code with Cordova%

JavaOne Track Highlights: Java and Server-Side Development

Di, 2015-09-15 23:39

The JavaOne conference will be held between October 25 and 29. SitePoint is partnering with Oracle to share highlights from the conference.

The JavaOne 2015 Content Catalog is live. We’ve got hundreds of great sessions covering all things Java related. To help you find exactly what you’re looking for, be it Server-Side Development, Security, or anything in between, the sessions have been placed into tracks. There are 8 tracks at this year’s conference designed to be the ultimate guide to help you stay on top of the latest innovations in Java technologies. This is the sixth post in a series on the tracks being offered at this year’s conference. Last week, we looked at the Java and the Internet of Things track. Today, let’s look at the Java and Server-Side Development track and a few featured sessions.

This track focuses on the Java Platform, Enterprise Edition (Java EE). Looking to get the most out of Java EE 7 and look forward to 8? You’ve come to the right place. Sessions on this track will keep you moving along with the best new methods and updates for staying on top of security, persistence, CDI, transactions, Java Message Service 2.0, Concurrency Utilities, and batch APIs. Java EE experts will also teach you how to develop secure and scalable services with technologies like WebSockets, JSON, and JAX-RS 2.0.

As far as featured sessions go, this track has 3 great Hands-On Labs to look out for. These sessions are unique because of their hands-on nature, meaning that you’ll walk away with some new tools in your belt. For example, Yuriy Artamonov poses a challenge in his session “Develop a Fully Functioned Business Application in Hours with CUBA Platform.” Can you build a genuine enterprise application with commercial value in just 2 hours? He’ll show you how in this session. You’ll utilize the CUBA Platform to create an application complete with a UI, business logic, security and audit, reports, and a REST API for a bicycle workshop.

To get even more hands-on Java EE knowledge, check out “Building Applications with PostgreSQL’s jsonb Datatype, Play 2 Framework, and REST.” Developing a web application with PostgreSQL’s jsonb datatype and the REST API means that you can store all data in a single database, easily make data changes, simplify the way you manage difficult class hierarchies, save data in one table in JSON and relational view, and decrease your development time while speeding up web application performance, and Anton Kazakov from Softarex Technologies Inc. will show you how in this session. The third featured session was covered in last week’s IoT Track Highlights. It’s called “Highly Loaded Server-Side Multitask Management Systems Based on Java and Redis.” It’s a great session for those of you interested in server-side development, the IoT, or both. You’ll walk away with the knowledge of how to develop an IoT system utilizing server-based solutions. Check it out here.

To see more from this track, head over to the Content Catalog and filter by Java and Server-Side Development. Let’s not forget that this great technology is only possible because of contributions from the rich community that surrounds Java EE. What better place to get to know this community and to meet the some of the biggest innovators face-to-face than JavaOne? The Early Bird Discount is in its final days, so register soon, and don’t miss this year’s JavaOne!

SitePoint is partnering with Oracle to give away 40(!) free tickets to the JavaOne conference. To win a ticket to the conference (October 25th-29th, 2015), leave a comment below telling us how you’ll convince your boss to give you the week off for the conference. The best answers win!>

Continue reading %JavaOne Track Highlights: Java and Server-Side Development%

A Glimpse into the Windows 10 Upgrade Notification

Di, 2015-09-15 19:00

This article is part of a web development series from Microsoft. Thank you for supporting the partners who make SitePoint possible.

There’s been a lot of press lately about the Windows 10 upgrade notification appearing for users of Windows 7, 8 & 8.1. I wanted to publish an article about the experience. Whether your dev box is a Mac or PC or Linux, you can expect that many of your users will be trying Windows 10 and Microsoft Edge – the default browser – out. So it’s a good reason to do a test pass. Fortunately Edge resembles browsers like Chrome and Firefox more than past versions of IE. Let’s take a look:

Please note that this is ONLY TO RESERVE THE FREE UPGRADE, made available July 29th; this is basically telling Microsoft that you want it. IT’s NOT GOING TO INSTALL IT IMMEDIATELY! If you want to use Win 10 now, go to insider.windows.com and download the ISO.

Continue reading %A Glimpse into the Windows 10 Upgrade Notification%

Avoiding Redundancy with WAI-ARIA in HTML Pages

Di, 2015-09-15 18:00

Life’s been easy since we’ve started integrating ARIA roles in HTML code. ARIA has been providing additional semantics to help assistive technologies (ATs) and making it possible for developers to enhance the usability of web applications for people with disabilities. The fundamental question remains to date — do HTML elements need ARIA role attributes to expose their semantics?

In this article, I will cover this subject along with the new HTML5 structural elements with default implicit semantics that contest ARIA roles.

ARIA Basics and General Perceptions

WAI-ARIA (commonly known as ARIA) is a set of attributes that you can add to your HTML elements. The purpose of these attributes is simple — to communicate role, property, and state semantics to ATs by means of accessibility APIs that are present in web browsers. Stephan’s post An Introduction to WAI-ARIA is a must-read for those of you who are new to ARIA.

The general perception about ARIA in the HTML community is “don’t use ARIA code if HTML has got you covered”. The same thing can be said a little more clearly: If your HTML element is already implemented but does not have accessibility support yet, use ARIA.

Effect of ARIA Roles on Most Elements

There are some general cases in which the semantics of an HTML element can be exposed by use of an ARIA role, property, or state. A bit perplexing at first, this is known in the HTML community as the HTML element’s default implicit ARIA semantics.

However, when coding in HTML it is best to write semantically correct HTML (and thus make use of its native semantics) before setting out to integrate ARIA attributes.

ARIA roles do not add anything to the default semantics of most HTML elements.

The rule is to keep it simple — if the semantics are included in the HTML element by default then do not use ARIA. Integrating ARIA where it isn’t necessary makes for redundant code.

Does HTML4 Need ARIA Roles?

As explained by accessibility expert Steve Faulkner, all of the HTML elements that were defined in HTML4 (and earlier HTML versions) do not require ARIA roles added to uncover their default semantics because they have already been mapped.

In fact, using ARIA roles in such situations and with elements defined in HTML4 will not make a difference. If ARIA roles are used in HTML4-based code, this will necessitate extra work by you by someone reviewing your code. Therefore, it is generally advisable to not add ARIA roles to HTML elements if it can be avoided.

New Features in HTML5

According to the HTML5 Specification:

In the majority of cases setting an ARIA role and/or aria-* attribute that matches the default implicit ARIA semantics is unnecessary and not recommended as these properties are already set by the browser.

This means that new features that have been defined in HTML5 have default implicit ARIA semantics exposed by most web browsers. Despite this fact, it cannot be assumed that the HTML element you’re using is already mapped to ARIA without looking it up first. Keeping this in mind, I suggest that you add the ARIA roles for the time being to stay on the safer side of the scale — even if it means having to write redundant code.

Continue reading %Avoiding Redundancy with WAI-ARIA in HTML Pages%

Watch: Create your First WordPress Child-theme, Quick Fast

Di, 2015-09-15 17:30

Creating an awesome WordPress theme from scratch can be a daunting task, especially if you are a beginner. Thankfully, WordPress offers a much easier and quicker alternative: child themes. In this screencast, I will be showing you how to create a child theme complete with customizations.

This is the first video in the Your First Steps into WordPress Theme Development series.

Loading the player...

Continue reading %Watch: Create your First WordPress Child-theme, Quick Fast%

Venture Capitalists (VCs) Answer: How to Approach Them

Di, 2015-09-15 16:00

Unless you’re bootstrapping it, you’re well aware that the fundraising process is frustrating, draining and stressful—yet when it, literally, pays off, you’re on top of the world. To help you get to the “funded” stage, I’m sharing some key insights into how founders and CEOs can build successful relationships with venture capitalists. These insights come […]

Continue reading %Venture Capitalists (VCs) Answer: How to Approach Them%

Saving Bandwidth by Using Images the Smart Way

Di, 2015-09-15 15:00

Images are the native language of our brains. While it takes us years to learn to talk, read and write, we're processing images from the day we're born.

This allows images to convey complex ideas much faster than words–even a thousand words. They can liven up a webpage and even draw people into reading about-about a topic they make not have otherwise bothered with.

The Costs

However, on the internet, imagery doesn't come without cost. Images soak up a large percentage of the world's bandwidth and this impacts on user experience. We know that every surplus second a page takes to loads increases the bounce rate while also negatively impacting your PageRank.

In this article, we’re going to discuss a lot of important tips designed to save you both time and bandwidth

Choosing the Appropriate Image Format

Let's begin by getting right back to basics, and look at the fundamental pros and cons of each web image format (even if you think you know it all).

GIF

GIF is a lossless file format with support for transparency and animation. It is limited to a maximum palette of 256 colors. It’s not recommended for saving highly-graduated photographic images as they are made up of much more than 256 colors. It is, however, great for logos, flat-color graphics and illustrations with few gradients.

GIF’s animation abilities mean it can also be used in place of short explanatory videos.

PNG

Like GIF, PNG is also lossless and supports transparency. However, there is no native support for animation.

This format is also suitable for small sized images or images which need to be saved without losing any data. PNG images can be saved in PNG8 or PNG24 format. PNG8 is palette-based and can be used as a GIF substitute if no animation is needed. PNG8 can support up to 256 colors.

One point worth keeping in mind is that it is still common for graphics application to export PNG-8 with 2-bit transparency (i.e. pixels are either 100% opaque or 100% transparent) and this can result in jagged edges. Better editors use a graduated 8-bit transparency in their PNG export.

PNG24, on the other hand, can support up to 16 million colors. You can use the latter to save photographic images, but more complex images will mean bigger file size.

JPG

Finally, JPEG or JPG format is suited for photographic images where color may change from pixel to pixel. This format can reduce file size by a huge margin, but there are a few caveats.

Firstly, JPEG is a lossy format. This means it compresses images by selectively discarding data. This is the reason it can reduce the file size significantly, you need to make a compromise between quality of image and file size. JPG also does not support transparency.

JPEG images can be in either baseline or progressive format. Progressive format renders a lower resolution image first before progressively enhancing its quality as more data becomes available. This format also reserves layout space on page for the image which reduces page elements from reflowing during page load.

When working with JPG you should always maintain your original uncompressed images separately. Re-compressing JPEG images results in a cumulative loss of quality, as more data is discarded each time the images are saved. It is much better to start with the uncompressed original image.

Let’s Compare

Here are a few images that show the difference in file size in various images: Simple, flat-color image in .gif format. File size : 4.4 KB

Simple, flat-color image in .png format. File size : 8.5 KB

Simple, flat-color image in .jpg format. File size : 26.2 KB

Photographic image in .png format. File size : 350 KB

Photographic image in .jpg format. File size : 85 KB

As you can see, there is no glaring difference between first three images quality wise but image size increases considerably in JPEG format for images with little to no color variations. In this case, GIF provides the most savings in bandwidth.

However, the last two images are different. Here the PNG format has much larger file size. This is because there is a huge color variation and PNG does not discard data selectively. Unless you examine the images very closely you won't see much difference in quality.

The example above clearly illustrates how you can save a lot of bandwidth by simply choosing the appropriate image format.

Does 'Save for Web' Make Any Real Difference?

Photoshop's 'Save as..' option has always allowed us to create PNG, GIF and JPG images, but we've had the option of 'Save for Web...' over recent years (and Extract Assets even more recently). Is there any real difference?

In short, yes there is a very worthwhile option.

Accessed via ‘File > Save for Web...’, this interface provides lots of options such as optimizing the number of colors in PNG-8 and GIF format and setting the quality in JPEG format. You can also set a blur value which can save a few more kilobytes.

Keep in mind that once you save images this way you won't be able to modify individual pixels anymore. For this reason, it is always a good idea to have an original image backed up. Here are the above two images optimized with 'Save for Web...' option.

Simple image in optimized .png format. File size : 3 KB

Photographic image in optimized .jpg format. File size : 40 KB

Relative saving on both these images is 32% and 53% respectively. This is beneficial for both the users as well as the website owners.

Serving Resized Images

Serving images with the same resolution to users with varying screen sizes is not optimal. Sure, it saves some time but it can cost a lot of extra bandwidth. The users have to wait longer for the webpage to load and images resized with CSS don't always scale well.

To serve different images based on screen size you can use a variety of solutions like Adaptive Images or a jQuery plugin like HiSRC.

There are three options available to resize images.

First one is to resize each and every image on your website manually. This can be a tiring process. You can then use browser re-sizing to make the initially resized image scale to fit perfectly on devices with more similar resolutions. For instance, it is much better to use CSS to resize an image from 400x300 to 350x262 than resizing it from 800x600 to 350x262.

If you have no problem working with some libraries, there are a few pretty good solutions available. This would cost you nothing in terms of money, but you will have to invest time in learning about the library.

Continue reading %Saving Bandwidth by Using Images the Smart Way%

Give Grunt the Boot! A Guide to Using npm as a Build Tool

Mo, 2015-09-14 20:00

Front-end build and workflow tools are available in abundance: Grunt, Gulp, Broccoli, and Jake to name but a few. These tools can automate almost anything you find yourself doing repeatedly in a project, from minifying and concatenating source files, to running tests or compiling code. But the question is, do you need them? Do you really want to introduce an additional dependency to your project? The answer is “No!”. There is a free alternative that can do the majority of these tasks for you and it comes bundled with Node.js. Of course I’m talking about npm.

In this article we’ll discuss what npm is capable of as a build tool. If you’d like a quick primer on npm before starting, please refer to our beginner’s guide to npm.

npm Scripts

To start our discussion, we’re going to create a directory for our new demo project, that we’ll call “buildtool”. Once done, we’ll move into this folder and then run the command npm init to create a package.json file:

$ mkdir ~/buildtool && cd ~/buildtool $ npm init

You’ll be asked several questions. Feel free to skip all or part of them as you’ll replace the final content of the package.json file with the following content:

{ "name": "buildtool", "version": "1.0.0", "description": "npm as a build tool", "dependencies": {}, "devDependencies": {}, "scripts": { "info": "echo 'npm as a build tool'" }, "author": "SitePoint", "license": "ISC" }

As you can see, we have a scripts object with a property called info. The value of info is going to be executed in the shell as a command. We can see a list of the scripts properties (also known as commands) and values defined in a project by running the command:

$ npm run

If you run the previous command in our project folder, you should see the following result:

Scripts available in buildtool via `npm run-script`: info echo 'npm as a build tool'

In case you want to run a specific property, you can run the command:

$ npm run <property>

So, to run the info command we defined in the package.json file, we have to write:

$ npm run info

It’ll produce the following output:

$ npm run info > buildtool@1.0.0 info /home/sitepoint/buildtool > echo 'npm as a build tool' npm as a build tool

If you only want the output of info, you can use the -s flag which silences output from npm:

$ npm run info -s npm as a build tool

We only used a simple echo so far, but this is a very powerful feature. Everything on the command line is available to us and we can be very creative here. So let’s build on what we’ve covered up to this point and install some packages to create some common workflows.

Workflows

The first thing we would like to implement is a linting capability for our JavaScript files. This involves running a program that will analyse our code for potential errors. We are going to use JSHint for this, so the first step is to install the package via npm:

$ npm install jshint --save-dev

After you execute this command, you’ll see a new subfolder named node_modules. This is where JSHint has been downloaded. In addition, we also need to create the following folder structure for our project:

├── assets │ ├── css │ │ └── main.css │ └── scripts │ └── main.js ├── dist ├── package.json ├── node_modules └── test └── test.js

On a Unix system, this can be done with the following command:

$ mkdir -p assets/css assets/scripts test && touch assets/css/main.css assets/scripts/main.js test/test.js Linting

Now we’ll force some syntax errors in the main.js file. At the moment the file is empty, so open it and paste in the following content:

"use strict"; var Author = new function(name){ this.name = name || "Anonymous"; this.articles = new Array(); } Author.prototype.writeArticle = function(title){ this.articles.push(title); }; Author.prototype.listArticles = function(){ return this.name + " has written: " + this.articles.join(", "); }; exports.Author = Author; var peter = new Author("Peter"); peter.writeArticle("A Beginners Guide to npm"); peter.writeArticle("Using npm as a build tool"); peter.listArticles();

Hopefully the intent of this code is clear — we are declaring a constructor function whose purpose it is to create new Author objects. We also attach a couple of methods to Author’s prototype property which will allow us to store and list the articles an author has written. Notice the exports statement which will make our code available outside of the module in which it is defined. If you’re interested in finding out more about this, be sure to read: Understanding module.exports and exports in Node.js.

Next, we have to add a property to our scripts object in package.json that will trigger jshint. To do that, we’ll create a lint property as follows:

"scripts": { "info": "echo 'npm as a build tool'", "lint": "echo '=> linting' && jshint assets/scripts/*.js" }

Here we’re taking advantage of the && operator to chain the commands and file globs (the asterisk) which gets treated as a wildcard, in this case matching any file with a .js ending within the script directory.

Note: the Windows command line does not support globs, but when given a command line argument such as *.js, Windows passes it verbatim to the calling application. This means that vendors can install compatibility libraries to give Windows glob like functionality. JSHint uses the minimatch library for this purpose.

Now let’s lint the code:

npm run lint -s

This produces the following output:

=> linting assets/scripts/main.js: line 1, col 1, Use the function form of "use strict". assets/scripts/main.js: line 5, col 28, The array literal notation [] is preferable. assets/scripts/main.js: line 3, col 14, Weird construction. Is 'new' necessary? assets/scripts/main.js: line 6, col 1, Missing '()' invoking a constructor. assets/scripts/main.js: line 6, col 2, Missing semicolon. assets/scripts/main.js: line 16, col 1, 'exports' is not defined. 6 errors

It works. Let’s clean up those errors, re-run the linter to make sure, then move on to some testing:

(function(){ "use strict"; var Author = function(name){ this.name = name || "Anonymous"; this.articles = []; }; Author.prototype.writeArticle = function(title){ this.articles.push(title); }; Author.prototype.listArticles = function(){ return this.name + " has written: " + this.articles.join(", "); }; exports.Author = Author; var peter = new Author("Peter"); peter.writeArticle("A Beginners Guide to npm"); peter.writeArticle("Using npm as a build tool"); peter.listArticles(); })();

Notice how we have wrapped everything in an immediately invoked function expression.

npm run lint -s => linting

No errors. We’re good!

Continue reading %Give Grunt the Boot! A Guide to Using npm as a Build Tool%

How to Make an Effective IoT Dashboard without Coding

Mo, 2015-09-14 18:00

Not everyone wants to code up a whole interface for their IoT ecosystem. Sometimes you need a quick and easy interface that'll be easy to set up and run. Blynk is that interface! It is a smartphone app which can integrate with a range of systems including Arduino, Particle, ESP8266, Intel Edison, Intel Galileo, LightBlue Bean, Raspberry Pi and more. It allows you to display the values from your sensors and trigger pin responses to turn components on and off. It's a very easy and quick way to test prototypes too. I couldn't find a good overview of how to pair a Particle device with Blynk, so that's what I'll be covering in this article.

If you don't have a Particle device but have an Arduino or other microcontroller, much of the Blynk process should be the same as I explain in this article, you'll just need to put the Blynk code onto the device differently (for Arduino, upload this library).

What You'll Need

[author_more]

  • A Particle Core or Photon
  • A breadboard, resistors and jumper wires
  • Some LEDs and analog sensors - the Blynk app works with any analog and digital pin signals, so feel free to switch these to use your own components. I've used a potentiometer and a photo resistor.
  • The Blynk app - You can find it on iOS and Android.
  • Knowledge of how to get code onto your Particle device - see the connecting to the Photon article if you're new to this or this official guide to Particle Core.
My Sketch

If you'd like to follow along with my exact set up (or close to it depending on which parts you have), here is the sketch:

Setting Up Blynk

To begin, open up Blynk on your smartphone (if you don't have it yet, these are the links to the iOS download and Android download).

On first loading the app, you'll need to create an account. That process is pretty simple, enter an email and password and click "Sign Up":

Once you have signed up, you will be greeted with the project screen. Click "Create New Project" to set up your first project:

In our new project's settings, we give it a name and choose "Particle Core" as our hardware model (this is the one to choose if you are working with a Photon too). I've called my project "IoT Dashboard", feel free to get more creative!

You'll see an auth token there on that screen too. Rather than typing it all in or somehow memorizing the whole thing, click the "E-mail" button to have it emailed to you. This is a huge time saver! The email you receive will look like so:

Click "Create" and you will end up at a rather black and empty looking screen. This is where you want to put in all your components. Click the icon with the plus at the top right corner to open up the "Widget Box":

The "Widget Box" is a menu of plenty of different widgets you can add to your project to either control hardware components or read in data from sensors:

To start with, lets create a button that can turn on our LED. Click "Button". This places a button widget onto our project:

Continue reading %How to Make an Effective IoT Dashboard without Coding%