Subdomain

Clean Subdomains in Laravel

When building a website or application there are a variety of reasons you might want a subdomain ranging from SEO to full separation of application responsibilities. Craigslist uses subdomains to separate it’s different regions within states. Other websites use a subdomain to differentiate their blog from their main marketing content.

In my case, i’ve developed several web applications that have had siloed account logins (commonly referred to as Multitenancy). The way I approached that requirement was to subdomain the site, and use that subdomain to differentiate which tenant you were trying to access.

In Laravel this is pretty trivial to setup, but there are some snags associated with it and some nicer ways i’ve found to handle it. In this post we’ll see what Laravel offers by default, how we can clean it up using middleware, and talk a little bit about how to integrate it into your overall app.

How Laravel handles subdomains

Adding a subdomain in Laravel is trivial, and in our case we want to treat the subdomain portion as a wildcard that is handed to our code (see the overall docs for more on Laravel Routing).


    //routes.php
    Route::group(['domain' => '{subdomain}.mysite.com'], function () {
        Route::get('/', 'SubdomainedController@index');
    });

    //SubdomainedController.php
    namespace App\Http\Controllers;

    use App\Http\Controllers\Controller;

    class SubdomainedController extends Controller {
        public function index($subdomain) 
        {
            dd($subdomain); //die and dump the subdomain
        }
    }    

From that example you can see the subdomain can be specified as a simple option called domain to the Route#group method. Here we’re saying we want the subdomain in {subdomain}.mysite.com to be a variable parameter (allowing us to use a wildcard subdomain which can be controlled from a configuration file or database entry).

The other thing we see is the actual controller definition, where the #index method is being supplied $subdomain as a parameter. We can then use that parameter to determine how to handle the current user and url. From here we could create a common method or service that we call within our controllers and handles the subdomain logic for us…

But what if every controller in our app is under that subdomain? What if we have 50 controllers and each controller has some slice of the typical REST interface? Now we have to remember to not only call this common helper in every single method in our entire application, but we also have to clutter our method signatures by having every single one include $subdomain as a parameter.

It works, but it kinda sucks. We can improve it.

Cleaning up our method signatures with middleware

We can use a combination of middleware and request modification to both utilize our subdomain and keep our controller interfaces clean. Here’s what it looks like:


    //routes.php
    Route::group([
      'domain' => '{subdomain}.mysite.com'
      'middleware' => ['subdomain']
    ], function () { ... }

    //Subdomain.php
    namespace App\Http\Middleware;

    class Subdomain 
    {
        public function handle($request, $next)
        {
            $route = $request->route();
            $subdomain = $route->parameter('subdomain');
            $route->forgetParameter('subdomain');
            //store parameter for later use
            return $next($request);
        }
    }

    //SubdomainedController.php
    class SubdomainedController extends Controller 
    {
        public function index() 
        {
            dd(func_get_args()); //die and dump any arguments - we no longer have the subdomain!
        }
    }    

To make this work, we start by grabbing a representation of the current route being acted on using $request->route(). This instance gives us access to information about the route including the current url, what HTTP verbs it responds to, and the parameters that have been supplied (if any). We utilize the #parameter method to retrieve the subdomain part of the url.

Once we have a handle on the subdomain, the key to this middleware is the call to #forgetParameter. By calling this with our parameter name 'subdomain' as the argument, it’s no longer handed to our controller methods. We can get access to the parameter without cluttering responsibilities in our code. After we get the parameter we can then store it for later use (in the session, in the database, in a global app service).

A note about the #forgetParameter method: It took a little digging and I wouldn’t suggest it everywhere, but I think this is a case where it makes the app cleaner and is more inline with our expectations. In general I think of the Principle of least surprise in these cases. By which I mean modifying the request so that it no longer matches our expectations could be considered “surprising”. But the alternative responsibility that you place on every single controller is a much bigger problem in my opinion (and a big violation of the Single Responsibility Principle).

Testing your subdomain locally using php artisan serve or any local server

If you’re using php artisan serve to run your local server and you want to test using subdomains you have to make a small modification. Add the --host option and set it to 0.0.0.0.

php artisan serve --host=0.0.0.0

This allows your server to be available from any interface of your machine. It will be accessible by other computers on your network, tools like browserstack in local mode, and most importantly it can be configured with a local subdomain using your hosts file.

127.0.0.1   dev.mylaravelproject.com

Now you can go to dev.mylaravelproject.com:8000 and it will point to your local development server. Laravel will be able to pull the subdomain using your route group, and you’re good to go.

Making the subdomain less hard-coded

You may have noticed the example I showed for local development (dev.mylaravelproject.com) and the route I setup weren’t identical. One option is to make them identical, but then if you are switching between testing your actual server and dev server you would have to continually update your hosts file. You could manually change the entry, but that’s error prone (wouldn’t want to update production with a route pointing to “mylaravelproject.com” instead of your actual url). So I think you have two options:

1. Make the entire route configurable

2. Keep the route as an entry in your environment file

Making the entire route configurable

There’s nothing that stops us from having more parameterized pieces of your subdomain as in this example:


    //routes.php
    Route::group([
      'domain' => '{subdomain}.{domain}.{tld}'
      'middleware' => ['subdomain']
    ], function () { ... }

We now have three parameters, one representing the subdomain, one the domain and one the tld (.com, .net, etc). In our Subdomain class we could pull all the pieces out, and similarly call #forgetParameter on each of them. This works, but I think it might be overkill and a little deceiving. If we aren’t actually going to use the domain and tld for anything, why parameterize them – just for convenience? And if the URL ends up more elaborate at some point, this pattern may need to be adjusted again. Workable, but not ideal.

Making the route an entry in your environment file

The other approach is to make the entire string configurable at the .env level. I prefer this approach, because it means I can keep it parameterized for the subdomain but make it as different as I want otherwise. I just change the env variable depending on where i’m deploying to.


    //.env
    DOMAIN_URL={subdomain}.mylaravelproject.com

    //routes.php
    Route::group([
      'domain' => env('DOMAIN_URL'), //Use the environment value instead
      'middleware' => ['subdomain']
    ], function () { ... }

Now we can still focus on the {subdomain} parameter alone, and have the configurability we need to move between environments easily.

Closing

We’ve learned how to use subdomains in Laravel, what it does to our code, how to make the experience cleaner, and how to keep it configurable. It took a few extra steps, but adding in these settings and middleware will make your code more easily maintainable as you move forward. Now that we have a subdomain in our site: what can we do with it, how do we track it, and what does it mean for our users? We’ll explore that in a later post. Let me know if you have any questions or input in the meantime by leaving a comment!

Clipboard

Using the Device Clipboard in React Native

As a quickly evolving library, React Native is often supplemented by features from the community, only to consume them or incorporate similar concepts later on.

Up until a few months ago, using the native clipboard on iOS or Android meant installing an npm module and then configuring the native components in each device environment (configuring the library in XCode or modifying your configuration for Android).

It wasn’t a huge burden, but it still required some platform specific knowledge and a few extra steps beyond being able to just plug and play with the module.

Existing packages

If you’ve tried using the native clipboard before in a React Native project you’ve probably used one of the two main libraries available for it: react-native-clipboard (iOS and Android) and react-native-pasteboard (iOS only).

With release 0.17 of React Native, those packages are no longer necessary. We now have a Clipboard component which works seemlessly for both iOS and Android.

How to use it

The functionality is as straight forward as it gets. There are no configuration file changes or library linkages required. Just import from the react-native package and go to town.

Here’s how to import the component using the ES6 import syntax


  import React, {Clipboard} from 'react-native';

Then to set a value to the device clipboard call #setString


  Clipboard.setString('my string');

Getting the current value is a tiny bit more work, as it’s returned asynchronously in a promise returned from #getString


  Clipboard.getString().then(function (content) {
    console.log(content);
  });

And if you want to use the ES7 await/async functionality (which React Native ships with enabled by default), it looks like this


  async function getString() {
    console.log(await Clipboard.getString());
  }

Just remember that your code has to be in the context of an async function for await to work properly.

The whole example


  import React, {Clipboard} from 'react-native';
  Clipboard.setString('my string');
  Clipboard.getString().then((content) => {
    console.log(content);
  });

Now with only a few lines of code you can set a value to the device clipboard, and retrieve it.

And that’s it. Go forth and copy/paste.

React Native WP

React Native impressions from a Cordova user

Introduction

As web developers, we see the potential that the web offers, as a platform and as a cross platform development environment. I don’t think it’s a desire for sameness or lack of imagination that propels web technologies across device targets, but the potential and power of what those tools can provide.

But being so ubiquitous means that solutions often fall short or feel off in comparison to what a platform provides natively. Native application development vs development using a web stack is a source of constant debate, and generally when tested at the extremes, web technology struggles to hold up to what a native experience can offer.

The gap is closing. Cordova has been a great environment, but as a baseline it is difficult to achieve the same level of polish and native feel that comes more natural from a native application. Frameworks like Ionic and Framework 7 make bridging that gap much easier. Their creators and developers have taken the time to polish and provide a set of tools, interactions and widgets so you don’t have to try and build it from scratch every time (and often fall short in trying).

But what if we could utilize our familiarity with part of the web stack (javascript) to delivery something truly native? A seamless experience delivered by web tech but not bound by it.

React native might be the answer to doing just that.

Where I’m Coming From

Talking about React Native as someone who uses web technologies in almost all of my development, a meaningful comparison would reference back to that tech. When is and how is React Native more compelling than what the competition offers?

What makes it a better alternative to a tool like Cordova matched with Ionic or Framework7? What are its clear strengths? Where is it lacking and where will it improve? That’s what i’m trying to answer for myself, and explore in the rest of this post.

A Very Brief History

React is the base library that powers React Native, and is a view layer, written in Javascript, and originally created by engineers at Facebook. Since its initial release in 2014 it has risen in popularity quickly (32K stars on github and rising) and people have been embracing its model. You write all of your view layer in their abstractions, and let them manage rendering to the appropriate format. They manage your UI and the flow of your data in an optimized way.

We’re seeing them refine React into a reusable base library, and extract the view implementations into their own modules (they recently removed all DOM related logic and created a new package – react-dom – to handle that for the web side of things). In addition to react-dom in the browser, people are using React for server-side rendering, and Flipboard recently came out with react-canvas – which writes your UI directly to the canvas tag. These are just a few examples of React view implementations taking the base React layer and applying it across different environments.

The obvious momentum here is towards reusing the React architecture to output to different formats. React Native takes these same principles, and applies it to the native app environment.

Why React Native

Learn Once, Write Anywhere

“The focus of React Native is on developer efficiency across all the platforms you care about — learn once, write anywhere.” (https://facebook.github.io/react-native/)

With the ability to learn all of the react principles and patterns, and then apply those to whatever view abstraction can be written, you’re able to take all of that knowledge and apply it on multiple views and across different platforms. Not just platforms that contain a browser but any platform where javascript can be run.

You know react from using it in other environments, and you’re now able to leverage that to build a native app. The components are different, how it functions is different, but the concepts are all the same.

Truly native

Everything you use in React Native is, behind the scenes, a native UI component. Many of the features that native developers are accustomed to on Android and iOS are available to you in their actual forms.

My understanding is that React Native makes this possible by serializing communications from your Javascript layer to a native layer, where the UI work is accomplished. Your javascript SwitchIOS component is a native iOS switch. Same for your MapView and ListView. It’s all first-class with the rest of the app environment. You define what you want to use in Javascript, and React Native handles the communication and implementation of how it is rendered.

runtime

The result is a larger ecosystem of code you can lean on, as well as out of the box improved performance.

Performance

One of the top reasons to use React Native is for performance. Because your javascript is communicating instructions to actual native code, you are able to operate at near native speeds. Your animations, gesture recognition and layout rendering will all be faster with no additional effort on your part.

Knowing that you are getting these out of the box gains, the main concern you are left with is keeping your javascript code running lean. Javascript operations are batched up and then sent to the native layer, but if your processing takes too long you can miss some of those communication windows and cause visibly degraded performance.

The React Native’s team is heavily focused on getting the best performance out of every aspect of the library they control. As part of their developer tools you can actually monitor the framerates of both your native UI and javascript threads, which helps to debug where a slowdown might be occurring.

perf monitoring

First Class Native Projects + Keeping up with iOS/Android updates

With a React Native project your generated iOS and Android applications are a first-class part of your development and source control. The obvious benefit here is unobstructed control of all of your application settings and libraries.

In the Cordova model, your “platforms” (the implementation of code for a given operation system like iOS and Android) are read-only and are not intended to be source controlled. The output of that generated code is controlled from generic configuration files within your project.

The Cordova approach is a double edged sword because while you are benefiting from the generic cross-platform nature of your configuration files, you can also lag behind new developments and be forced to wait on Cordova updates or make modifications to the runtime yourself. Recently there were issues with the introduction of Application Transport Security in iOS 9, which meant having to use some hacks to get around the problem until Cordova could release an update to address it (which took some time).

Using React Native you trade off the generic configurability of Cordova for full project control.

Community

The React Native community is growing fast. Much like the React community, React Native is garnering tons of attention and contribution. As of this writing they have around 24k github stars, and new modules are coming out for it every week.

But,

It doesn’t feel quite like an ecosystem yet as much as a large group of people excitedly producing code. There are a number of React Native modules started and abandoned, many of the modules are not mature enough yet, and they’re working on a moving target. The React Native team is doing a good job avoiding massive breaking changes, but the framework is young and these things are to be expected.

App Reloads / Dev Tools

Ability to reload from the app was awesome, and something Cordova and Ionic are only just starting to offer.

You can bring up and options menu while running your application in real-time, and it comes with several options including live code reload, remote debugging from your browser, and performance statistics of your running code.

debug-console

Touch Events

The gesture system in React Native is a rich and complicated aspect of the library. They claim that the touch interaction offered by the web is a big usability issue, and that “Users can feel huge differences in the usability of web apps vs. native” ref.

I’ve seen and worked with some great touch interactions in a web context – but I believe them that there is more the user could be offered. I just haven’t seen the value in action yet. The “Gesture Responder System” is a fairly dense API and I haven’t gone beyond basic tap interactions with it so far.

UI Flow

Everything being native, the flow and styling of your application is very consistent. Contrast this with trying to integrate a native component into a Cordova application and it’s a very different experience. Bringing in something like the native Map component and trying to style it into a completely different UI paradigm (your webview) can be confusing and the precedence of elements unclear.

In React Native, it’s as easy as laying out your components and styling them using a subset of CSS that you define in your javascript. The components interact and flow with each other naturally with no magic involved, because everything is speaking the same language.

Where it’s the only option

One of the most interesting aspects of React Native is its ability to go places that standard web technologies cannot.

Up until a year ago, Cordova was still an option for all the common “smart” technologies that people used: phones and tablets for Android, iOS, Windows Phone (even Amazon FireOS, Firefox OS, Blackberry, and more). But it wasn’t until the Apple Watch came out that hybrid developers found themselves at a loss. Watch OS 1 and Watch OS 2 do not support UIWebView.

Around six months later Apple released tvOS. Another platform intentionally missing UI and WKWebView.

There is a reasonable explanation for why they’re excluding webviews: they just don’t make sense on those platforms. The reason they include webviews is to be able to display web content. But interacting with a web page on your watch, even a responsive one, is cumbersome at best. tvOS has a similar problem in the opposite direction – they don’t expect people to be interacting with webviews on a large screen using a remote control. Wired explains it pretty nicely: “Instead of tapping and swiping a 4.7-inch display with your fingers, you’re using a remote to control a 55-inch digital tapestry from 10 feet away. It’s like trying to play a banjo with two oven mitts on.”

So without a webview, what can a hybrid developer do? The answer right now is nothing. So far there are no solutions to get around this problem.

So in the case of these two platforms, React Native has the potential to shine. Being a native technology that doesn’t rely on a webview, we’re able to adapt to almost any platform.

The community is already working on it for tvOS: https://github.com/facebook/react-native/issues/2618

tvos

Watch OS is not receiving much interest so far, but that certainly could change over the next year: https://github.com/facebook/react-native/issues/685

Unless Apple releases webview capabilities for these platforms in the future, Cordova will never be an option for them. So you’re left with either developing something entirely natively, or using an environment like React Native.

Scratching the surface

There are alot of other reasons to look into React Native and what i’ve described are just my impressions, understanding and usage so far. Check out their docs for more. I haven’t had a chance to fully utilize it yet, but their animation implementation looks powerful.

Why Cordova/Ionic

We’ve gone through what i’ve learned about React Native so far and what has me excited. But what are the positives to continuing with a tool like Cordova?

Familiarity

The obvious win for developing applications using standard web technologies is familiarity. When you develop an app using a tool like Cordova, you are writing standard HTML, CSS and Javascript. Whatever tools or approaches you add on top do not change the fact that this is the same code that could also power a website.

Does this familiarity actually play out in practice? Do web developers navigate seamlessly into the mobile world?

My experience is that no, it’s rarely that straightforward or simple. Frameworks make it easier, but there is always a learning curve to thinking with a mobile mindset, understanding the proper interactions, and dealing with the quirks of developing in this environment.

But is the learning curve smaller – definitely.

CSS, not “Styles”

I glossed over the way React Native handles styling when I talked about UI Flows earlier. That’s because despite the benefits of of all your components interacting consistently and performing nicely, the way you style them is not exciting. It works, but there are some definite weaknesses (you can read through a speaker deck about why they made these choices here. It’s at the top of the article).

To start, what you know about CSS is only partially relevant here. The full specification is not implemented, shortcuts are not supported, and you have to define it all in your Javascript code. It’s somewhat akin to writing all your styles using the dom style attribute, but more limited (everything is assumed to be pixels, for instance, so you define things like margin and padding as simple integers).

For example:


var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    margin: 10,
    marginBottom: 5
  },
  text: {
    color: 'black'
  } 
});

That code compiles your definition, and you can now use that styles object to apply styling to your components.

Applying the styles

So how do we apply this to our components? Let’s take a simple React Native code sample, and apply it to that. I’m not going to elaborate on what is going on in the code except to note how the styles are being applied, since the general concepts are the same as any React code.


var ExampleApp = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}>
          My example with styles applied.
        </Text>
      </View>
    );
  }
});

If you’re like me, your initial reaction to that example is probably something like this:

inline-styles

It’s a CSS styling sin to employ inline styling at all, let alone as your primary mechanism for your entire layout. It’s a bummer, but in practice it’s not so bad. In a sense the styles are acting a bit like selectors, in that you are defining your style elsewhere and referencing it from here. There is some amount of cascade that goes on here as well, though I haven’t identified all the rules around it yet and have encountered some surprises along the way.

Flexing your layout

You may have noticed I have some flex properties defined in that example, and that’s because in addition to only supporting a subset of properties, React Native only supports one layout option: Flexbox. This also seems like a downside, and technically it is (more options being better than less), but it turns out to be a pretty solid choice. Flexbox supports the app layout and concept nicely so in practice this is not a huge determent – just a learning curve for many developers (including myself).

Miscellaneous

There is no nesting of styles, so you end up defining multiple style objects, or prefacing your definitions with additional context about where it goes. It doesn’t always use standard names and properties: flexDirection instead of flex-flow, for instance. So even where it is using standard CSS concepts there are some subtle differences. (correction).

React Native’s approach to styling works, and at least you can take advantage of many of the principles of CSS… But it’s not CSS. It’s comparatively cumbersome, verbose, and seems likely to stay that way unless projects like react-native-css take off and become a community standard.

Back to Cordova

So developing using standard CSS means you have the full feature set of CSS available, and as new features are added you can start to take advantage of them immediately. It works the same way you’re used to in your regular web development, and that’s a pretty large advantage.

It also means you can potentially use things like CSS Grid Layouts. I’m going to back away slowly now, before i’m pressed further and you realize I have no idea why that would be useful to you. But it’s coming, you won’t get it with React Native today, and may never be able to.

Updating your app without updating your app

The app submission process is not known for being speedy, so having options to update application functionality without going through a full submission process is a definite benefit towards developing applications with Cordova. There are lots of tutorials explaining how you can achieve that, so I won’t go into it here. But being able to load in your javascript and CSS remotely means faster code turnaround and faster deployment of new features to your users.

However

Originally I thought this would not be an option for React Native, but was proven wrong pretty quickly. It’s not quite as straight forward as what you can do with Cordova, but there are approaches available.

Apphub offers a service for it: https://apphub.io/

And here is a medium article about dynamically updating your app: https://medium.com/ios-os-x-development/so-you-want-to-dynamically-update-your-react-native-app-d1d88bf11ede

Richer pre-built components

In fairness, React Native is a young library. And compared directly to straight Cordova, they actually have an advantage because of their out of the box native components.

But the existing pre-built components (both in the project and in the community) are still pretty limited at the moment, and not as mature as what you’d get by using a library like Ionic.

I was disappointed to find no Pull to Refresh or Swipe action implementations available in React Native itself. From what i’ve read in their responses to issues is that they aren’t interested as a core project in coming up with a huge array of components – they want the community to get involved to build that out while they focus on the library itself. I can definitely respect that, and I look forward to what gets produced over the next year. There are already some community pull to refresh and swipe action implementations available, but the quality is variable right now.

So compared to what I can use now in Ionic, if I had to build something on a tight timeline and use a breadth of components, Ionic has a clear advantage.

Example

Before I close, there are a couple great tools I want to mention for playing around with React Native with the lowest barrier to entry possible.

Appetize.io (https://appetize.io/) is a service that lets you stream iOS and Android apps in the browser. While not directly relevant to React Native, it’s what powers the next tool.

Rnplay.org let’s you write React Native code in your browser and test it using their app viewer (which is powered by appetize.io). Other users can fork your code and for trying out React Native for the first time there is no better option (as long as you don’t need to branch outside the core components). I’ve embedded an example here for you to try. Feel free to fork the code and see what you can put together!

https://rnplay.org/apps/aPx5Uw

Conclusion

You’ll notice that where I have complaints about React Native, most of them are surface level, or related to the young age of the project. I’m excited about what React Native is offering, and excited for what is next for them.

I’ve been using Ionic/Cordova for awhile now, and really enjoy it. I’ve deployed client code using it, and will continue using it for the foreseeable future.

But React Native has definitely caught my eye, and I think it’s a powerful and interesting project. It’s not usable for everything just yet – there are some widget niceties that I think it needs for more mass appeal and quick use. But it will get there, and using it has been fun and productive so far.

I’ve got an app coming out soon that I will write about more in depth in terms of actual implementation details using React Native. Something very simple, but it gave me a good way to test the tech and see what React Native could offer and handle, and fueled everything in this post. I’ll go into specifics about what modules I used, benefits of the native experience, issues I hit, community responsiveness, resources available, and bugs in the platform I encountered.

So what is my final feeling on React Native? Excited, and a little mixed. There’s a side of me that loves everything they are offering and the possibilities, but it is also at odds with my love of a more pure web tech solution. Despite using many elements of web technology is also eschews a lot of it and does its own thing. So if you’re a web developer looking to try React Native – you’ll feel comfortable there, but not exactly at home.

Update 12/5/15:

Thanks to @notbrent for some feedback on this post. Notably pull to refresh just landed in core ios/android, and a mistake I made about non-standard flex properties (flex-direction is valid. While react-native doesn’t support shortcut definitions, the properties it supports should be capable of handling all simple forms in a standard way)

Click Delay

Better Than Bootstrap Javascript: Click Delay

This entry is part 3 of 3 in the series Better Than Bootstrap Javascript

Last week we dug into Javascript Carousels, first analyzing the implementation Bootstrap offers and then examining two alternatives in Flexslider and Slick. We reviewed examples in each and noticed the simplicity of setup as we moved beyond Bootstrap – but that wasn’t enough. Developer productivity and effectiveness is important, but what else did alternatives have to offer?

Ultimately, the user experience was the major differentiator. Flexslider and Slick offered swiping and dragging for navigation, natural animations, and fine tuning for responsive displays. One important differentiator was around user feedback – how the carousel responded to a users tap or click, and the detriment of the click delay.

This weeks post is a bit different in that it’s not specifically comparing a Bootstrap component to an alternative, but comparing the absence of a feature and how you can implement it in your web apps. Let’s get started.

Click delays and the smartphone tap

If you’re an iPhone user, i’d encourage you to visit the Bootstrap website on your phone and tap around on the links and features displayed there. A great example on the phone would be clicking the “hamburger” menu (the three stacked bars you see at the top right corner of the page). You’ll immediately notice the short delay between tapping the menu, and actually seeing the content open or close. Is it loading from the server? Did my action register?

Bootstrap-Delay

Looking at it in action, it’s not painfully slow. Is there really an issue? Is the perceived latency that big of a deal?

Now go to the Google homepage, and click the menu in the top left corner (again, the same “hamburger” style menu, with three horizontal bars). Here, the reaction is immediate. You tap, and right away it slides open and gives you a scrollable list of pages. Tap it again (now moved to the right) and it immediately slides closed.

Google-Tap

The experience on the Google homepage is a clear improvement over that of the Bootstrap site. The Bootstrap responsiveness seemed fine, but then we experience Google’s menu and the Bootstrap interaction feels less natural. The responsiveness of Google’s menu is instant – difficult to distinguish from a native application.

What’s the deal, Bootstrap?

You might be wondering why Bootstrap, being a mobile first framework, wouldn’t take care of something like click delay for you?

I’ve never looked into it specifically, but Bootstrap’s reasons could fall into a few camps – reducing dependencies, inconsistencies between the multitude of platforms Bootstrap tries to support with one codebase, or feeling that browsers will eventually fix the issue for them.

I used to be a jquery mobile user, and their goal is to support as many mobile platforms as humanly possible. They found removing the click delay was problematic while trying to maintain maximum platform support, so they left it as a task for the developer to deal with on a case-by-case basis. Since Bootstrap does the same, it’s up to us to figure out how to approach the issue.

So how can we move ourselves beyond the sluggishness of the Bootstrap site with their click delay to the immediate feedback that we get in the Google example?

Immediate feedback with touch events

The first approach you could take to resolve this might be with touch events. Touch events are fired immediately when a user taps something. Using touchstart, we recognize the users tap and can react right away.


$('.action-button').on('touchstart', function () {
  alert('no click delay');
});

The problem is that this is only useful for isolated interactions. What about regular pre-existing links on the page – do we apply touchstarts to them all? What if we want to prevent the default behavior and perform a different action when something is clicked? How can we apply this to existing javascript code running on the site without modifying it (for instance, how could we improve the speed of the Bootstrap menu)?

Pretty quickly, the depth of the click delay issue becomes apparent. In principle the solution could be simple, but the reality is that it bleeds into all aspects of your site, and can be inconsistent to implement between browser vendors and devices.

Leveling the playing field with FastClick

The most popular approach available to solve the click delay issue is with a tool called FastClick. They take the issue and approach all of the multitude of scenarios for you, all wrapped up in a very simple API.

Since we’re talking about Bootstrap here, I’ll assume jQuery is available and use it to load FastClick once the DOM is ready. You get a reference to the body element (which can be accessed directly from the document object using the body property), hand it off to FastClick, and you’re good to go.


$(function () {
  FastClick.attach(document.body);
});

This is the shotgun blast approach. Everything on your site is now freed of the click delay – buttons, links, click events – all of it. FastClick attaches itself to the touch events that are immediately responsive (similar to what we did with touchstart earlier), and handles the rest for you from there.

Now when you attach a click event to something, the delay is gone. Not only that, but our ability to suppress the default behavior (for instance, a link changing the url of our browser) is also available.


$('.action-button').on('click', function (e) {
  e.preventDefault();
  alert('clicked immediately!');
});

It’s dead simple, and generally it just works.

If we apply FastClick to our Bootstrap example from earlier, we now have the same responsive feel that the Google homepage gave us.

Bootstrap-Fastclick

Alternative to FastClick: device-width

You might notice that when I first talked about the issue, I said “If you’re an iPhone user…”. That’s because outside of the iPhone, there are some alternative approaches that browsers and devices take to the click delay.

If you’re on an Android phone, check out the sites I mentioned earlier (Bootstrap and Google) in Chrome. Depending on your Android version, and which provider released it, you may not experience any click delay. This is because some browser vendors have been introducing ways to avoid click delay when your site meets certain criteria. In this case – if you define your viewport as being the width of the device – Chrome on Android will remove the click delay for you.


<meta name="viewport" content="width=device-width">

In general, this is an important setting for mobile-first sites, and a Bootstrap recommendation. Having a width of device-width means your viewport width is based on the device you’re using. So if your site is responsive, and the width of the viewport is device width, you’ll get a display that is better suited to the device.

On Chrome on Android, they piggy back on your viewport setting to mean you don’t need tap-to-zoom, and they remove the click delay for you automatically.

You can read more about this here. That article is also nice because it mentions approaches that apply to Windows Phone as well, which works by a different set of rules from iOS and Android.

Why wouldn’t I always use FastClick?

Learning about FastClick might seem like a good point to stop the discussion, apply it to your site, and call it a day. And in many ways, it could be. If you have a responsive site using Bootstrap and you want to remove click delay across the board, this is the way to go.

There are some warnings here, though. FastClick works really well, but like any project it is continually in development, and it can have issues. New versions of mobile OS’s come out and break things. The browser vendors are not expecting FastClick, they implement their own behavior, and edge cases arise. FastClick meets the browser, meets the rendering and javascript engines, and on the fringes of functionality things can breakdown.

In some cases, FastClick can also impact other plugins. At the time of this writing i’ve had issues personally getting FastClick and Select2 to play well together, and have had to patch FastClick to bypass the issue. This is something that could happen with other libraries as well, who may try to eliminate the click delay issue themselves, or just have some other scenario which ends up conflicting with what FastClick is trying to do.

There’s also the question of whether this user experience matters to you at all. If your site is heavily content driven, and most of the interaction is through clicking links – you may not want to bring in another library just to remove a click delay which only happens as the user intermittently clicks things. Perhaps in this case just manually applying touch events when appropriate is the better approach (for instance, to improve a specific scenario like a carousel, but not to remove it from everything across the board).

The important thing to consider if that FastClick is a tool, and you should weigh the benefit of the tools that you use, and test them on your site. If you’re creating a web experience that needs to give the user a native feel – I’d encourage you to use FastClick. Just make sure you do your due diligence and test your site before pushing it off into production.

Should I always use device-width?

If you’re designing responsive, mobile-first sites using Bootstrap, then you should definitely be setting the device-width on your viewport. But in terms of its impact on click delay be careful, and understand the extent to which it’s available. If you have some sense for what browser or devices you’re deploying to, test to see that it actually works.

I’ve encountered situations where it didn’t work, even when it was supposed to. I had a client with a lower-end Android tablet being deployed to their userbase running Android 4. We were having the client use Chrome and the click delay was supposed to be removed. It wasn’t. Even applying FastClick we still had some work to do – FastClick tries to intelligently disable itself if it detects a browser and device which should have click delay disabled natively. In the end we had to apply a minor patch to FastClick to remove the check for the native feature.

Approaching the problem differently with FastActive

A very different way of approaching click delay is to solve the problem by altering the users perceived performance and offering immediate visual feedback, even if the actual result of the interaction is not immediate. This can be achieved by using the FastActive library.

It applies an .active class to links and inputs, so you can create the appearance that they are reacting immediately (through CSS). This may be an alternative for you if you do not want to risk platform related click issues, and are more concerned with the users perception of performance.

Conclusion

You’ll notice that i’ve talked at length about user perception and interaction in this Bootstrap series so far. This is because despite my love for the web and its potential, the experience of native is compelling and fluid and fast, and the web struggles to compete with this out of the box. More and more people have an expectation of performance, regardless of whether they’re in an app or in their browser. The app experience creates high expectations, and that expectation still remains when using the web. How we deliver on that expectation is through tools and approaches like these.

If approaches like flipboard’s react-canvas are any indication, ios has raised the bar and users are expecting beautiful interactions. Flipboards approach was about flawless animation and scrolling. Click delay wasn’t even discussed in this situation because it’s so basic as to be taken for granted – it’s just not an option. When I hop out of a native app where I can swipe, tap and scroll with ease into a website where I click a link that takes 300ms to register, I feel it. And if your app is trying to compel your users to continuing using it, that may make the difference between them coming back or choosing something more compelling (or ditching the web entirely, and using a native app instead).

Carousel

Better Than Bootstrap Javascript: Carousels

This entry is part 2 of 3 in the series Better Than Bootstrap Javascript

Last week we started small, and looked to improve the perceived performance of our website with interactive loaders. We looked at what Bootstrap had to offer out of the box, and then explored a more robust option with the Ladda plugin.

This week we’re aiming to improve the carousel experience. Carousels are ubiquitous on the web and are used for a wide variety of purposes – from picture slideshows to client testimonials to an entire web page experience. And while there are some people who say you shouldn’t be using carousels, the bottom line is they won’t be going away soon, and are a useful tool to use and understand.

So let’s start by taking a look at the Bootstrap approach.

Bootstrapping our Carousel

In comparison to Bootstrap loaders and buttons, Carousels is a more meaty area of functionality.

Here’s an example of a simple Bootstrap Carousel.

<div class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
    <li data-target="#carousel-example-generic" data-slide-to="1"></li>
    <li data-target="#carousel-example-generic" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner" role="listbox">
    <div class="item active">
      <img src="slide-1.jpg" alt="First slide">
    </div>
    <div class="item">
      <img src="slide-2.jpg" alt="Second slide">
    </div>
    <div class="item">
      <img src="slide-3.jpg" alt="Third slide">
    </div>
  </div>
  <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="right carousel-control" href="#carousel-exa mple-generic" role="button" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

To setup the Bootstrap Carousel, you need to manually specify all of the html elements that go into it.

The .carousel class specifies the carousel container.

The .slide class specifies how to transition – in this case sliding. The alternative is to remove the class and the images change immediately.

The .carousel-indicators list specifies the position indicators at the bottom of the carousel.

.carousel-inner is the main content of the carousel, and the elements that get displayed are labeled with an .item class. To make sure your carousel displays at all, you have to make sure one of the items has an .active class applied to it.

For moving back and forward in the carousel, we have the .carousel-control class, and the data attribute data-slide with a value of “prev” or “next”.

Having specified all your markup, you can initialize the carousel in one of two ways.

1. Apply the data attribute data-ride="carousel". The plugin automatically applies carousel functionality to any markup on the page with that data attribute, on page load.

<div class="carousel slide" data-ride="carousel">

2. Initialize the carousel manually in Javascript

$('.carousel').carousel();

The result for our efforts is a carousel with clickable position indicators, click forward and back navigation, and that gives a baseline level of responsiveness based on screen size (it becomes smaller or larger as the screen size changes). It works the way we expect and gives us a solid carousel experience.

See the Pen Bootstrap Carousel by JP Camara (@jpcamara) on CodePen.

In addition to what i’ve shown, the plugin also offers a couple events (before and after the carousel slide has occurred), a few configuration options, and an API for manually pausing and moving forward and backward in the slides.

You can see that the functionality is limited, and the setup is very manual. We specify every piece of our html, and the capabilities we have beyond what you saw in the example are limited. What if we want additional transitions? What other capabilities are there for responsiveness? How fluid is the interaction on mobile?

Truthfully, I’ve never decided to go with the Bootstrap Carousel on any of my projects. The alternatives are just too good, and equally as easy (or easier) to setup. I’d suggest always using one of the alternatives, unless you have a real restriction on a project and can’t bring in outside libraries.

Flexslider

“Best responsive slider. Period.”

The first alternative to Bootstrap i’m presenting is Flexslider. Their boastful claim aside, it is a great carousel library and the functionality it delivers is pretty compelling.

Flexslider is a robust solution and was my go-to for a long time. It offers tons of flexibility, works great on mobile, has integrated swiping and comes with more levels of responsiveness.

Let’s look at an example of our markup.

<div id="flexslider-carousel" class="flexslider">
  <ul class="slides">
    <li>
      <img src="slide-1.jpg" />
    </li>
    <li>
      <img src="slide-2.jpg" />
    </li>
    <li>
      <img src="slide-3.jpg" />
    </li>
  </ul>
</div>

The thing we immediately notice is the simplicity of what we need to setup. Whether this is a good thing or not is a matter of preference. The Bootstrap markup is very manually specified, but that gives a decent level of control over exactly what is presented. With Flexslider, it does most of the setup for you and you just specify a small set of markup for it to enhance. It’s something of a Convention over Configuration approach – we provide Flexslider with a simple, consistent structure and it will handle the rest for us. Control over the output past that point comes in the form of configuration options and CSS styling. Personally, I prefer the slimmed down setup so I’m a fan of the Flexslider approach.

The conventional Flexslider setup contains the following pieces.

An outer container with a class of .flexslider.

An inner list of elements, with a class of .slides. This contains typical li items. Whatever content they contain is the content of the carousel.

And that’s it. A couple classes and a list. Having specified that markup, you can initialize the plugin by using the Flexslider API. We’ll also pass in a configuration option of animation here, to achieve the same transition that our Bootstrap example had.

$('.flexslider').flexslider({
  animation: 'slide'
});

The results of that effort in this case result in an experience similar to what the Bootstrap plugin offered. It has position indicators, forward and back navigation, and responds to screen size.

See the Pen Flexslider Carousel by JP Camara (@jpcamara) on CodePen.

So if we’re getting a very similar experience, is the only benefit we get is that there’s less markup? Isn’t that just a matter of preference?

Probably the most important benefit you get, before even digging deeper into configuration options and the API, is that the mobile user experience is much closer to a “native” feel.

Click Delay

The back and forward indicators (and the position indicators) in the Bootstrap Carousel suffer from what is known as “click delay”. A common problem on mobile touch devices is that clicking things like links is hampered by a 300ms delay. This is a problem caused by the mobile browser not knowing whether your tap on the screen is meant to perform an action, or if you’re in the process of double tapping to zoom in on some content (a common mobile browsing convention for zooming in on content that is not responsive, invented by Apple and replicated by every smartphone after them). So it mitigates this by enforcing a 300ms delay to determine your tap intention (you can read a more in-depth discussion of this topic here).

This may not sound like a big deal, but as I mentioned in the Bootstrap Loaders post, humans can perceive latency in as little as 100ms. 300ms leads a person to question whether their interaction even registered at all, and is a suboptimal user experience (imagine going through your mail on your smartphone, and every time you clicked an email it took 300ms to respond in any way – you’d probably drop the app, and the phone as well if everything were like that).

In Flexslider, click delay is not an issue. When on mobile, Flexslider uses touch events to control forward, back and positional navigation. This way the latency is non-existent and the interaction is immediate – your carousel moves forward and back as soon as the user taps it.

Swipe to navigate

In addition, a common pattern users have come to expect on mobile is the ability to swipe through things. It has become a natural expectation that many elements you interact with are capable of receiving, understanding and reacting to swiping and dragging gestures. With Bootstrap, the functionality is absent. With Flexslider, the user’s gesture registers immediately and can be used to either swipe quickly through items, or slowly drag between them.

Animations

The animations in Flexslider feel more natural than the Bootstrap equivalent and the position indicators give a more interactive feel to the items when clicked.

The first point is around the way we animate in between slides in our carousel, which has to do with what the animations “easing” is. “easing” basically has to do with how objects move – the Bootstrap easing is “linear”, meaning the animation progresses at a constant pace. Since most things don’t move that way (at a constant pace), it doesn’t feel as natural. It doesn’t feel “wrong”, but when we see the Flexslider animation in comparison, there’s a more fluid and understandable feel to it. The Flexslider easing is called “swing”, and it means the animation progresses slower at the beginning and end (you can see examples of lots of different easings here. I think “easeQuadOut” is the equivalent of “swing” in this case).

The second point is about how the positional indicators work. If you have more than two slides in your carousel, Bootstrap never changes the positional indicator behavior. I’m on the first slide and I click the third slide, I’m animated automatically to the third slide. There’s no sense of movement or position in the animation. In addition, it’s somewhat confusing if i’ve gone through all the slides, because casually sliding in the third slide in this case causes me to wonder what happened to the second slide – we’ve bypassed it entirely. In Flexslider, the slides are all quickly animated through, so you see that you’re actually progressing back to the first slide rather than being immediately transported there.

These might be more a matter of preference, but I think the difference is noticeable and an improvement to the experience.

Digging Deeper into Flexslider

For me, the improved mobile experience around gestures and tapping would be enough to warrant using Flexslider over Bootstrap. But i’ll talk about a few more configurations and API pieces before leaving the rest of the exploration to the reader.

An Example

$('.flexslider').flexslider({
  animation: 'fade',
  selector: '.slides div.slide',
  end: function () { alert('last slide!'); }
});

Here we’re modifying just a few options to add/change some functionality.

animation allows you to specify how the slides will animation. While not wildly expansive, you can choose “fade” in addition to “slide”.

selector lets you change some of the convention aspect of Flexslider. The convention is to specify a list item li, but here you can modify things so more types of markup are capable of being slides.

end is one of several events, in this case being fired when the carousel reaches the last slide. It’s useful for a plugin to have points to hook into throughout its lifecycle – you’ll inevitably find yourself in a place where knowing the state of your plugin is important due to a project requirement.

Flexslider comes with many, many options, but you don’t need to worry about them until you need them. I’d approach it in the simpler form to start, and add more capabilities when necessary. You can see the Flexslider homepage for more interactive examples.

Slick

“the last carousel you’ll ever need”

While probably not the last carousel you’ll ever need, since I learned about Slick it is becoming my new favorite option.

As with Bootstrap and Flexslider, let’s start off by looking at a markup example.

<div id="slick-carousel">
  <div><img src="slide-1.jpg"/></div>
  <div><img src="slide-2.jpg"/></div>
  <div><img src="slide-3.jpg"/></div>
</div>

It seems we’re getting progressively simpler. In the case of Slick we have even less to define and even more convention than Flexslider. The conventional Slick setup contains the following pieces.

A container element of some kind. Since we hand the element to the Slick API, it doesn’t really matter what it is, and it doesn’t require any special classes.

div elements to indicate the slides inside. This was something of a strange convention to me since I think of li elements when thinking of slides, but it’s the default. No extra classes required, it just finds the child elements and makes them slides.

After that, we initialize it with a call to the Slick API. We’ll include the dots configuration here to be consistent with Bootstrap and Flexslider (it’s disabled by default).

$('#slick-carousel').slick({
  dots: true
});

Again, we have an experience similar to Bootstrap, and now Flexslider – forward and back navigation, responsive sizing and position indicators.

See the Pen Slick Carousel by JP Camara (@jpcamara) on CodePen.

So surely we’re hitting an impass? Bootstrap was ok. Flexslider was alot better. How could Slick be better than what we’ve seen so far?

A Plethora of options

Slick is highly configurable. Not only does it have a lot of options, it also comes with additional functionality that neither Flexslider or Bootstrap offer.

Responsive Display

Flexslider and Bootstrap come with fairly basic responsive capabilities. Bootstrap gets smaller or larger as your shrink or expand your screen size. Flexslider does the same but also offers some variability in the width and margins of its slides, making it seem a bit more responsively flexible. But Slick takes this configuration to a totally different level.

Slick allows you to setup a responsive configuration property, which takes an array of objects defining how it is supposed to behave at any breakpoint you define.

$('#slick-carousel').slick({
  slidesToShow: 5,
  responsive: [{
    breakpoint: 1024,
    settings: {
      slidesToShow: 3,
      dots: true
    }
  }, {
    breakpoint: 480,
    settings: {
      slidesToShow: 1
    }
  }]
});

In this example, we’re specifying a responsive array that contains an object for each breakpoint where we want a different behavior. Inside the object we define a breakpoint property. Effectively we are creating javascript media queries, and these allow us to change how the Slick carousel behaves at each breakpoint. In this example i’m saying that above 1024, I want to show 5 slides, at 1024 and below I want to show 3 slides and show dots, and at 480 and below I want to show 1 slide with no dots.

Your responsive control is virtually limitless in this case. You have as much control over how your carousel works as you have over how your CSS does. Every option you’ve specified as the base of your Slick carousel can be configured at the different responsive levels.

Drag on Desktop

Sometimes, even in a Desktop browser, you want to drag between images in a carousel. At the time of writing this, the Flexslider folks aren’t particularly interested in that feature, so if you want desktop dragging between carousel items you’re out of luck with them.

With Slick, it’s enabled by default. This may not seem immediately useful, but there are lots of use cases. For one thing, users used to mobile interaction sometimes bleed that mental model into the browser, expecting things to work similarly between the two. Another example would be where you aren’t creating a carousel for the standard “slide through a bunch of images or text” experience – perhaps your carousel is meant to act like a timeline where users can drag between events. In these cases, you have so many features that work for your use case (forward and next, moving to points in the future or past, fluid transitions and good mobile interaction), and all that might remain to you is the desktop dragging behavior. Slick has you covered.

Lazy Loading

Slick also has some support for out of the box lazy loading. It’s a simple setup, and requires a couple additional configuration options.

<div id="slick-carousel">
  <div><img data-lazy="slide-1.jpg"/></div>
  <div><img data-lazy="slide-2.jpg"/></div>
  <div><img data-lazy="slide-3.jpg"/></div>
</div>
$('#slick-carousel').slick({
  lazyLoad: 'ondemand'
});

Our img tags now have data-lazy data attributes, instead of a src attribute. If you included the src attribute, the image would always load regardless of your intent. This way Slick can pull the attribute out and apply it to src at the appropriate time.

Our Slick initialization now has a lazyLoad option. Supply ‘ondemand’ for it to load the images as you progress through the carousel.

Considering that web page size has been on the rise and 56% of page size tends to come from images – lazy loading is a nice option to have with little to no additional effort.

Digging into Slick

Slick has way more options and features than i’ve mentioned here, so check out the demos it offers for some more impressive functionality. I’ve just offered a few features that i’ve found useful recently – there’s plenty more to try out.

Angular

For the angular inclined, here are some options for Slick and Flexslider.

Slick: https://github.com/vasyabigi/angular-slick

Flexslider: https://github.com/thenikso/angular-flexslider

Conclusion

We want to make websites that work great on all devices. We want to be responsive and capable and we want the interaction to be natural. Working with the Bootstrap Carousel our options are limited (by design) and our mobile interaction is bare. We can do better. With Flexslider and Slick we can create a Carousel experience that feels native and responsive to the user.

Have any of your own suggestions? Have a qualm with Carousels in general? Let me know in the comments.

Better Than Bootstrap Javascript: Loaders

This entry is part 1 of 3 in the series Better Than Bootstrap Javascript

Bootstrap LogoBootstrap is an awesome tool, and something I use all the time. The ability to have so much css scaffolding in place for you to use is a huge time-saver and makes building responsive sites attainable in a more reasonable, repeatable and budget-friendly way.

On top of the CSS functionality, Bootstrap comes with a suite of javascript plugins that solve some common requirements for your UI. Including a modal, popover, carousel, tooltip and loader (among other elements), it really is a handy way to get some dynamic functionality out of the box, and get up and running quickly.

But when you’re such a large framework, and you encompass so many different areas – that means you’re going to be great for some things, and average (or poor) for others. When the parts are taken individually, their flexibility, capability and quality fall short of other tools that are built with only one specific purpose in mind.

When I’m working on a non-Bootstrap project, it’s rare that I would reach for a Bootstrap javascript component to complete a task – there are just better tools suited to specific jobs. Even when working on a Bootstrap project specifically – you might find a plugin lacking in some way, and want to try something else.

This is the first in a series about Bootstrap Javascript components, and some high quality alternatives.

First stop, user action feedback.

Starting small

This first comparison is of a small area of Bootstrap functionality, specifically centered around buttons. In Bootstrap, you can manipulate “states” on a button and give it behaviors outside of the standard button click behavior. They use it, for instance, to create buttons that can behave like checkboxes or radio buttons. In addition, they demonstrate behavior where a button can react to the users click, and provide the user feedback in the form of a “loading” state.

For instance, a user could click a button with the text “Loading state”, and once clicked the button is disabled and its content changed to “Loading…”.

<button type="button" id="myButton" data-loading-text="Loading..." class="btn btn-primary" autocomplete="off">
  Loading state
</button>
$('#myButton').on('click', function () {
  var $btn = $(this).button('loading');
  setTimeout(function () {
    $btn.button('reset')
  }, 2000);
})

In our HTML, we’ve provided a button that has attributes about how to behave when in a “loading” state. data-loading-text provides the value Bootstrap will swap out when we switch to that state, and Bootstrap automatically disabled the button for us until we reset it. We just use the button api to tell it when we want it in a state of “loading”, and when done tell it to “reset”. Resetting it will bring us back to our original state: an enabled button with the text of “Loading state”.

Here’s an example of the concept in action:

See the Pen Bootstrap Loader by JP Camara (@jpcamara) on CodePen.

In practice I’ve used these loading states as an immediate indicator to the user that something has happened. Their action resulted in a process being started. For instance, if the user clicks a button and I make an ajax request, changing the state of the button to loading lets them know that something is going on (rather than sitting their wondering what might be happening, and if something went wrong). Humans can perceive latency in as little as 100 milliseconds (and maybe even less), so giving them that immediate feedback is important.

A more dynamic indication

The ability to add this loading state gives the user immediate feedback, and doesn’t leave them guessing about whether their click registered. But it’s somewhat of a jarring interaction (the button immediately changes to the loading state), and isn’t far beyond what we could do manually ourselves (disabling a button and changing its display text isn’t difficult javascript).

I think we can do better.

Ladda UI

Ladda is a UI concept created by Hakim El Hattab that “merges loading indicators into the action that invoked them”. In our case, that gels nicely with the concept we’ve already been promoting by using a “loading” state on our buttons to give the user immediate feedback. But the Ladda concept takes that a step further, and introduces multiple animated feedback mechanisms centered around the button.

Using the Ladda library from Github, the approach we take here looks similar to the Bootstrap states.

<button class="ladda-button btn btn-primary js-expand-right" data-style="expand-right">
  <span class="ladda-label">Submit Right</span>
</button>
var $expandRight = $('.js-expand-right').ladda();
$expandRight.on('click', function () {
  $expandRight.ladda('start');
  setTimeout(function () {
    $expandRight.ladda('stop');
  }, 2000);
});

Our HTML looks a little different – we’re no longer specifying loader text and we now have a new attribute data-style. The data-style attribute specifies how the button will react when Ladda is enabled – in our case we’re telling it to “expand-right” when the user clicks it. There are several “styles”, including expand-left, expand-right, slide-up, and slide-down, among others (see Hakim’s demo page for all styles available).

In addition, we’ve now split our button and inner text into two pieces: the outer button layer with a class of ladda-button, and the inner span layer with a class of ladda-label.

Our Javascript code is straightforward, and i’m taking advantage of the jQuery plugin Hakim provides to make the setup even simpler. We grab the element using jQuery, apply Ladda to it using the ladda method, and then when clicked simply tell Ladda to start and stop at the appropriate times.

Here is an example in action, also including how to indicate incremental progress as some background action happens.

See the Pen Ladda Loader by JP Camara (@jpcamara) on CodePen.

Perceived Performance

What we’re going for with these two approaches is perceived performance. We haven’t actually improved the performance of our code or our server by including this, but the user feels like their action is progressing faster. Simply clicking on a button with no feedback (except maybe a loading icon in the tab of your browser) leaves the user feeling like things are moving slowly, or are possibly stuck.

Angular

The examples provided here are based on using standard Bootstrap and Ladda. If you’re an angular user and want to try this, here are a couple options

Angular Ladda provides an angular implementation on top of the Ladda plugin from Hakim

This gist provides an example of just creating a directive wrapper you could copy into your own project.

Conclusion

The feedback Ladda offers is more visually appealing and gives a deeper sense of progress than what Bootstrap provides out of the box. Using this approach we can make the user interaction more pleasant and responsive than what we were capable of with Bootstrap alone. I’m interested to know if you agree, or if you have any other alternatives that you’ve used in your work. Let me know in the comments!

Next up, we’re going to take a look at Carousels and what alternatives there are to Bootstrap’s native carousel component.

Selecting carefully with Laravel joins

Laravel comes packaged with an ORM called Eloquent, which is one of the better PHP tools for dealing with your database layer using objects. It provides all of the features you’d expect from a modern relational mapper, and cleanly uses some PHP magic to make the process pleasant.

But it has its quirks, and today i’m setting my sights on a not-uncommon operation – the join.

The tables

Let’s say we have two tables: users and posts. users has an id and a name. posts has an id, name, content and user_id (a foreign key to the users table). Each table has the following data

users 
id | name 
1  | jp 
2  | cosmo

posts 
id | name         | content      | user_id 
18 | jp's post    | hello there! | 1 
22 | cosmo's post | hi there!    | 2

Here are their definitions in Eloquent

class User extends Eloquent {
  protected $fillable = ['name'];
  public function posts()
  {
    return $this->hasMany('Post');
  }
}

class Post extends Eloquent {
  protected $fillable = ['name', 'content', 'user_id'];
}

With this definition, we can retrieve the first user easily, and the results are what we’d expect

$user = User::first();
print $user->id;   //prints 1
print $user->name; //prints "jp"

Where it gets tricky

Retrieving a User object directly is nice, but many times when dealing with the database you’ll be issuing joins to retrieve your data. A join is fairly simple in Eloquent

$user = 
  User
    ::join('posts', 'posts.user_id', '=', 'users.id')
    ->where('posts.name', 'LIKE', '%jp%')
    ->first(); 

The join takes a table name, and then the pieces of the join clause. In this case we’re joining on the relationship between the posts.user_id and the users.id. A little bit clunky, but usable.

What isn’t usable, are the results.

print $user->id;   //prints 18
print $user->name; //prints "jp's post"

The object looks the same, but we’re getting what seems to be invalid results. When we ran it before, we printed an id of 1 and a name of “jp” – now we’re seeing an id of 18, which isn’t even available in the users table at all. And the name “jp’s post” is the from the posts table. What’s going wrong?

Under the hood

By default when Eloquent issues a query, it selects all columns

User::all(); //SELECT * FROM users

When you perform a join, it continues issuing the same select call, additionally adding the join and where clauses. So our join from earlier results in the following query

SELECT * 
FROM users 
INNER JOIN posts ON users.id = posts.user_id 
WHERE posts.name LIKE '%jp%' 

The result is a row with two id and name columns. Raw sample output from a database tool would look something like this

id | name | id | name      | content      | user_id
1  | jp   | 18 | jp's post | hello there! | 1

This means that when Eloquent parses the results into the User object, it’s contending with two versions of the same column name. Most likely it’s using a hash internally, and the second key overrides the first. The result is a User object with the id and name of the related Post.

Fixing the issue

The solution turns out to be very simple. You have to be specific with your select clause.


$user = 
  User
    ::join('posts', 'posts.user_id', '=', 'users.id')
    ->where('posts.name', 'LIKE', '%jp%')
    ->select('users.*')
    ->first(); 

Now our select is specifically selecting columns from the users table only, and our results are consistent with our expectations again

print $user->id;   //prints 1
print $user->name; //prints "jp"

How Rails does it

One reason this tripped me up in the first place, is coming to Laravel from Ruby on Rails. In Ruby on Rails, this problem is taken care of for you.

User.joins(:posts).where(name: '%jp%').first
SELECT users.* 
FROM users 
INNER JOIN posts ON users.id = posts.user_id
WHERE name LIKE '%jp%'

I assumed a similar behavior in Laravel without ever checking the results. Personally I think the Rails behavior is the more sensible default, since it keeps your class mapping directly to your table (unless you explicitly tell it otherwise using #select).

Why not use #with?

For people used to using eloquent, it may be suggested to instead use the #with method. Using #with does technically fix the select issue, but the use case it solves and queries it generates aren’t the same.

#with allows you to work around the N + 1 problem and also can give some form of filtering. To achieve a similar affect to the join clause using #with

User::with(['posts' => function ($query)
{
  $query->where('name', 'LIKE', '%jp%');
}])->first();

Using #with you might expect a similar result to the join, but the queries generated work differently.

SELECT * FROM users
SELECT * FROM posts WHERE posts.user_id IN (1) AND name LIKE '%jp%'

#with generates two queries, so if you’re trying to perform an operation on the data with one call, it’s not the way to go. It first fully retrieves the users table information, then uses that to construct a query on the posts table. It’s less efficient and may not always be accurate.

Also – it’s up for debate, but I find that adding a where clause to a #with method is more complicated to read.

Conclusion

The way joins work in Eloquent has bitten me a few times, and it teaches you to be careful about making assumptions when moving around between frameworks and abstraction layers. Laravel feels right at home when you’re used to using other systems like Rails, but truly understanding the framework you’re using and implications its tools have is important to making sure mistakes like this don’t slip through.

Using Famo.us with the Ionic Framework

ionic_famous

Ionic and Famo.us are Javascript frameworks that aim to bridge the gap between the web and native app world, so that web technologies can compete with the native experience.

Ionic

Ionic is focused on on creating beautiful hybrid mobile apps in HTML/CSS, and their ecosystem, tooling and library provide a great experience that allows web developers to leverage their skills quickly and effectively in the mobile app space. But despite the cohesive and rich experience they can provide, extending their framework solely relies on the use of HTML5 and CSS3 – without their internal focus on performance and native feel, components you extend it with may not be the same quality or seamlessness as what the Ionic team can provide.

Famo.us

Famo.us is a framework obsessively concerned with making the browser interactive UI experience fluid, effortless, and fast. They haven’t provided the same kind of ecosystem and tooling that Ionic has (yet), but their competitive edge is definitely in the power their layout engine provides. Where Ionic has lots of built-in, native feeling components, Famo.us instead provides all of the tools you need to build a native feel yourself on a foundation that is designed to perform. They’ve worried about what makes the browser experience as fluid as possible, so if you manipulate it through their API, you don’t have to.

Working together

Most articles you see only want to compare the two and claim which is ‘better’. I think a more interesting and beneficial path is to see if we can use the two to play off each other: Use Ionic to scaffold your applications and easily achieve a native theme and feel, while using Famo.us to power more complex interactions that Ionic doesn’t provide an easy capability for.

Getting Setup

For this tutorial, we’re going to use the Ionic Beta 14 framework/tooling, and Famo.us 0.3.2. Since Ionic is an AngularJS project, we’ll use the Famo.us/Angular project which provides easy-to-use directives for controlling Famo.us from your HTML views.

To install the ionic tools, you’ll need npm. We’re also going to throw in bower for installing famo.us.

Now that we have the ionic cli installed, we’ll use one of their starter templates as the base of our project. The sidemenu template provides a sliding side menu with routing and a modal example.

You can run ionic serve to make sure everything installed correctly, and have a live-reloadable version of your code running in the browser.

Now to install famo.us and the angular integration, and save it to our bower.json file

If asked which angular version to choose, choose from the 1.3.x releases.

In your www/index.html file, add in references to the famous code you installed with bower.

Go into www/js/app.js, and add famous.angular as a dependency.

Now we’re ready to embed Famo.us content into our views. For this example, all we will do is embed a Famo.us Surface, which is the most basic piece of renderable content in the Famo.us layout engine.

Go into www/templates/playlists.html, and replace the entire content with this

What we’ve done here is setup one of the simplest Famo.us examples you can create. Each snippet of Famo.us content you display using their angular integration begins with the fa-app directive.

To display any actual content to the screen, it must be wrapped in a Surface. Using the fa-surface directive makes that very easy to do, and in our example simply contains a small snippet of text which will be rendered in the browser.

Following these steps, you should have an embedded Famo.us surface in your Ionic app!

Ionic Famous Example

Conclusion

This hardly scratches the surface of what could be possible in using these two frameworks together, and i’ll be exploring each individually and combined in future posts. For now, head over to my Famo.us/Ionic Demo project on Github to get a fully working version of what you’ve read here with some additional examples. Feel free to comment if you have any suggestions or thoughts on what an Ionic/Famo.us combination could mean for you!