Wednesday, January 21, 2015

9 Tips for WordPress Plugin Development - Six Revisions

9 Tips for WordPress Plugin Development - Six Revisions


9 Tips for WordPress Plugin Development

Posted: 21 Jan 2015 07:30 AM PST

In this article, I would like to share some of my tips for developing WordPress plugins.

My Background

I’ve developed more than 20 WordPress plugins. Some of them were for clients, some for free release at the WordPress Plugin Directory, others as joint ventures, or for sale on marketplaces such as CodeCanyon.

Plugins I’ve worked on have been installed on well over 50,000 sites. I’ve sold over 5,000 copies in the premium market.

Throughout this experience, I’ve learned many lessons, and would like to share them with you in this article.

1. Use the Right Hooks

Hooks are the bridge between your plugin and the larger ecosystem (WordPress). You can’t write plugins without hooks. You’d be surprised how many plugins misuse them though.

The first step to the proper use of hooks lies simply in taking the proper time to read through the official documentation of the Hooks Plugin API.

You want to end up with a deep understanding of which hook fires at which part of the sequence — from the page request, all the way to sending content to the browser. The Action Reference API shows us what order things typically fire in.

There’s a lot of hooks to choose from, and depending on what your plugin does, you might need to wire in many of them.

I always abide by the practice of sub-dividing functionality to be as relevantly-distributed across my hooks as possible. This is because, for plugin development, adopting a "just in time" (JIT) mentality by running code only when it’s needed is a good idea.

If you need to set up some global variables or register post types, regardless of what page is being loaded, that should probably be fired on init. You should not be preparing HTML nor doing any heavy-processing on init in most cases.

Any strenuous processing within the init hook will mean all front-end page loads, admin page loads, AJAX requests and such, will be subjected to the delays caused by these heavy processes. This isn’t ideal and should be avoided for better performance.

Generally, I only use the init hook to:

  • Enqueue scripts
  • Localize scripts
  • Retrieve settings (depending on the user type and the page requested)

The following code block is a general example of how I conditionally enqueued scripts on init. You’ll see I’m careful to feed only the required resources for each type of page. No admin stylesheets unless the user is loading one of the plugin admin pages. Likewise, no front-end stylesheets loaded for the backend interface.

<?php    #} Plugin Init  add_action('init', 'examplePlugin_init');  function examplePlugin_init(){     	global $examplePlugin_Settings; #req    	#} Retrieve settings (if not loaded)  	$settings = $examplePlugin_Settings->getAll();    	#} Admin & Public (Global) Scripts  		wp_enqueue_script("jquery");  	  	#} Enqueuement for Public & Admin seperately  	if (!is_admin()){    		#} Public only    		#} Public-Global - JS & CSS  			wp_enqueue_script('examplepluginjs', plugins_url('/js/examplePlugin.min.js',__FILE__),array('jquery'));  			wp_enqueue_style('exampleplugincss', plugins_url('/css/examplePlugin.min.css',__FILE__) );  		  		#} Any specifically enabled elements  		if ($settings['showElement'] == 1) wp_enqueue_script('examplepluginextrajs', plugins_url('/js/examplePlugin.extraFeature.min.js',__FILE__), array('jquery'));    	} else {  	  		#} Admin only    		#} Admin-Global - JS & CSS  			#} Try not to use these, unless specifically necessary, use the below method    		#} Admin only + specifically a plugin admin page  		if (examplePlugin_isAdminPage()) {    			#} Plugin-specific Admin styles  			wp_enqueue_style('examplepluginadmincss', 	plugins_url('/css/examplePlugin.admin.min.css',__FILE__) );  					  		}	    		#} Admin only + WordPress Edit Page specifically  		if (examplePlugin_is_edit_page()){    			#} Anything which is to load on the edit post/edit page, page  			#} For example shortcode inserter functionality    		} else {  		  			#} Anything which is to load on non-editor admin pages  		  		}    		#} Admin only + WordPress editor on page  		if (get_user_option('rich_editing') == 'true') {  			  			#} This is another way of targetting the WordPress Editor  			#} In this instance we use this to localize a script:  			wp_localize_script( 'examplepluginadminjs', 'exampleAJAX', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));     		}    	}		    }    #} Example function for detecting if the requested page is an edit page  function examplePlugin_is_edit_page($new_edit = null){      #} Global   global $pagenow;      #} Ensure we are in admin   if (!is_admin()) return false;     #} Detect edit page type   if($new_edit == "edit") #} Edit page    return in_array( $pagenow, array( 'post.php', ) );   elseif($new_edit == "new") #} New Edit page    return in_array( $pagenow, array( 'post-new.php' ) );   else #} New or Edit page    return in_array( $pagenow, array( 'post.php', 'post-new.php' ) );  }    #} Determines if this is our admin page  function examplePlugin_isAdminPage(){  	  	#} This is defined on init, and is a simple array of page slugs  	global $examplePlugin_slugs;    	#} Detect page  	if (isset($_GET['page'])) if (in_array($_GET['page'],$examplePlugin_slugs)) return true;   	  	return false;  	  }

Beyond init, you will probably need to use a combination of the following Action hooks, which for most plugins will be enough to modularize the code logic without causing performance issues or maintainability challenges.

  • admin_menu
  • admin_notices
  • wp_head
  • wp_footer
  • wp_ajax_[yourFunction]

Note: Some themes will tend to drop wp_footer, (and sometimes even wp_head), in favor of their own versions. These WordPress themes are typically quickly-written or of the hack-y variety, but they are more common than you’d expect. So always test your plugin with as many themes as possible if your intention is to provide universal compatibility.

2. Take Advantage of WP Cron

Cron is a task-scheduling system originally built for UNIX which lets users execute commands at specified times.

Did you know WordPress core has a cron-like feature built in? This feature is aptly called wp cron.

If your plugin has a routine task that needs to be run, wp cron can be useful for firing off the task.

wp cron has its limitations though. For example, it’s dependent on web page requests, resulting in a delayed firing of a task if the WordPress site doesn’t have high-traffic. But these limitations are fixable.

For well-trafficked sites, and for those that are set up with auto-pinging, wp cron can be a pleasant way to create a cron-like setup.

Other lesser-known but useful WordPress features are:

3. Take Advantage of Auto Updates

Since WordPress 3.7, automatic updates have been available to WordPress plugin and theme developers.

This functionality is not enabled by default, and must be turned on by the user, or through your plugin. The latter is not advised because the user should explicitly opt-in for auto-updates. However, it’s good to highlight/remind the user about the auto-update option through your plugin’s admin interface.

If enabled, automatic updates are an excellent tool for continuous WordPress plugin development. It’s great for rolling out security patches, hot fixes, and version releases.

Plugins listed on WordPress.org benefit from automatic management of plugin versions through their repositories.

4. Consider Using the MVC Design Pattern

WordPress plugins benefit greatly when they are created using the MVC architecture. For maintainability, modularity, and many other reasons, there’s no better option.

MVC makes it really easy to be clean and organized with your plugin architecture.

There’s the odd occasion that I do still use what I refer to as a "wild code" architecture. It’s for tiny plugins, one-offs, and sometimes demo functionality.

Below you can see the two directory structures I typically use for plugins: the "wild" architecture version to the left, and MVC to the right. It will give you a better idea regarding the difference MVC can make:

In addition, all new plugins I write contain a documentation directory with docs composed in HTML, a languages directory, and Sass versions of the plugin’s stylesheets. Currently, I would say preprocessors are now a standard tool you’ll find among the toolsets of professional WP plugin developers.

Check out Ian Dunn’s presentation on implementing MVC for plugin development — it’s a great primer.

5. Name Plugin Files Uniquely

Don’t forget that your plugin will be installed in a "busy ecosystem", perhaps even at the same time as your competitors’ plugins.

Unique names for your files and variables are essential.

The easiest way to do this would be to prefix custom PHP variables, classes, functions, CSS selectors, and file names with your plugin’s name.

6. Test Your Plugins Thoroughly

The last part of any good software development cycle is polishing, prepping and testing the product for release.

Here are my suggestions for when you are getting ready to deploy the initial release of your plugin, or are preparing a version release:

  1. Debug your plugin with wp_debug enabled until everything is resolved.
  2. Test the plugin on a fresh WordPress install.
  3. Test the plugin using multiple WordPress themes.
  4. Consider testing the plugin on old WordPress versions and PHP versions that you suspect might affect the functionality of the plugin.
  5. Analyze and test your plugin with browser developer tools (DevTools for Chrome, Firebug for Firefox, etc.).
  6. Compress all front-end files (HTML, CSS, and images). Include non-minified versions of your stylesheets and HTML files so that the plugin user can perform custom modifications.
  7. Write good documentation. Documenter can be helpful with this process.

7. Allow Users to Customize the Plugin

There’s a dirty secret that your users are never going to tell you. They’re fumbling around behind the scenes with your plugin’s source code.

WordPress users, more than any other group of software customer I’ve dealt with, dig through code. Many plugin customers are also developers who buy your plugin to add the functionality it offers to their WordPress projects.

Any plugin that grows a large user-base typically designs with customizability in mind, or deals with the wrath of support tickets.

Rather than making plugin customization difficult and forcing customers to fumble around with the plugin’s source code, give your users options and APIs that allow them to tailor the plugin’s functionality to their needs.

Global settings should be set via the plugin’s admin interface. Single-instance settings, such as custom settings specifically for a WordPress post or page, can be accomplished by providing users with a custom shortcode API for your plugin.

I believe that your plugin users should, at the bare minimum, be able to do the following:

  • Change styles such as colors, icons, borders, fonts, backgrounds, etc. Consider creating multiple plugin themes (dark, light, etc.).
  • Enable/disable optional third-party dependencies (e.g. Google Analytics, Facebook API, etc.)
  • Enable/disable certain features of the plugin
  • Change the front-facing text labels (such as the labels used to describe UI buttons and input fields)
  • Override the plugin’s default CSS through an admin interface

Other ways to empower your users:

  • Provide preprocessor versions of your stylesheets. Users who prefer to customize the plugin’s look-and-feel using Less, Sass, or another CSS preprocessor will thank you.
  • Have a good HTML structure. Often users restyle the plugin’s theme with CSS placed in their WordPress theme’s styles.css. Make it easy for them to select specific elements of the plugin by having a good HTML architecture with elements that have intuitive class and id names.
  • Explain how to modify plugin settings via documentation.

Finally, don’t forget to give your plugin a "restore to default settings" feature. This "factory reset" feature is good to have for when something disastrous happens during customization.

8. Prioritize Plugin Performance

Performance should be a top priority when developing a plugin. Every component should be optimized with speed in mind.

In the end, your users are likely using many plugins, making each page load churn through handfuls of PHP files.

The leaner you can get your plugins, the better. Wherever possible, build in caching, especially in multi-instance environments.

Above all else: Test.

Test on several hosts, with several themes, and with other plugins. P3 Profiler is a superb tool that will help you optimize your plugin’s source code.

9. Put Effort into Branding the Plugin

This tip may not matter to you. Perhaps you’re releasing plugins just for fun. Maybe your main goal is to give back to the WordPress community.

Whether it be for fun or profit, I would argue that every plugin deserves at least a decent shot, even if there’s no money trading hands.

Why make the plugin if you don’t want it out in the hands of WP users?

There are tons of free plugins released to the community that take the time to craft a good visual brand identity.

Like any product, WordPress plugins are subject to market competition. To stand out in the bustling marketplace around WordPress, you will need to execute well across all types of job roles, including roles outside of development such as design, marketing, SEO, copywriting, and so forth.

It’s not enough to have a great plugin. No one will use it if no one knows about it.

To brand a plugin well is an art and science. To this end, I hire a designer to design a logo and a "look and feel" for all new plugins I release to the premium market.

Sometimes, if it’s a tiny thing, I’ll try and do it myself. This rarely works.

Good branding and a great plugin will carry you far.

Beyond that, building a successful WordPress plugin business is largely a game of idea-generation -> development -> marketing. And then optimizing that loop.

Here are the key lessons I’ve learned specific to plugin sales:

  • Each plugin should add just one amazing feature rather than ten mediocre ones. Keep it simple.
  • Price should be based on the amount of value the plugin can add to the customer.
  • Great customer service is hugely important.
  • Build an off-marketplace business website (don’t rely on your marketplace profiles).
  • Don’t fight competitors. Focus on creating a great product people want to use.

Conclusion

There are some painful challenges pushing a WordPress plugin to market. It can create support-ticket storms, raging refund-requests, and one-star-review woes. Using the practices above, I’ve managed to reduce a lot of these challenges, and am increasingly finding a win-win way of generating revenue from WordPress development.

Related Content

About the Author

Woody Hayday is a developer whose specialty includes WordPress development. He also runs EverClients, a lead service for freelancers, and is an advisor at EpicPlugins. You can find more about the author at WoodyHayday.com.

The post 9 Tips for WordPress Plugin Development appeared first on Six Revisions.

Monday, January 19, 2015

A Guide to Design Mockup Fidelity - Six Revisions

A Guide to Design Mockup Fidelity - Six Revisions


A Guide to Design Mockup Fidelity

Posted: 19 Jan 2015 07:00 AM PST

This is a guest post by Jerry Cao, coauthor of The Guide to Mockups.

In this article, I will discuss the various levels of UI design mockup fidelity to help you choose the best option.

Web designer Brad Frost summarizes the progression of design fidelity best, using an analogy:

You start out with a big slab of rock, and slowly chip away to get the rough shape of the form you’re creating. You take another pass at it to get a better sense of the object you’re trying to extract from the stone. You take another pass to start getting a bit more detailed. Eventually, you start honing in on a particular aspect of the form: a face, the arms, or the torso. Slowly but surely you detail each section of the sculpture until you’ve arrived at the final form.

The Fidelity Continuum

"Design methods are not mutually exclusive. Rather, each method exists on a continuum of fidelity," Tyler Tate, a well-regarded UX designer and book author, says in this article.

According to Tate, the design process starts with low-fidelity (lo-fi) sketches, and progresses towards high-fidelity (hi-fi) prototypes.

source: jfarny.com

Where do mockups fit, in the continuum of fidelity?

I would put design mockups at the mid- to high-fidelity range, wedged between low-fidelity wireframes and high-fidelity functional prototypes.

To apply too much fidelity prematurely in the process will waste time and money. On the other hand, not giving this process enough time and money will leave many avenues unexplored.

There’s this balance that needs to be established between time, resources and fidelity.

source:  uxbooth.com

The optimal level of fidelity is the minimum amount of fidelity needed to get the job done. Nothing more, nothing less. This is what you might call "being lazy in a good way" or "responsibly lazy."

Concept Mockups

Concept mockups exist outside the traditionally accepted form of UI design mockups. They are useful nonetheless.

Companies sometimes skip the wireframing phase and replace it with a concept mockup, which they then iterate on as they climb up the continuum of fidelity.

As illustrated in the following diagram, a concept mockup comes before wireframing or detailed (higher-fidelity) mockups:

source: leacock.com

Below, you can see that concept mockups can be done simply by sketching out some of your initial design ideas on paper:

source: alistapart.com

Concept mockups are helpful if you prefer starting on paper and plan on digitally creating mid- or high-fidelity mockups later on.

Concept mockups may add extra work onto the design process, but it lets you quickly explore some ideas on paper.

In addition, if you plan on wireframing before the mid- or high-fidelity mockup, your concept mockups can serve as rough guidelines.

Digital Mockups

Moving forward, we go to the subject of digital mockups.

There are two schools of thought that divide the preferred approach to creating digital mockups:

  1. Those that see the mockup phase as transitional, and thus should not take too much time (mid-fidelity)
  2. Those that believe design mockups should represent the end-product exactly (high-fidelity)

Mid-Fidelity Mockups

Mid-fidelity mockups have these advantages:

  • You can go from the conceptual phase to the implementation phase more quickly.
  • It allows for more flexibility, creativity and exploration during the implementation phase.
  • It can reduce the creation of unnecessary design components that might eventually be scrapped when developing the actual front-end.

Creating a mid-fidelity mockup also has its drawbacks:

  • The lack of polish means many design decisions are up in the air.
  • A lot of the time you may have saved during the mockup phase will go into fine-tuning UI components in the implementation phase.
  • Clients and stakeholders won’t be as impressed with a mid-fi mockup as they would with a hi-fi one, so that’s worth keeping in mind.

source: uxpin.com

High-Fidelity Mockups

The high-fidelity mockup plans out and develops most of the design decisions right at the start, including font size, dimensions, color scheme, margin sizes, etc. This level of fidelity can be considered as being "pixel-perfect".

You can see the level of design detail we include in our high-fidelity landing page mockups over at UXPin:

source: uxpin.com

Hi-fi mockups are beneficial for several reasons:

  • You give yourself more time to iterate and perfect the UI design.
  • You will make most of the design decisions early in the production process.
  • They are easier to present to non-designers: Clients and stakeholders prefer this style over mid-fi mockups because they may not be aware of the continuum of fidelity. However, anyone can understand high-fidelity prototypes.
  • Front-end developers can see what the final product must look like, which means hi-fi mockups can doubly serve as a visual specs sheet.

However, there’s a downside, and one that shouldn’t be overlooked: High-fidelity mockups take longer to produce.

One could make the argument that creating high-fidelity mockups isn’t time efficient since we’ll need to rebuild the design in HTML, CSS, and JS anyways. To some, this workflow process might seem redundant.

However, you could also say that high-fidelity mockups can save time in the end because of all design decisions, design testing, and planning that are made early in the process. This can all equate to time-savings during the implementation phase.

Mockup Fidelity Progression

When choosing how much fidelity to give your mockups, consider first your individual needs, and then examine how you want mockups to fit into the process as a whole.

Mockups will be as varied as the end-products they represent, so there’s really no fixed standard for how they should look or function. Only guidelines.

The choice of how much fidelity or how much time to spend making your mockup is up to you.

We at UXPin recommend an iterative approach that allows for simultaneous mid-fidelity mockup and prototype creation:

  1. Start with sketches: Get your ideas on paper first, where you won’t get too attached to your initial designs. For each concept, draw out and explore a couple or so options.
  2. Move to a digital environment: Once you’ve drawn out some ideas, switch over to a digital tool like Axure, OmniGraffle, or my company’s own tool UXPin. There’s tons of options. Converge your sketches into a quick digital wireframe, then add visual details until you are at mid-fidelity.
  3. Prototype the functionality: The beauty of digital design tools these days is that many of them allow for simultaneous wireframing and prototyping. With a few clicks, you can turn a mockup into a functional prototype quite easily.
  4. Test, iterate, refine: At this point, your mockup is now a high-fidelity prototype. Test it with users or even coworkers (grab at least five people for a quick test session). Then, analyze your results and add fidelity and functionality as needed. Repeat this step as much as required.

In our experience, this progression helps balance resources, time and fidelity well. Visual design is first explored on paper through sketching, and then we move to a specialized tool to build functionality and improve the visuals.

Further Reading

Download my free ebook called The Guide to Mockups for a thorough look at mockup best practices and methods.

The ebook includes insights from experts such as Luke Wroblewski, Marcin Treder and Ash Maurya.

Related Content

About the Author

Jerry Cao is a content strategist at UXPin. In the past few years, he’s worked on improving website experiences through better content, design, and information architecture (IA). Join him on Twitter @jerrycao_uxpin.

The post A Guide to Design Mockup Fidelity appeared first on Six Revisions.

Friday, January 16, 2015

Why I Ditched Angular for React - Six Revisions

Why I Ditched Angular for React - Six Revisions


Why I Ditched Angular for React

Posted: 16 Jan 2015 07:30 AM PST

A few years ago, when my code started to get cluttered with jQuery selectors and callbacks, AngularJS came to my rescue.

Angular helped me with the maintainability of my dev projects. It came with a lot of functionality out-of-the-box. It was tooled for building large-scale web apps, greatly facilitating rapid development in this genre of applications.

I remember how its two-way binding and the philosophy of Model as the single source of truth blew me away. And, in practice, they reduced data-redundancy throughout my applications.

Over time though, I discovered some pain points in Angular. Eventually they caused me enough frustration that I began looking around for alternatives.

Here are the concerns I have with Angular.

DOM for execution. Angular heavily relies on the DOM for its execution flow. In the default bootstrapping of Angular apps, it scans the DOM and compiles it with priorities of directives, which makes it difficult to debug and test the execution order.

Two-way binding is a double-edged sword. As the complexity of your components grows, this approach can lead to performance issues.

How does two-way binding affect performance? JavaScript (ES5) doesn’t have any implementation to notify for any change to its variables or objects, so Angular uses something called "dirty checking" to track data changes and sync them with the user interface (UI).

Dirty-checking is carried out after any operation is performed within Angular’s scope ($digest cycle) which leads to slower performance as the amount of bindings increases.

Another problem with two-way binding is that many components on the page are capable of changing data, which means there are multiple sources of data inputs. If not managed well, this can lead to a confusing and overwhelming situation. To be fair, this is an implementation issue, not an Angular issue in and of itself.

Angular has its own world. Every operation in Angular must go through its digest cycle, or else your components won’t sync with your data models. This leads to compatibility issues with other dependencies.

If you use any third-party JavaScript library that involves data changes, you need to wrap it with Angular’s $apply function. Or you will need to convert it to a service, if it’s a utility library. This is like having to reinvent every JavaScript library you use in order for it to interoperate with Angular.

Dependency injection. JavaScript currently doesn’t have a package manager and dependency resolver of its own. AMD, UMD and CommonJS have been solving this gap well. But, until recently, Angular did not play well with any of these. Rather, it introduces a dependency injection (DI) of its own. Though, to be fair, there are unofficial Angular dependency-injection implementations using RequireJS.

Steep learning curve. Using Angular requires learning a ton of concepts including, but not limited to:

  • modules
  • controllers
  • directives
  • scopes
  • templating
  • linking functions
  • filters
  • dependency injection

It can be very difficult to get started with Angular. It’s not for the faint of heart.

All of this led me to React.

What’s So Great About React?

React, the new open source framework for building user interfaces, is a different way of developing JavaScript apps. React is led by Facebook and Instagram.

To be clear: React isn’t an application development framework like AngularJS. It’s not fair to compare the two in an apples-to-apples manner.

When React was introduced at JSConf EU in May 2013, the audience was shocked by some of its concepts, like "one-way data flow" and "Virtual DOM".

React is for building user interfaces. In other words, straight from the official landing page of the project: "people use React as the V in MVC." However, you can write self-contained components with it, which more or less compares to Angular directives.

React rethinks our current web development concepts and best practices.

For instance, it encourages one-way data flow and believes in a philosophy that components are state machines driven by data.

Whereas most of the other similar frameworks love working with the DOM and directly manipulating it, React hates the DOM and works to shield the developer from it.

React provides the bare-minimum API needed to define a UI component. Nothing more, nothing less. It follows UNIX philosophy: Small is beautiful. Do one thing, and do it best.

You can find a more detailed comparison of Angular vs. React by Pete Hunt (who works at Facebook/Instagram).

Why Did I Switch to React?

Here are some of the things I like about React.

React is Fast

React takes a different approach to the DOM compared to other frameworks.

It does not let you work with the DOM directly.

It introduces a layer, called Virtual DOM, between your JavaScript logic and the actual DOM.

Virual Dom illustration

This concept improves web performance. On successive renders, React performs a differential (diff) on the Virtual DOM, and then updates only parts of the actual DOM that need to be updated.

Cross-Browser Compatibility

Virtual DOM also helps solve cross-browser issues because it provides us with a standardized API that even works as far back as IE 8.

Modularity

Writing self-contained UI components modularizes your app, which in turn isolates issues only to the problematic component/s.

Every component can be developed and tested in isolation, and they can use other components. This equates to maintainability improvements.

One-way Data Flow Makes Things Saner

Flux is an architecture for creating one-way data layers in JavaScript applications. It was conceptualized by Facebook along with the React view library. The Flux concept makes large-scale app development simpler.

Flux is a concept rather than a tool-specific implementation. It can be incorporated into other frameworks. For instance, Alex Rattray has a nice implementation of Flux using Backbone Collection and Model in React.

Just JavaScript

Modern web apps work in a different way compared to the traditional Web.

For example, the View layer needs to be updated with user interactions without hitting the server. And hence View and Controller need to rely on each other heavily.

Many other frameworks use templating engines like Handlebars or Mustache to deal with the View layer. But React believes that View and Controller are so interdependent that they must reside at a single place without the use of any third-party templating engine, and, on top of that, without leaving the scope of JavaScript.

Isomorphic JavaScript

The biggest drawback of single-page JS web apps is that it has limitations when crawled by search engines. React has a solution for this.

React can pre-render apps on the server before sending it to the user agent. It can restore the same state into the live application from the pre-rendered static content on the server.

Because search engine crawlers rely on the server response rather than JavaScript execution, pre-rendering your apps helps with SEO.

It Plays Well with Others

Loaders and bundlers like RequireJS, Browserify and Webpack are much needed when you’re building large applications. They make the arduous task surmountable.

Unfortunately, the current version of JavaScript doesn’t provide a module bundler or loader. (Though there’s a proposal to address this in the upcoming version, ES6, with System.import).

Fortunately we have some alternatives like RequireJS and Webpack, which are pretty neat. React is built with Browserify, but if you’re looking to inject image assets and compile Less or CoffeeScript, then probably Webpack stands as a better option. The point is: You are afforded that choice.

Do I Need Another Development Framework with React?

Using React, you can build user interfaces, but you still need to make AJAX calls, apply data filters, and other things that Angular already does.

So if we need an additional JavaScript app development framework, why ditch Angular?

Frameworks are a set of modules and rules. If I don’t need some of its modules, or want to swap out a module for another one that does the job better, how do I do it?

One of the ways to achieve modularity and better dependency-management is through package managers.

But then, how do we manage packages in Angular? That’s up to you, but know that Angular has its own world. You will most likely need to adapt third-party packages into Angular’s world.

React, on the other hand, is just JavaScript. Any package written in JavaScript won’t need any wrapping in React.

For me, using package managers like npm and Bower is better. We can pick and choose our components and craft custom toolsets. To be clear: This is more complicated compared to just using a comprehensive app development framework like Angular.

On this front, the saving grace is that React encourages the use of npm, which has a lot of ready-to-use packages. To get started building apps with React, you can, for example, use one of these full-stack starter kits.

Switching to React is Not Painless!

Since Angular is an app development framework, it comes with a lot of goodies. I’m giving up great features like an AJAX wrapper in the $http service, $q as a promise service, ng-show, ng-hide, ng-class, and ng-if as controlling statements for template — all that amazing stuff.

React isn’t an app development framework, so you need to think about how to deal with the other aspects of building applications. For example, I’m working on an open source project called react-utils which can be used with React to ease development.

The community is also actively contributing similar reusable components to fill in the blanks, so to speak. React Components is an unofficial directory website where you can find such open source components.

React’s philosophy does not encourage you to use two-way binding, which brings a lot of pain when you’re dealing with form elements and editable data grids.

However, as you start understanding the Flux data flow and Stores, things become clearer, simpler and easier.

React is new. It will take some time for the community around it to grow. Angular, on the other hand, has already gained huge popularity, and has a relatively large number of extensions available (e.g. AngularUI and Restangular).

However, although React’s community is new, it is growing fast. Extensions like React Bootstrap are a testament to this. It’s just a matter of time before we have more components available.

Conclusion

If you love the Angular approach, then you may hate React at first. Mainly because of it’s one-way data flow and lack of app development features. You end up needing to take care of many things by yourself.

But as soon as you get comfortable with the Flux design pattern and React’s philosophy, I guarantee that you will begin to see its beauty.

Facebook and Instagram both use React (because they are leading the project).

GitHub’s new source code editor, Atom, is built using React.

The upcoming Yahoo! Mail is being rebuilt in React.

React already has large-scale apps and big tech companies betting on it.

Related Content

About the Author

Kumar Sanket is a freelance full-stack web developer/engineer at Toptal. He specializes in modern, scalable web app development.

The post Why I Ditched Angular for React appeared first on Six Revisions.

Wednesday, January 14, 2015

Interactive JavaScript Tutorials - Six Revisions

Interactive JavaScript Tutorials - Six Revisions


Interactive JavaScript Tutorials

Posted: 14 Jan 2015 07:30 AM PST

Learning the fundamentals of JavaScript can be easier and more fun through interactive tutorials. Interactive tutorials are immersive, letting you write and experience code immediately.

Here are three free interactive JavaScript tutorials that will get you started programming with JavaScript in no time.

The online tutorials discussed are suitable for beginning and intermediate JavaScript programmers. They are arranged in a logical sequence, from easiest to hardest.

1. JavaScript Road Trip

JavaScript Road Trip

Code School has a free beginner-level interactive JavaScript tutorial that’s designed to be completed in 2 hours, called JavaScript Road Trip. The tutorial has video-based instructions and coding challenges that allow you to experience writing JavaScript code right away.

The tutorial covers the basics: JavaScript Boolean values, strings, variables, and how to work with JS files.

2. JavaScript Track (Codecademy)

JavaScript Track (Codecademy)

On Codecademy, you can find a free interactive JavaScript course curriculum that has 7 sections. There will be plenty of coding challenges along the way as you navigate through the course. The course is estimated to take about 10 hours to complete.

The JavaScript Track on Codecademy goes into intermediate-level topics such as functions, loops, data structures (arrays and objects). However, the first section is an intro to general programming concepts that you should take if you’re new to programming, or if you need a refresher.

This is a great interactive course, especially because each section concludes with building simple JavaScript applications like a contact list, an address book, and a digital cash register.

3. Learning Advanced JavaScript

Learning Advanced JavaScript

This interactive tutorial is sectioned into 15 parts, covering some of JavaScript’s harder concepts. It was built by John Resig, the creator of jQuery.

This JS tutorial is fitting for intermediate- to advanced-level JavaScript programmers; folks who have a good command of the fundamentals. (Otherwise, you might not fully appreciate the topics that are discussed in the tutorial). Topics included are closures, creating functions as objects, etc.

Conclusion

There are many more interactive JavaScript tutorials out there. But rather than overwhelming you with a ton of links and giving you the burden of choosing which ones to take, I handpicked and tested the best ones I’ve found, and then shared it with you in this article.

JavaScript is a powerful programming language. Aside from being a key component of modern web development, the language is finding itself in other environments such as web servers, desktop software, and mobile apps. When it comes to the question of which programming language to learn first, I can think of no other option better than JavaScript.

Related Content

About the Author

Jacob Gube is the founder of Six Revisions and a front-end web developer. Join him on Twitter @sixrevisions and Facebook.

The post Interactive JavaScript Tutorials appeared first on Six Revisions.

Monday, January 12, 2015

CSS Background Shorthand Property - Six Revisions

CSS Background Shorthand Property - Six Revisions


CSS Background Shorthand Property

Posted: 12 Jan 2015 07:45 AM PST

The background shorthand property is a way to specify the values of multiple CSS background properties in a single declaration.

Example

body {    background: url(photo.jpg) top left no-repeat #000;  }

The example above specifies four background properties in one declaration and is the same as writing:

body {    background-image: url(photo.jpg);    background-position: top left;    background-repeat: no-repeat;    background-color: #000;  }

Syntax

Here are the eight background properties that can be declared using the background shorthand property:

  1. background-image
  2. background-position
  3. background-size
  4. background-repeat
  5. background-attachment
  6. background-origin
  7. background-clip
  8. background-color

The general syntax of the background property is:

background: [background-image] [background-position] / [background-size] [background-repeat] [background-attachment] [background-origin] [background-clip] [background-color];

Each property value is separated by at least one spacing character.

When specifying a background-size value, it must immediately follow the background-position value. Additionally, the background-position and background-size must have a slash (/) in between them (e.g. top right/contain).

The following rule set utilizes all eight background properties using longhand syntax:

body {    background-image: url(photo.jpg);    background-position: center center;    background-size: cover;    background-repeat: no-repeat;    background-attachment: fixed;    background-origin: padding-box;    background-clip: border-box;    background-color: #ccc;  }

(When used, the above style rule will result in a responsive full background image that covers the entire viewport.)

The style rule above can be shortened to just one line as follows:

body {    background: url(photo.jpg) center center/cover no-repeat fixed padding-box border-box #ccc;  }

And since:

  • padding-box is the default value of background-origin
  • border-box is the default value of background-clip

The style rule can be further shortened
by omitting those two property values:

body {    background: url(photo.jpg) center center/cover no-repeat fixed #ccc;  }

As can be seen above, the background shorthand syntax is useful in reducing the amount of CSS we have to write. The longhand syntax above occupies 272 bytes, while the last shorthand syntax shown above only occupies 81 bytes — a -108.2% reduction of code.

Behavior

Here are some things to keep in mind when using the background shorthand property.

Do you have to declare all background property values?

You don’t need to declare all eight background property values. At the minimum, you just need one valid property value.

For example, if you just want to give an element a green background, you can write:

div {    background: green;  }

Which is equivalent to:

div {    background-color: green;  }

How are undeclared property values treated?

A background property value that isn’t explicitly specified in the background shorthand property declaration will be equal to its default value, or it may inherit values from your other style rules.

For example, the following style rule only specifies the value for background-image and background-repeat:

background: url(small-photo.jpg) no-repeat;

Thus, the other six properties that aren’t declared are given their default values, such that the above is equal to the following:

background: url(small-photo.jpg) no-repeat;    /* The following properties are implicitly assigned  their respective default values */  background-position: 0% 0%;  background-size: auto;  background-repeat: repeat;  background-attachment: scroll;   background-origin: padding-box;  background-clip: border-box;  background-color: transparent;

Note: The example above assumes there are no inheritable properties from other rule sets in the stylesheet. If other rule sets affect these unspecified properties, then it will inherit those values according to CSS inheritance rules.

Default Values of Background Properties

Property Default Value
background-image none
background-position 0% 0% (this is the same as top left)
background-size auto
background-repeat repeat
background-attachment scroll
background-origin padding-box
background-clip border-box
background-color transparent

Does the order of property values matter?

In most cases the sequence of declaring background property values doesn’t matter. There are three exceptions to this rule (we’ll discuss them shortly).

Hence, the following:

background: repeat-x url(photo.jpg) orange 0% 50%;

Is the same as:

background: 0% 50% orange url(photo.jpg) repeat-x;

The first exception is background-origin and background-clip must be declared in the correct order. This is because they can share the same value. Both properties can have one of these three values: border-box, padding-box or content-box.

If only one of the values are found in the background shorthand property, it’s not as big of an issue because it’s assumed that the value is being assigned to both background-origin and background-clip.

For instance, the following:

background: content-box url(photo.jpg);

Is the same as:

background-origin: content-box;  background-clip: content-box;  background-image: url(photo.jpg);

However, when two values are present, it applies the first value to background-origin and the second one to background-clip.

For example, the following:

background: border-box url(photo.jpg) padding-box;

Is the same as:

background-origin: border-box;  background-image: url(photo.jpg);  background-clip: padding-box;

The second exception is background-size must be declared immediately after background-position, and both properties must be separated by a slash (/).

The following shows the correct way of specifying the background-size and background-position within the background shorthand property (as well as erroneous examples).

Examples

/* Correct */  background: url(photo.jpg) top left/cover no-repeat fixed;    /* Invalid!  background-size is declared before background-position */  background: url(photo.jpg) cover/top left no-repeat fixed;    /* Invalid!  background-size doesn't immediately follow background-position */  background: url(photo.jpg) top left no-repeat/cover fixed;    /* Invalid!  The slash (/) is missing */  background: url(photo.jpg) top left cover no-repeat fixed;

The third exception is when you use two numerical values for the background-position property.

When using two numerical values for background-position:

  • the first value refers to the vertical position
  • the second value refers to the horizontal position

For example, 0% 50% means that the background image is to be positioned at the top-center of the element, and not left-center.

However, when using two position keywords (i.e. top, right, bottom, left or center) their order doesn’t matter.

For example, bottom right is the same as saying right bottom.

But you must make sure one keyword refers to the vertical position and the other keyword refers to the horizontal position.

For example, right left and top bottom are invalid.

Finally, the two background-position values — whether they’re numerical values or position keyword values — must be right next to each other.

Here are several correct and invalid examples of using two values for background-position.

Examples

/* Correct */  background: 0% 0% url(photo.jpg) no-repeat;    /* Correct */  background: url(photo.jpg) no-repeat top left;    /* Correct */  background: url(photo.jpg) left top no-repeat;    /* Invalid!  The background-position values both refer to horizontal positions */  background: url(photo.jpg) no-repeat left right;    /* Invalid!  The background-position values are not next to each other */  background: left url(photo.jpg) no-repeat top;

Multiple Backgrounds

You can give an HTML element more than one background with the background shorthand property. Each group of background properties must be separated by commas (,).

The following example assigns the body element two background images. The first is located at the top-left of the web page, while the other is located at the center-left of the web page. Notice that the corresponding background properties for each background is delineated by a comma.

Example

body {    background: url(photo.jpg) top left no-repeat,                url(photo2.jpg) center left no-repeat #ccc;  }

The one rule to keep in mind when setting multiple backgrounds is this: Only the last group of background properties can have a background-color property.

If a background-color property value is found anywhere else besides the last set of background properties, the background shorthand property will be ignored by the browser.

Examples

/* Correct  The last group contains the background-color property  */  body {    background: url(photo.jpg) top left no-repeat,                red url(photo2.jpg) center left no-repeat;  }    /* Invalid!  The first group has a background-color value */  body {    background: red url(photo.jpg) top left no-repeat,                url(photo2.jpg) center left no-repeat;  }    /* Invalid!  Both groups have background-color values */  body {    background: red url(photo.jpg) top left no-repeat,                red url(photo2.jpg) center left no-repeat;  }

Conclusion

The background shorthand property is useful because it allows us to do more with less code.

The biggest tip I can offer to those using the background shorthand property is to establish a standardized way of ordering the background property values. Having a guideline makes the property declaration easier to read and write. It can also help you avoid logic errors/bugs, such as when background-origin and background-clip values are incorrectly-arranged.

Also, when specifying many property values with the background shorthand property, it will become harder to read and maintain. Consider declaring the not-so-popular and infrequently-used background properties on their own. For instance, I prefer declaring background-size, background-attachment, background-origin and background-clip as separate declarations outside the background shorthand property.

Example

body {    background: url(photo.jpg) 50% 50% repeat-x #ccc;    background-size: cover;    background-attachment: fixed;    background-origin: border-box;    background-clip: padding-box;  }

It makes the style rule more readable in my opinion.

Lastly, as a best practice, whenever you’re specifying the background-image property, you should also specify a good fallback background-color property alongside it even if it’s not mandatory, for the purpose of graceful degradation.

Example

div {    color: white;    /* Fallback color is black because foreground color is white */    background: url(photo.jpg) 50% 50% repeat-x black;  }

With a good background-color property, users can still read the text even though the background image is still loading, or in the event that there’s a web server failure that prevents the background image from loading.

Related Content

About the Author

Jacob Gube is the founder of Six Revisions and a front-end web developer. Join him on Twitter @sixrevisions and Facebook.

The post CSS Background Shorthand Property appeared first on Six Revisions.

Saturday, January 10, 2015

Semi-Transparent Buttons - Six Revisions

Semi-Transparent Buttons - Six Revisions


Semi-Transparent Buttons

Posted: 09 Jan 2015 02:00 AM PST

In this tutorial, you will learn how to create a semi-transparent UI button that works really well on photographic background images.

Semi-Transparent Buttons

View Demo

Download Source

GitHub Repo

Why Semi-Transparent Buttons?

Photo backgrounds are a hot web design trend right now.

Alongside this web design trend are ghost buttons, which look like this:

A ghost button example

Because their background is fully transparent, ghost buttons don’t distract our eyes from the photographic background as much as traditional web buttons that have a solid-colored background.

An issue with ghost buttons is they’re too subtle, especially because they’re competing against a photographic background. Site visitors might not perceive ghost buttons as being important because of their low visual weight.

Also, ghost buttons look like highlighted text. In other words, they might not portray the appearance of being clickable.

These are major usability problems.

On the other hand, a ghost button looks great on top of photographic backgrounds because of its background transparency. How can we preserve this aspect of the ghost button, while still making sure the button has strong affordance?

I came across a good solution on the Tumblr front page. Tumblr has this semi-transparent log-in button set on top of a photographic background:

Tumblr's semi-transparent button

It was an elegant middle-ground between a ghost button and a traditional solid-colored web button.

The semi-transparent background of the button allows some of the photo behind it to come through, which results in an appealing visual effect, similar to ghost buttons.

The classic button shape gives the semi-transparent button a strong and familiar visual signal that it’s clickable.

Semi-transparent buttons are easy to create. All we need is a bit of HTML and CSS.

HTML

The markup for this only requires a single HTML element. In this case, an <a> element is used.

<a class="semi-transparent-button" href="#">Button</a>

You can substitute in another HTML element such as a <button> or an <input>.

CSS

The CSS property that’s responsible for the semi-transparent visual effect is the background property. The background property is assigned an RGBA color value so that we can control its opacity. The color of the background is white with 50% opacity.

.semi-transparent-button {    display: block;    box-sizing: border-box;    margin: 0 auto;    padding: 8px;    width: 80%;    max-width: 200px;    background: #fff; /* fallback color for old browsers */    background: rgba(255, 255, 255, 0.5);    border-radius: 8px;    color: #fff;    text-align: center;    text-decoration: none;    letter-spacing: 1px;    transition: all 0.3s ease-out;  }

Also:

  • Rounded corners are achieved with the border-radius property
  • text-align is used to center the button’s label (which is a common trait of UI buttons)
  • max-width is set to 200px so the button doesn’t become too wide on larger screens
  • A simple animation effect is triggered when the user interacts with the button by way of the transition property

Additionally, a fallback solid background color using hex color notation is declared for browsers that can’t render rgba() color values (e.g. Internet Explorer 8 and below).

To improve the button’s affordance, we need to set an indicative style rule for the :hover, :focus and :active pseudo-classes. When the user hovers over or activates the button, we transition to a solid-colored background in order to suggest that the button can be interfaced with.

.semi-transparent-button:hover,  .semi-transparent-button:focus,  .semi-transparent-button:active {    background: #fff;    color: #000;    transition: all 0.5s ease-in;  }

One technique for increasing the semi-transparent button’s visual weight is to utilize a more vibrant background color. Opaque-white is a very neutral color, so in the demo, you can also find a semi-transparent blue button to use as an alternative. The code for a semi-transparent blue background is:

background: rgba(30, 52, 142, 0.5);

Another technique for increasing the visibility of semi-transparent buttons is to give them a solid-colored border. This can be done quite simply by giving the button a border property.

border: 1px solid #fff;

That’s really all there is to it. I hope this tutorial was useful to you in some way.

View Demo

Download Source

GitHub Repo

Related Content

About the Author

Jacob Gube is the founder of Six Revisions and a front-end web developer. Join him on Twitter @sixrevisions and Facebook.

The post Semi-Transparent Buttons appeared first on Six Revisions.