Categories
JavaScript WordPress

First Steps with Javascript and WordPress

It starts with a simple maxim.

Learn Javascript Deeply.

That’s what Matt said. And it’s good advice. Javascript underpins everything we do, and it’s becoming more and more advanced every day. It’s not just the future of WordPress, it’s the future (and present) of the web.

Of course, Matt mentioned this right around the time he showed off a new admin dashboard written entirely in client-side Javascript with React, and proxied through a server also written in Javascript. Which is great for WordPress. But it’s not a great place for everyone to start.

The truth is there are a number of ways to start using Javascript that are a little more… approachable. My goal here is to go through a few ways you can start using Javascript, today, without completely changing your workflow.

I will be talking about a lot of things. There will be code. I won’t be diving too deep into any one thing. My hope is that I can spark some interest for you. That you connect with one of these new processes or patterns and you feel encouraged enough to keep digging.

Generally speaking, I think there are three great ways to approach Javascript.

  • Using Javascript to manage a front-end build process
  • Managing events, page transitions and AJAX with a watchful eye
  • Building a full-scale Single Page Application with the WordPress REST API.

I want to talk about that last bit a lot more in the future. But for now, I’m mostly going to focus on the first two.

Javascript Build Tools

If you develop front-end code in your plugins or themes, you’ve probably noticed yourself doing the same things over and over. Things like compiling SASS down to CSS, concatenating JS files together and minifying them, creating SVG or icon fonts, linting your code for errors, the list goes on You might have even heard of some nifty tools out there like CodeKit or Prepross that can do this for you. But there’s another way you can do this. With Javascript.

Javascript build tools allow you to create basic script files that will automatically perform these tasks for you, with a little help from Node on the command line. Build tools are a great way to learn Javascript because the barrier to entry and the risk factor can’t be lower. If you screw up, it won’t effect your live site. You’ll just have to track down the error and try again.

These build tools typically run on top of Node, which is why you’re able to run it from your machine. And there are a lot of them out there. I’m just going to focus on two: Grunt and Gulp.

Since both use Node, they follow the same basic procedure.

  1. Install NodeJS, either from the site or with a tool like Homebrew
  2. Navigate to your theme or plugin folder in your Terminal and type one command: npm init. This will automatically create a file called package.json. This stores a list of dependencies that the build tool will need to work. But don’t worry, you won’t be editing this file directly.
  3. The way you do add packages is with npm install PACKAGENAME --save-dev. These packages will automatically get added to your package.json file for future use.
  4. Create a Gruntfile or Gulpfile (depending on your preference)

I’ll start with Grunt. Grunt works by creating basic Javascript objects, which you use to pass in configurations for modules. There’s not a whole lot too it, but you can chain them together to do some pretty great stuff. For instance, if we wanted to concatenate our JS files and compile SASS files, we would install packages with npm install grunt-contrib-concat grunt-contrib-sass --save-dev. Then we would set up our Javascript in a file called Gruntfile.js.

Gruntfile.js
module.exports = function (grunt) {
  grunt.initConfig({
    concat: {
      dist: {
        src: [
          '/assets/scripts/vendor/*.js',
          '/assets/scripts/*.js'
        ],
        dest: '/js/app.js',
      }
    },
    sass: {
      all: {
        options: {
          style: 'compressed'
        },
        files: {
          'style.css': '/assets/styles/style.scss'
        },
      }
    },
  });
}
grunt.registerTask('styles', ['sass'])
grunt.registerTask('default', [sass', 'concat', 'uglify', 'watch']);

One thing that you’ll learn about in Javascript is that just about everything is an object. That means that inside of these objects you can run any Javascript you want. So you can take grunt files, put them next to vanilla Javascript functions or variables and build anything. The possibilities are really endless.

Gulp is similar, with a few small differences. It works by chaining together tasks, one after another. It also uses CommonJS, so if you’re looking to learn more about Javascript modules and how to link together small packages, it may be a good starting point. To run the same tasks we have in the Grunt example, we just install our packages with npm install gulp-sass gulp-concat --save-dev, and then add our Gulpfile.js.

Gulpfile.js
var gulp           = require('gulp'),
    concat         = require('gulp-concat'),
    sass           = require('gulp-sass');
gulp.task('scripts', function() {
    return gulp.src('./assets/js/app/**/*.js;)
            .pipe(concat('scripts.js'))
            .pipe(gulp.dest('./assets/js/'))
            .pipe(rename({ extname: '.min.js' }))
            .pipe(gulp.dest('./assets/js/'));
});
gulp.task('sass', function () {
    return gulp.src(‘./assets/
                     styles/style.scss')
            .pipe(sass.sync({
          outputStyle: ‘compressed'})
          .on('error', sass.logError))
            .pipe(gulp.dest('./'));
});
gulp.task('default', ['scripts', 'sass']);

Interested?

Organizing Javascript

But you can do even more with Javascript. It turns out that a lot can be learned simply from structuring your Javascript better.

If you’ve been coding up themes or plugins for a while, chances are you’ve written some jQuery. You know, click this button to show a dropdown type stuff. And you’ve probably written out code that looks like this:


$('.btn-thing').on('click', function(e) {
    // Do your stuff
});

But there’s a better way. Learn yourself a few basic Javascript patterns to manage your events, and you’ll find yourself writing reusable code over and over.

The Module Pattern

The module pattern can be a great way to organize events like clicks, input changes, or other basic jQuery binded events. Remember how I said everything in Javascript is an object? Well the Module pattern uses this as an advantage. You basically store all of your events in a single object, decoupling your elements from the functions that is called when an event occurs. This is probably easiest to explain with some code:

The Module Pattern
var Module = {
    el : {
        $wrapper : $('#wrapper'),
        $button : $('.btn')
    },

    init : function() {
        this.bindUIActions();
    },

    bindUIActions : function() {
        Module.el.$button.on('click', 'onClickEvent');
        Module.el.$wrapper.each(function() {
            Module.doSomethingWithList($(this))
        })
    },

    onClickEvent : function(e) {
        // Do Something
    },

    doSomethingWithList : function(item) {
        // Do something with the item el
    }

}

Elements are stored in the “el” objects, events are controlled from the init function, which then passes the buck down to individual functions. Writing code like this makes things a lot easier to read, and it can make your job easier.

The Inheritance Pattern

If you wanted to take this a step further, the Inheritance pattern may do the trick. It starts out the same way, you build a simple object which sets up some basic functionality. But you also include a way to extend that object, so you can pass it a few options that will change functionality.

This is most commonly seen in jQuery plugins, but there’s no reason why you can’t start doing this today. That way, you don’t have to keep writing the same functionality over and over again. Instead you write it once, and then just pass an object a few options to change little things here and there. Then your code becomes a reusable module.

The Inheritance Pattern
var Object = {
  init: function( options, el ) {
    this.options = $.extend( {}, this.options, 
                    options );

    this.el  = el;
    this.$el = $(el);

    this.init();

    return this;
  },
  options: {
    option1: "default"
  },
  init: function(){
    // Do something with messages
  },
  myMethod: function( msg ){
    // this.$el or this.options is accessible
  }
};
// Basic create / extend of object for browser support
if ( typeof Object.create !== 'function' ) {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}


// Create a plugin based on a defined object
$.inherit = function( name, object ) {
  $.fn[name] = function( options ) {
    return this.each(function() {
      if ( ! $.data( this, name ) ) {
        $.data( this, name, Object.create(object).init( 
        options, this ) );
      }
    });
  };
};
$.inherit('inheritedObject', Object);('#elem').inheritedObject({option1: "Different"});

There are really two things to pay attention to here. The $.extend({}) function is what extracts options out to use within the main object. And the $.inherit() function is what will pass options back up to the Object when something is called.

Interested?

Managing AJAX and Page Transitions

AJAX stands for Asynchronous Javascript and XML. In practice, it means fetching chunks of HTML or data using Javascript and loading it into a page without a page refresh. Coupled with some new HTML5 features and Javascript libraries, AJAX can really add to your site. It can make screens transition from one to the next, as a user navigates seamlessly around your site.

There are lots of ways to manage AJAX in WordPress. But the way I prefer is to organize the server-side code into a single Class and then use the module pattern to interpret the requests. Rather then try to explain that all here, I’ll let Jay Wood over at WebDev Studios do it for me. Really, click that link. It’s a great article.

I will, however, mention two Javascript libraries of interest: smoothState.js and pjax.

Both libraries automatically fetch pages when a user clicks on any links and loads the content in. smoothState puts more of an emphasis on the transitions between pages, using CSS3 transitions and basic class switching to do most of the work. To set it up you just need a simple object.

smoothState
(function ($) {
  'use strict';
  var content  = $('#main').smoothState({
        onStart : {
          
          duration: 250,
          
          render: function () {
            content.toggleAnimationClass('is-exiting');
          }
        }
      }).data('smoothState');
})(jQuery);

pjax is even simpler to get started with, but can do a bit more if you dive in. To automatically start pulling in content without a page refresh you just need to load the code and write one line of Javascript.

$(document).pjax('a', '#pjax-container');

But there’s a lot more that can be done. Exploring the library and employing some of the patterns talked about earlier can go a long way. But check out the links below for some great implementations.

Interested?

The REST API and Beyond

The big news for WordPress this year was the REST API. Again, this isn’t the time to go too deep into this, but basically the REST API allows you to access your site’s content as basic data JSON objects. These data objects can be read by frameworks like Backbone, Angular and React to process content completely on the client-side (on the browser). This allows you to build more complex web applications instead of just sites. Think Gmail. Or Facebook.

And that’s just scratching the surface of the REST API. It can also be used to connect to third party platforms and services, and even more importantly I think, get sites talking to each other. Which is really cool. And will almost certainly require some Javascript. So roll up your sleeves, find your entry point, and get going.

Interested?

Just Keep Learning

I’m hoping I peeked your interest somewhere. I’m hoping you’re ready to learn Javascript and have some resources to get started with. The trick is to start somewhere, get familiar and keep the ball rolling.

Categories
Development JavaScript WordPress

Gulp, LiveReload, SASS and WordPress

For a little while now, I’ve been using Gulp in my WordPress themes to automate my front-end workflow and add some handy helpers along the way. For those unaware, Gulp is a slick JavaScript task runner, which can be used to concatenate JS and CSS files, lint files, and generally automate your front-end workflow.

My goal was to write a short introduction to how this works. It ended up kind of long. But by the end you’ll be compiling SASS, minifying Javascript, working with livereload and implementing a SVG icon system. So not bad.

Setting Things Up

First off, gulp runs on top of NodeJS, and is generally operated from the command line. If you’re not set up with Node yet, I’d recommend following the steps on their website (or better yet, installing Homebrew).

With Node installed, you can install gulp globally on your system by opening up your Terminal and running:

npm install -g gulp

This will ensure that you can use the gulp command from the command line. In the root directory of your theme file, you will also need to install and set up a local version of gulp, and add a package.json file to manage your dependencies. This is basically just a config file that Node uses to figure out which packages it needs to bring down and install (things like a SASS concatenate or a JavaScript linter or any number of other tools). To create this file, just navigate to your theme’s directory in the terminal and run:

npm init

This will step you through the process of creating a package.json file. When that’s finished, the last step is to install gulp locally to your WordPress theme folder.

npm install gulp --save-dev

That last flag, --save-dev will automatically save this to a list of dependencies in your package.json file, so you can easily pass the directory around. But more on that later.

More info at CSS-Tricks.

Folder Structure

I just want to quickly note my folder structure. You’ll notice that a lot of my decisions in gulp are dependent on this, but they can easily be changed. My theme folder looks like this:

screen-of-files

 

In the root directory, we’ve already created the package.json file, and we’ll create the gulpfile.js in just a minute. The other important folder is assets which includes all of my front-end files.

  • assets/js/app – Contains all of my custom Javascript files, which gulp will combine
  • assets/js/vendor – Contains any vendor Javascript files, things like Bootstrap and Modernizr
  • assets/sass/style.scss – My main SASS file, which contains imports for all the other sass files
  • assets/sass/ – All the other SASS files
  • assets/svg/individual – Contains any SVG files I would like to use in my SVG icon system

Hopefully this will be a bit more clear as we step through.

From here, it’s just a matter of installing the packages we need, and creating a gulp task for each one.

Getting Started with SASS

Ok, let’s start out with the SASS setup. The first thing we’ll need to do is install gulp-sass, a library which will compile SASS down into plain old CSS.

npm install gulp-sass --save-dev

With that, we can finally start setting up Gulp. Create a new file in the root directory titled gulpfile.js and at the very top add:

Gulpfile.js
var gulp     = require('gulp'),
    sass    = require('gulp-sass');

Gulp uses the require syntax in order to import dependencies, so all we are doing here is ensuring that the gulp and gulp-sass library are loaded into variables.

Gulp works in what’s known as tasks. Each task performs a simple operation, passing files through and spitting them out in a different format on the other end. We’ll call our first task sass, which will handle the process of processing the style.scss file located in the assets/sass directory of our theme.

Gulpfile.js
gulp.task('sass', function () {
    return gulp.src('./assets/sass/style.scss')
            .pipe(sass.sync({outputStyle: 'compressed'}).on('error', sass.logError))
            .pipe(gulp.dest('./'));
});

Pretty simple actually. We give the initial task a source, and then use pipe, a built in connector for tasks to process sass. You’ll notice on line 3 that we’re actually calling the sass variable in order to process our file. Now, if we run gulp sass in the terminal, a new CSS file will be generated in the root directory of our theme. So far, so good.

Concatenating and Minifying Javascript

In a typical theme, I have two sets of Javascript files. The first are vendor files, and the other are my custom files. As seen above, I keep these in two separate folders helps to manage them better, and later on, I use gulp to combine them all together.

One thing I’ve run into over and over again is loading order for Javascript. If you’re using modules, you may not have to worry about this, but I’ve found that rather then trying weird naming conventions or separating files, I’ve opted to simply list out my Javascript files in the order I would like them to load. That way, gulp will process them one by one and spit them out into one big file. I know there are other methods, but this has worked best for me.

We’ll need to install a few other packages to get this up and running.

npm install gulp-concat gulp-uglify gulp-rename --save-dev

Gulp-concat will combine all of our Javascript files into one big file, gulp-ugilfy will minify them, compressing the file and saving us precious kilobytes, and gulp-rename will allow us to call this outputted file whatever we would like. Once again, at the top of our gulpfile we need to define the packages we just installed.

Gulpfile.js
var concat   = require('gulp-concat'),
    uglify  = require('gulp-uglify'),
   rename   = require('gulp-rename');

Next, we will create a config variable that defines all of the Javascript files we want to concat. This variable will be used by gulp to process the files in order. If you simply want to include all the files from a directory, you can use the /**/*.js syntax, as we will do for our app folder.

Gulpfile.js
var config = {
    scripts: [
                // Bootstrap
        './assets/js/vendor/bootstrap.js',
        // Modernizr
        './assets/js/vendor/modernizr/modernizr.shiv.js',
        // SVG Fallback
        './assets/js/vendor/svg/svg-fallback.js',
        // Any Custom Scripts
        './assets/js/app/**/*.js'
    ]
};

With that all set up, we can add a new task called scripts, which will run the files through concat and uglify and output the file:

Gulpfile.js
gulp.task('scripts', function() {
    return gulp.src(config.scripts)
            .pipe(concat('scripts.js'))
            .pipe(gulp.dest('./assets/js/'))
            .pipe(uglify())
            .pipe(rename({ extname: '.min.js' }))
            .pipe(gulp.dest('./assets/js/'));
});

This time for our source, we pass the variable we creaed, which has an array of the files we want to concat. This will output a file called scripts.js in our assets/js folder. Then uglify will compress this file even further, and output it as scripts.min.js. This will be our production-ready file. However, the scripts.js file can come in handy when debugging your theme.

If you want to see this in action, simply run gulp scripts.

SVG Icons

I won’t go too far into why I prefer SVG icons over any other systems, but if you want a lengthy introduction on how they work, CSS Tricks has a great tutorial. If you find yourself convinced, like I did, just make sure to save all of the individual SVG files you want to use in the assets/svg/individual folder. We will then use the gulp-svg-sprite and gulp-svg2png libraries to automatically create an SVG sprite and image fallbacks of our icons to easily use in our theme.

First step, install the two libraries we will need.

npm install gulp-svg-sprite gulp-svg2png --save-dev

Next, we’ll define our npm packages at the top of our gulpfile.

Gulpfile.js
var svgSprite    = require("gulp-svg-sprite"),
    svg2png     = require('gulp-svg2png');

Now it’s time to set up our SVG icon tasks. I’ve actually broken this up in my gulpfile into two tasks. The first creates the SVG sprite, which we can embed in our theme, and the second creates PNG fallbacks for our icons. The first we’ll call sprites:

Gulpfile.js
gulp.task('sprites', function () {
    return gulp.src('**/*.svg', {cwd: './assets/svg/individual'})
            .pipe(svgSprite({ shape: { transform: ['svgo'] }, mode: { defs: {dest: '.'} } } ) )
            .pipe(gulp.dest('./assets/svg/'));
});

As our source, we are simply looking in the ‘assets/svg/individual’ folder for anything with an .svg extension, and then processing it using the svg-sprite library. You will notice that I passed an svgo transformation, which will automatically optimize the SVG files. The final sprite will be saved to assets/svg as sprites.defs.svg. From there, you can follow the article linked above for how to include this in your theme.

Next up is the SVG fallbacks. For these fallbacks, I use a script from Luke Whitehouse. I had to modify it a bit to point to the proper URL (MyTheme + /assets/svg/png/”), but it works fairly well. You may also want to consider a library like SVG For Everybody. But in order for either method to work, they will need PNG images to fall back to. So we’ll create a gulp task that simply runs through our SVG files, converts them to PNG, and drops them in our assets/svg/png folder.

Gulpfile.js
gulp.task('svg2png', function () {
    return gulp.src('./assets/svg/individual/**/*.svg')
            .pipe(svg2png())
            .pipe(gulp.dest('./assets/svg/pngs/'));
});

This uses the gulp-svg2png library we installed to convert our SVG files on the fly.

Gulp tasks do not simply have to be one-off scripts. In fact, they can simply be an array of tasks to perform, in order. For our SVG workflow to be complete, we’ll want to combine the two tasks we created into a single task called icons. All we need to do is pass the names of these two tasks to a new one.

Gulpfile.js
gulp.task('icons', ['sprites', 'svg2png']);

Now, if you run gulp icons you will see this workflow in action.

Bonus Round: LiveReload

Livereload is an incredible library that can be used to automatically reload your site whenever changes are made. That way you don’t have to do the annoying Ctrl / CMD + R, check changes, switch to editor dance. And for CSS files, it will even inject styles on the fly, with no refresh needed. So you will see your styles change instantly.

The first step is to install the gulp-livereload library.

npm install gulp-livereload --save-dev

Next, we need to make sure that the livereload script is actually running on our site. H/T to Rob & Lauren for pointing me in the right direction with this one. We can add this to the functions.php file in our theme, automatically enqueueing the script on local environments.

functions.php
if (in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1'))) {
  wp_register_script('livereload', 'http://localhost:35729/livereload.js?snipver=1', null, false, true);
  wp_enqueue_script('livereload');
}

 

With that added, we can go back our gulpfile.js file. At the top, make sure to define your dependency in a new variable.

Gulpfile.js
var livereload      = require('gulp-livereload');

Next we can add the livereload function to our SASS and JS tasks. This will call livereload at the appropriate times so that your development site is reloaded automatically in the browser whenever one of these tasks is called. So our SASS task will now be:

Gulpfile.js
gulp.task('sass', function () {
    return gulp.src('./assets/sass/style.scss')
            .pipe(sass.sync({outputStyle: 'compressed'}).on('error', sass.logError))
            .pipe(livereload())
            .pipe(gulp.dest('./'));
});

And our scripts task will now be:

Gulpfile.js
gulp.task('scripts', function() {
    return gulp.src(config.scripts)
            .pipe(concat('scripts.js'))
            .pipe(gulp.dest('./assets/js/'))
            .pipe(uglify())
            .pipe(rename({ extname: '.min.js' }))
            .pipe(livereload())
            .pipe(gulp.dest('./assets/js/'));
});

Wrapping It Up With Watch

The last thing we will want to do is use Gulp’s built-in watch feature to automatically watch for any changes to files and call the appropriate task when needed. So, if a SASS file is changed, the SASS task will be called, and if a JS file is changed then the scripts task will be called. We can also set up livereload here so that everything is wired up.

Gulpfile.js
gulp.task('watch', function () {
    livereload.listen(35729);
    gulp.watch('**/*.php').on('change', function(file) {
          livereload.changed(file.path);
      });
    gulp.watch('./assets/sass/**/*.scss', ['sass']);
    gulp.watch('./assets/js/**/*.js', ['scripts']);
});

 

Now all we have to do is add a default task which combines everything from before, calling each of our tasks and ending in watch.

Gulpfile.js
gulp.task('default', ['icons', 'sass', 'scripts', 'watch']);

And that’s that! All we have to do is run gulp and our tasks will be called in order and livereloading will begin. Try changing around some SASS or Javascript files and see what happens.

This is by no means an entirely exhaustive workflow, but it’s more then enough to get started. The trick is to understand how it works, and play around with it when you can. If you want to see what the full gulpfile looks like, well, here it is:

Full Gulpfile.js
var     gulp           = require('gulp'),
    concat         = require('gulp-concat'),
    uglify         = require('gulp-uglify'),
    rename         = require('gulp-rename'),
    sass           = require('gulp-sass'),
    livereload      = require('gulp-livereload'),
    svgSprite     = require("gulp-svg-sprite"),
    svg2png     = require('gulp-svg2png');

var config = {
    scripts: [
        './assets/js/vendor/bootstrap/bootstrap.min.js',
        // Modernizr
        './assets/js/vendor/modernizr/modernizr.shiv.js',
        // SVG Fallback
        './assets/js/vendor/svg/svg_fallback.js',
        // Any Custom Scripts
        './assets/js/app/**/*.js'
    ]
};

gulp.task('scripts', function() {
    return gulp.src(config.scripts)
            .pipe(concat('scripts.js'))
            .pipe(gulp.dest('./assets/js/'))
            .pipe(uglify())
            .pipe(rename({ extname: '.min.js' }))
            .pipe(livereload())
            .pipe(gulp.dest('./assets/js/'));
});

gulp.task('sass', function () {
    return gulp.src('./assets/sass/style.scss')
            .pipe(sass.sync({outputStyle: 'compressed'}).on('error', sass.logError))
            .pipe(livereload())
            .pipe(gulp.dest('./'));
});

gulp.task('sprites', function () {
    return gulp.src('**/*.svg', {cwd: './assets/svg/individual'})
            .pipe(svgSprite({ shape: { transform: ['svgo'] }, mode: { defs: {dest: '.'} } } ) )
            .pipe(gulp.dest('./assets/svg/'));
});

gulp.task('svg2png', function () {
    return gulp.src('./assets/svg/individual/**/*.svg')
            .pipe(svg2png())
            .pipe(gulp.dest('./assets/svg/pngs/'));
});

gulp.task('icons', ['sprites', 'svg2png']);

gulp.task('watch', function () {
    livereload.listen(35729);
    gulp.watch('**/*.php').on('change', function(file) {
          livereload.changed(file.path);
      });
    gulp.watch('./assets/sass/**/*.scss', ['sass']);
    gulp.watch('./assets/js/**/*.js', ['scripts']);
});

gulp.task('default', ['icons', 'sass', 'scripts', 'watch']);
Categories
Inspiration

Adam Phillips on Missing Out

We refer to them as our unlived lives because somewhere we believe that they were open to us; but for some reason – and we might spend a great deal of our lived lives trying to find and give the reason – they were not possible. And what was not possible all too easily becomes the story of our lives. Indeed, our lived lives might become a protracted mourning for, or an endless tantrum about, the lives we were unable to live. But the exemptions we suffer, whether forced or chosen, make us who we are.

Adam Phillips, Missing Out

Categories
Links Thoughts

Bringing Back the Personal Site

There have been quite a few articles recently about the importance of the personal site, and the blogging community. It’s a sentiment I’m super excited about.

Rian Van Der Merwe has probably the simplest point. Blogs are the front page of the internet, and it’s their freedom that gives them their strength.

All this to say that I think it’s time we bring blogging and personal sites back. Some of my favorite sites are the ones that give me a glimpse into everything a person is interested in… It’s a way to get to know someone through their interests, and to learn a bunch of things along the way. So I invite you not just to follow along here as I expand into topics beyond design and technology, but to start your own personal blog up again if you’ve been neglecting it for a while.

Tom McFarlin pointed out that a personal site was a great way to ensure that you own your own data, so that it can outlive and outgrow the third party, walled gardens we’re all used to.

Imagine being able to continue sharing information, but also continuing to own all of the information for yourself by simultaneously bringing it back into a database into an area you own.

Pretty exciting, right? At least for those of us who are tin foil hat types.

Reacting to Twitter’s plan to keep long form content on their own site, Mandy Brown discussed the magic of the hyperlink and the journey that is the open web.

In addition to places to talk… they have also been places to venture off from—you start in your feed, but you end up in a browser, half a dozen clicks away. If everything comes to your feed instead, will you never leave? Will this be like working in one of those startup buildings with their own coffee houses and cafeterias and laundry services, where the streets outside could flood and you wouldn’t notice for days?

Then, Dave Wisner lashed out at Medium, but I think more importantly, talked about the opportunities for a new blogosphere, one that is more connected then ever, (and that the WordPress REST API can certainly play a part in).

But there is another approach, to have WordPress accept as input, the URL of a JSON file containing the source code for a post, and then do its rendering exactly as if that post had been written using WordPress’s editor. That would give us exactly what we need to have the best of all worlds. Widespread syndication and control over our own writing and archive.

As a bit of a retort in The State of the Casual Blogger, Ghost founder John O’nolan was quick to point out that people use services like Medium because they’re easy, fun and simple. And, hey, maybe we should try that, but at the end of the day both will continue to exist side by side:

There is more than enough room in the publishing industry for open and closed platforms to exist in harmony, catering to different types of writers with their individual advantages.

In 2016, I want to start writing again, and sharing things as I come across them. I always want to work on tools that can help personal websites become a central hub for all of our data and content that’s currently distributed all around the internet. Looking around, I guess I’m not alone.

Categories
Thoughts WordPress

The Responsibility a WordPress User

Last week, WP Tavern posted an article about how Matt Mullwenweg was addressing concerns over WordPress development moving too quickly. Matt more or less shrugged the question off in his State of the Word, but it is still a rising sentiment. And it’s not just a concern in the WordPress community, but in the larger web community as well.

There was a lengthy discussion that followed the post. It’s worth a read if you’re into that kind of thing, but to me, it highlights a growing divide that gets right down to the core of what’s expected of a WordPress user. 

Several users noted that even small changes can ripple out to larger ones or break expectations without even a remote need. Similarly, users don’t have the time or capacity to keep up with every little development and when things change they have to go through and check the changes against all of their sites and client sites, then update tutorials, then let their clients know. Every. single. time.

Others, including a handful of core committers, pointed out (rightfully so) that even small changes are heavily considered, and that they often solicit feedback about these things on places like WP Tavern and mailing lists.

The response was that these where places developers and coders hang out and WordPress users can’t be expected to check every little thing. But of course, if a site is code to WordPress conventions, it shouldn’t break anyway. And so maybe we all need to just trust WordPress a bit more.

And so on.

I’m (over)generalizing. But time and time again, we see mention of two groups. The first are the end users, the Average Joe with a laptop and a dream. The second are the developers, programmers on the bleeding edge of web applications. So really, the conversation comes down to what is the responsibility of the WordPress user? Is it the user’s job to ensure that their site is up to date, or it WordPress’ job to ensure that nothing ever breaks on existing sites? That’s a trick question, but it’s part of a continuing identity crisis in the WordPress community.

At this point, WordPress is trying to handle two pretty distinct use-cases. For the end users, a better admin experience, a fast install, and a quality controlled theme and plugin marketplace are of utmost importance. For the coder, extendability, speed of updates, and frankly, a trendy toolset are held in highest esteem. The article’s discussion focused on finding a balance and a place to draw the line between these two groups. The central theme being:

How can we maintain a strong pace of development with new features, while still leaving things simple (and relatively unchanged) and for the average user?

Wrong question. To pit two user types against one another implies some sort of mutual exclusion. It obfuscates the nature of the web and website development. And it puts the community at odds with one another.

Think about some of the things that WordPress does well out of the box. User authentication, media management, commenting, routing, and a pretty well thought out admin interface to boot. None of these components are good for just one group. In fact, a lot of the differences between these groups is just about how we want to render HTML on a page. But it’s the open web all the way down.

Let’s stop defining the “average” WordPress user. Let’s work on ways to elevate the WordPress user instead of insulting their intelligence at every turn. Let’s drop the assumption that these users don’t have the will or interest to learn more about how their site comes together. We don’t need to speak in techno-babble or build confusing interfaces. We can use the WordPress admin and site building process as teachable moments, to educate users on the types of things they can do. We can find better ways to reach out to everybody that uses WordPress and gather feedback. The WordPress core community is already working on this, and of course, they could always use some help.

We make it sound as if the REST API is only useful for NodeJS wielding front-end developers. What about the user that wants to use it to wire WordPress to Facebook, or connect to a third-party app, but doesn’t know how? WordPress just brought responsive image potential to 25% of the web. That’s a win for everybody. We have whole teams working on accessibility and localization. There’s no one group that benefits from any of the work that’s done.

As WordPress continues to grow, it will be its diversity of spirit and community that keep it alive. Take a look around at the next WordPress event that you’re at and note the multitude of voices and opinions. Remember that the role of the WordPress user is to make websites, and love doing it. We should encourage that.

Categories
JavaScript Links

The Magpie Developer

Jeff Atwood wrote this article seven years ago but it holds true:

These so-called thought leaders have left a virtual ghost town before anyone else had a chance to arrive.

I became a programmer because I love computers, and to love computers, you must love change. And I do. But I think the magpie developer sometimes loves change to the detriment of his own craft.

This seems as relevant as ever. As a developer in the Javascript world, it’s hard to keep up. Sometimes, I feel like I’ve done more “Hello World’s” then real projects. Small side projects help, but I’ve found the trick is to learn the basics of something, then log it in the back of your head (or write it down somewhere) for future use.

Side note, it’s disturbing how many links in this article are 404’ed these days. We need to all do something about that.

Categories
JavaScript WordPress

Leveling Up in JavaScript for WordPress Developers

Or How I Learned JavaScript.

When I started building websites, I used Notepad, and wrote pages in plain HTML and a little CSS. After a couple of years giving that a go, I moved to WordPress, and found out all about web standards. I’ve certainly written my fair share of PHP, but my primary skill set is the front-end. I was never trained in computer science, and programming has been a slowly acquired skills. Only in the last few years have I truly become serious about JavaScript development. In that time, I’ve picked up a few resources that I wish somebody had told me about when I first started out. Hopefully, a couple of these will help.

The JavaScript / jQuery debate

I’ll cop to it. I learned jQuery first. Some will say that’s wrong. In my opinion, it abstracts away annoying browser quirks and makes diving into code a lot easier. The trick is to avoid simply writing a mess of chained spaghetti right from the get go.

If you really want to understand how jQuery works, I’ll give you the secret sauce. Learn jQuery in 30 Days, from Jeffrey Way. In about 8 hours you’ll learn about how forgiving JavaScript really is, and why you need to fight against that to write maintainable code.

When you’re done with that, follow it up with a real deep dive. An oldie but goodie from Addy Osmani about building large-scale jQuery applications. A lot of the tools he mentions have been abandoned, or are very different these days, but the fundamental concepts are essential.

Structuring JavaScript

To me, the easiest way to start getting better with JavaScript was to learn how to structure code properly. For instance, let’s say you have a set of jQuery events and click handlers throughout your app. How can you organize events to keep things DRY?

One option is to use the module pattern, expertly explained by Chris Coyer over on CSS-Tricks. Modules start simple, a plain JavaScript object that stores your jQuery handlers and delegates events, like so.

var s, 
Module = { 
    el : {
        button1 : $('#button-1'),
        button2 : $('#button-2')
    },
    
    init : function() {
        s = this.el;
        this.bindUIActions();
    },
    
    bindUIActions : function() {
        s.button1.on('click', Module.firstEvent);
        s.button2.on('click', Module.secondEvent);
    },
    
    firstEvent : function(e) {
        e.preventDefault();
        console.log("Event 1 successful");
    },
    
    secondEvent : function(e) {
        e.preventDefault(e);
        console.log("Event 2 successful");
    }
}

Module.init();

Modules, and design patterns generally, help you understand how JavaScript really works. There’s almost nothing more important than wrapping your head around Objects and scope. One trick here is to declare the global variable s and then call it in init(), assigning it to this.el.

Why? Because this is incredibly tricky in JavaScript, and binding it to a global variable from the get-go makes it easier to access in your entire module.

If you’re looking for the next level up, try Rebecca Murphy’s description of using objects to organize JavaScript. Of course, there’s also an entire book by Addy Osmani about JavaScript design patterns if you’re interested.

Understanding JavaScript

Here’s one thing you’ll hear, oh, all the time. 

Everything in JavaScript is an object.

Of course, that’s not entirely true. But it’s also absolutely true. Yes, there are primitives like booleans and strings that aren’t technically Objects, but they are usually transformed into Objects as they’re interpolated. And everything else, functions, arrays, etc. are prototypical Objects free to be mutated and extended. Why is that important? I can tell you one reason.

JavaScript provides a technique that gets us the best of both worlds. We can specify properties that, from the outside, look like normal properties but secretly have methods associated with them.

That’s a quote from Marijn Haverbeke, who wrote a free online book called Eloquent JavaScript. It is, by far, the most in-depth discussion of the why behind JavaScript and how we as developers can use it to our advantage. At the end of the day, you can do just about anything with JavaScript. Eloquent JavaScript will help you understand why you shouldn’t.

Still not convinced? Pick up a copy of JavaScript: The Good Parts. Douglas Crockford is a prophet.

I’ve also heard great things about the You Don’t Know JS series, though I haven’t fully dived in yet.

Learning Frameworks, Learning Always

Ok, but you want to build an application with WordPress as the base, and JavaScript as the client. That’s where I’m at. And for the past year or so, I’ve been doing just that. I’m hoping to share a good amount of those learnings here from time to time, but here’s the thing I’ve learned about all these frameworks: They come and go. Many take fundamentally different ideological approaches, but the underlying foundation remains pretty similar. Learn a library, and you can use it. Bully for you. But, learn basic JavaScript MVC (MV*) principles and you can pick up just about any framework or library in a couple of days.

I know many of you are just looking for comparisons. Here’s a decent one.

But for those that want to understand the right use case for frameworks, WP Sessions has an excellent course on using Backbone and WordPress. The presenters really dive into why using a front-end framework / library like Backbone is important and discuss piratical ways to layer it into existing projects.

Another great introduction into the “why” of MVC is Developing Backbone Applications, again by Addy Osmani. Osmani doesn’t simply walk you through how to create an application in Backbone, he gets to the core of application frameworks, and how they can help you get the job done.

And then there’s React. Which, and I can’t state this enough, is just one of many tools available to you. It’s the new hotness, and I understand why it feels imperative to learn. If you’re a functional PHP programmer, it actually probably makes a lot of sense. What really brought React into view for me was an article called “ReactJS For Stupid People“. I recommend you read it. I can also recommend an excellent tutorial about React + WordPress over on Rastislav Lamo’s site. And of course, Calypso is being written in React.

But always remember, you don’t need a framework.

Just Give Me the Links

Fine.

Categories
Inspiration

Craig Mod On Books

To return to a book is to return not just to the text but also to a past self. We are embedded in our libraries. To reread is to remember who we once were, which can be equal parts scary and intoxicating. Other services such as Timehop offer ways to return to past photos or past tweets. They, too, are unexpectedly evocative. Far more so than you might think. They allow us to measure and remeasure ourselves. And if a resurfaced tweet has an emotional resonance of x, than a passage in a book by which you were once moved must resonate at 100x.

Craig Mod, in Aeon

Categories
Development JavaScript

How to Make Text That Writes Itself in Javascript

One of my goals for the new year is to start actually blogging, to share the things that I’m learning, and to keep a better record for myself. To go along with that, I launched a new version of my site with the Fixed Theme from Array Themes. It’s incredibly well balanced, fast as hell, and a pleasure to use.

But I did want to carry over one thing from the last iteration of my site, and that is a sort of typewriter effect on the homepage which has a few messages from me to you. I actually saw this over at Music For Programming, and adapted the code for my own needs. But I thought I’d break down how it works. It’s written in vanilla JavaScript, in about 50 lines of code. The end effect is that text appears to type itself across the screen, delete the words, and then type some more.

Here’s what it looks like in action:

The effect itself is deceptively simple. JavaScript runs through each message, and one by one, pops the last letter off of the a message, and attaches it to the container. When we switch to “delete” mode, the opposite is done. In between running each of these, we add a random delay, then call the function again.

The first part is just about setting some variables. Nothing special here, just getting the value of the initial text with container.innerHTML, creating an array with the messages we want to type out, and setting an initial delay.

Next up, we create a simple updateText function. All this will do will take the value passed to it and update the container div with our new text:

function updateText(txt) {
    container.innerHTML = txt;
}

Now comes the cruft of our code, the “tick” function. The first part of the function checks to see if there is any text in our container div. If it is empty, then we have reached the end of the word. It increments our global variable timer (t), sets the message back to an empty string and switches to “write” mode.

    if(container.innerHTML.length == 0) {
        t++;
        thing = things[t];
        message = '';
        mode = 'write';
    }

Next up we use the JavaScript switch statement to move back and forth between two different modes. Switch simply takes a variable, in this case “mode” and runs code based on which case is set. The first mode is called write, which you’ll notice is what we set our mode to above, when the container is empty.

Our mode uses two crucial JavaScript string functions. The first is slice and the second is substr. Imagine our message is blank, we are starting to type a new line. First, the function uses slice to grab the first word off the beginning of our new message, and adds it to the message variable:

message += thing.slice(0, 1);

Next, it removes the first word off our message. That way, the next time this function is called it will grab the second letter, then third letter, and so on:

thing = thing.substr(1);

The write mode of this function does a few more things. For instance, if we have reached the end of our array, then we clear the window’s timeout function and return. We are done, and we want the last message to simply stay on screen. It also checks if there are any more letters in our message. If there are, it creates a delay that uses Math.rand to generate a random number. By using a random number, the effect has more of a typewriter feel. If you made the delay something static, it would look a lot more robotic. You can play around with the delay a bit to change the effect.

Our “delete” mode is even simpler then write. All we have to do is use slice to grab our message and pull the last word off of it. Then we run updateText() again to update our message, one by one.

  message = message.slice(0, -1);
  updateText(message);

And that’s about it. Our final step is just to kick off the function with an initial setTimeout. This will the delay we declared in our global variable (in this case 1 second), and start the function by deleting the initial message. Keep in mind, that I assigning window.setTimeout to a variable so that when the function is all done, I can use clearTimeout() to remove it altogether.

var timeout = window.setTimeout(tick, delay);

I’m sure there are lots of ways to do this, so I’m definitely open if someone has a different implementation. But I thought it was a cool trick that makes use of pretty common JavaScript string functions. Hopefully, you found it useful.

Categories
Inspiration

Ranier Maria Rilke

For one human being to love another: that is perhaps the most difficult of all our tasks… the work for which all other work is but preparation.”

Ranier Maria Rilke, A letter to a friend