Aurora Core: a clean, modern Sass and ES Next-ready project boilerplate

Now that Aurora Theme has a solid foundation built upon Underscores, it’s time to make it a React-ready project. To speed up this process, I am going to integrate Aurora Core, a project boilerplate, into Aurora Theme. Today I’ll discuss a few key features of Aurora Core, the problem it’s meant to solve, and a little about how I’ve built it. In future posts, I’ll talk about how it’ll be integrated into Aurora Theme, and the key differences between Aurora Core and Aurora Theme.

The problem

After building several dozen projects for Bov Academy, I realized most projects had a common set of requirements / tooling. Unless a project requires 200 lines of CSS or less, I always reach for Sass, and I needed a way to compile my styles.

always use JavaScript in all my Bov Academy projects, and typically, I’d have more than one file to deal with. Keeping performance and ease in mind, I needed a way to concatenate and minify to JS, too.

Additionally, I have a preferred structure for each of my projects. HTML files tend to stay at the top level, while Sass, JavaScript, images, and other assets live in an assets/ directory. Why recreate the structural wheel for each project, right?

My first attempts at rolling my Sass and JavaScript requirements together was within my Bov Web Components project. I set up my desired project structure and added a pretty sweet Gruntfile for all sorts of tasks. And it worked pretty decently. Except not all projects require accordions or tabs or [insert other component here]. And ain’t nobody go time for ripping all that junk out at the start of a project (because we all know if you wait to the end, that ish is shipping 😬). After ripping out the same components for the forth or fifth time, I decided it was time to consider building a proper boilerplate.

What makes a good project boilerplate?

The structural and Grunt task running features of Bov Web Components were infinitely useful. Other features, mainly the components themselves, were less so. I wanted to use what worked as a starting point, and expand upon that. So I created a little list of requirements for my boilerplate:

  • Sass support
    • functions
    • mixins
    • a base config file
  • JavaScript / ES Next
  • Task running
    • Sass compilation & minification
    • JavaScript concatenation & minification
    • Image processing (compression)
    • Icon concatenation & minification
  • Linting
    • Stylelint
    • ES Lint
  • Configuration
    • Editor Config
    • Prettier
    • Babel
  • Documentation
    • Sassdoc
    • JS Doc
    • KSS

Once the initial requirements were defined, I started really digging into research. Mina Markham’s Sassy Starter provided a lot of inspiration, as did fellow Bov Student Gabriele Romero’s ES6 Professional Starter Kit. Both are clean slates for a new project, and both are documentation-forward. Sassy Starter has incredibly well documented Sass functions and mixins using Sassdoc, while Gabriel’s ES6 starter kit has JavaScript documentation in mind with JS Doc integration.

I cannot express enough how important this type of documentation is. Have you ever used MDN or the jQuery API docs? Both have rich documentation available for both Sass and JavaScript was really important to me since Aurora Core is an open source project. I want anyone who comes across the boilerplate to feel confident that they can download it and get started with no problems.

To round out my research, I looked to the more popular feature-rich front end frameworks like Bootstrap and Foundation. I wanted to get a sense of what was included beyond a bunch of predefined components (i.e. were there any useful Sass functions or mixins I could replicate). I noted anything that looked interesting in Evernote, and found a few other resources along the way.

With a clear list of requirements, and a bunch of helpful notes research notes, I set to work on the boilerplate.

Laying the foundation

Bov Web Components was a great starting point for this project. In fact, I actually grabbed all the configuration files (Prettier, ESLint, Stylelint, etc.) and the Gruntfile from that project to start Aurora. Around the time I started Aurora Core, I read about Readme Driven Development (RDD). RDD claims to be a happy medium between a waterfall process, where projects are outlined in too much painstaking detail, and agile development where projects aren’t defined in enough detail. While I didn’t write my readme from the very start, I did set to work on it in the first day. Having a project charter has, indeed, been hugely beneficial to keeping my on task.

After the initial project setup, I focused on creating my foundational Sass files. I made detailed lists of must-have functions, mixins, and variables, trolled through old projects for more ideas, and added ideas based on my research. Even though I adore Sass, this part was painstaking. Remember when I mentioned documentation being important? Well, it’s also a PITA to write. It’s especially painful for mixins. Feast your eyes on this as an example:

/// Generate button variations quickly and easily.
///
/// @param {Color}  $background                                    - The desired background color.
/// @param {String} $border            [0]                         - The desired border (use shorthand e.g. 1px solid aqua).
/// @param {Color}  $background-hover  [lighten($background, 10%)] - The hover background color.
/// @param {String} $border-hover      [$border]                   - The hover border (use shorthand).
/// @param {Color}  $background-active [$background-hover]         - The active background.
/// @param {String} $border-active     [$border-hover]             - The active border.
///
/// @example - scss Sample Usage
///  @include button($color__primary, $border__button, $color__accent);
///
/// @todo Determine whether color should be passed, or add way to automatically determine color to use (light or dark).
@mixin button($background, $border: 0, $background-hover: lighten($background, 10%), $border-hover: $border, $background-active: $background-hover, $border-active: $border-hover) {
  background-color: $background;
  border: $border;
  color: $text-default-dark;

  &:focus,
  &:hover {
    background-color: $background-hover;
    border: $border-hover;
    color: $text-default-dark;
  }

  &:disabled {
    background-color: tone($background, 20%);
  }

  &:active {
    background-color: $background-active;
    border: $border-active;
    color: $text-default-dark;
  }
}

There is nearly as much / more documentation for this mixin as there is code! But it sure is helpful to have documentation to which I can refer later.

A screenshot of Sassdoc documentation for a button mixin within Aurora Core.

Introducing Webpack

Grunt is great. It’s familiar, but it is also slow AF. I heard all the kids these days are using Webpack, and as soon as I had an opportunity to learn it, I wanted to integrate it into Aurora Core.

One of the most common conceptions of Webpack is that it’s difficult to learn. And it kind of is. But while it’s not as easy or familiar as Grunt or Gulp, it’s not super duper difficult either. Once you wrap your head around loaders and plugins, you’re golden. 👌

But where Webpack really shines is in it’s ability to play super nicely with not only ES6+ JavaScript, but also with front end frameworks including Vue and React. While Aurora Core’s charter is to be ES6+ ready, I also wanted to make it really easy to integrate JavaScript frameworks.

So not too long after learning Webpack, I set to work researching loaders, plugins, and doing a bunch of trial and error to see what worked, and what didn’t. I’ll readily admit I have started it over once or twice already. But I’m feeling much better about where it is currently. I still need to add a few things specifically for production builds, but once that’s done, it’ll be good to go.

This is so much already, and I haven’t even touched on how Aurora Core will be integrated into Aurora Theme. 😅  In the next post, I’ll talk about adding Aurora Core to Aurora Theme. I’ll talk about preparing the theme for React, and on the differences between how Webpack works within Core vs. the Theme. After that, I’ll talk about how I’m using Aurora Core’s Sass in the Theme. There are some rad benefits of Sass + Webpack + React that I cannot wait to share. And last in this micro series on Aurora Core, I’ll review how I am using code formatting and linting tools, and the differences in them between Core and the Theme.

Building a React-powered starter theme

As I near the final stretch in my Bov Academy studies, it’s time for me to choose a final project. For my final project, I have decided to capitalize on my love of JavaScript + WordPress. So, in this post, I want to introduce Aurora Theme–a React-powered starter theme for WordPress. (If you click the link shortly after this is posted, the joke’s on you. I haven’t deployed anything yet, and that is, indeed, the current default theme.)

So maybe you’re thinking, “why is she sharing something she hasn’t even started?” That’s a great question. I thought it’d be pretty neat to document the entire journey of building this thing. To many of us in the WordPress community, this whole REST API thing is still a foreign concept. Breaking our traditional PHP theme paradigm is going to take time. It’s going to take research. And it may not be pretty. I already have questions about implementation of things in the back of my mind, and I’m hoping to answer these questions as I go, and share them with the community. Of course, if you’re reading one of these posts, and you have questions, speak up and ask in the post comments, or @me on Twitter. Let’s help each other. With that, let’s get this thing started. Read on below for a detailed project plan.

Aurora Theme Project Plan

Business Justification

The WordPress REST API was merged into WordPress Core in December 2015. The REST API gives developers a modern way of interacting with WordPress using modern JavaScript techniques and technologies. By default, WordPress ships with endpoints to interact with standard post types (posts and pages), but it can be extended to create custom endpoints which may include post meta, or anything else one might need from the database.

Implementation of the REST API gives WordPress users and developers several advantages. WordPress can continue to operate as a familiar and robust backend for data storage and delivery, while making the data itself more accessible to other platforms. Decoupling data delivery from the content management system (CMS) makes WordPress more accessible to a broader audience. For example, building a frontend to consume WordPress data no longer requires knowledge of the WordPress theming system. It frees developers up to consume their data in whatever way is necessary from use in websites, to apps, and other third party services. Instead of WordPress being the solution for a website, it can be a building block in the foundation of a user’s larger application.

Even though the REST API has been part of WordPress for nearly two years, adoption of the API has been slow, and there are few themes utilizing the features of the REST API. There are even fewer “starter” themes built on the REST API. To date, most REST API-driven projects have been limited to the “high end” spectrum of client sites. But with the imminent integration of Gutenberg, JavaScript technologies are becoming an increasingly integral part of the WordPress experience.

Aurora will be a starter theme built to utilize the features of the standard endpoints in the WP REST API, and will use modern JavaScript technologies including ES Next and React. Aurora will finally make REST API-driven sites and technology more accessible to the everyday WordPress user and developer.

Requirements & Objectives

Any starter theme built for WordPress needs to give developers a leg up in the development process, but should not include so many features that it becomes burdensome to work with. To that end, it is incredibly important that Aurora remain relatively un-opinionated, yet provide the basic features one might expect of a functional WordPress theme (i.e. if you install and activate the theme, it shouldn’t look like a dumpster fire). Ideally, any opinionated elements (e.g. styling) could easily be blasted away, giving the next developer a clean slate.

To that end, Aurora will support modern JavaScript development techniques, and give developers a solid foundation for starting a REST API project. Including documentation support is especially integral to the success of Aurora. Since WordPress has long been in the PHP-based theme paradigm, it’s important to have a well-documented theme to help PHP developers transition to writing JavaScript-driven themes.

Aurora will be a clean, modern theme with the following features:

  • Sass
  • ES Next + React
  • Icon (SVG) management
  • Linting according the WordPress Coding Standards using PHPCS, ESLint, and Stylelint
  • Documentation support

Requirements

  • Support default post types (post, page, nav-menu, comments)
  • Well-documented
  • Easy to understand
  • Extensible
  • Performant
  • Accessible
  • Gutenberg-ready

Objectives

  • Adheres to WordPress Coding Standards for PHP, styling (CSS), and JavaScript.
  • Complies with Section 508 and WCAG 2.0AA accessibility standards.
  • Meets WordPress internationalization and localization guidelines.
  • Use techniques including Atomic Design to keep the theme files organized and easy to understand.

Project Scope / Deliverables

At this time, Aurora will only consist of the starter theme. Future implementations may include:

  • Extensibility via the command line–easily spin up reusable components via a command line integration (e.g. Yeoman), which will be hosted indepently from the theme (likely via a branch of Aurora Core).
  • Gutenberg components. Support for default Gutenberg components will exist, but new components are not in scope for the initial phase of the project.
  • A plugin for interacting with Custom Post Types / Custom Endpoints.

Aurora

Aurora will be a clean, elegant starter theme with simple styling, and basic components, to help developers get started on their WordPress REST API theme projects.

  • Use Aurora Core (the non-theme boilerplate) as the base setup for the theme
    • Tweak Aurora Core Webpack setup to work with WordPress (keeping in mind that hot module replacement doesn’t work in WordPress).
      • Browser Sync
  • Use Underscores for some of the base theme files
    • header.php (pulls in styles and head scripts)
    • footer.php (pulls in scripts)
    • index.php (a fall back if our JS fails)
    • 404.php?
    • functions.php
  • Theme components (React components)
    • Header
    • Navigation (this might be a challenge given that there is no clear way of interacting with menus via the default endpoints)
    • Footer
    • Archive (home, categories, tags, etc.)
    • Single post / page
    • Sidebar (I’m really curious about supporting widgets via the REST API)
    • 404
    • Search results (maybe this is the same as the archives?)
    • Social icons (menu)
    • Comments
  • How should the theme interact with the Customizer?
    • Custom logo
    • Site title
    • Site tagline
    • Site icon (favicon)
    • Sidebar (no sidebar, sidebar right, sidebar left)
    • Widget area(s) for the footer (see Alcatraz)
    • Footer copyright text
  • Testing (Mocha? Jest? other?)
  • Performance metrics
  • Type checking
    • Flow?
    • TypeScript?
  • Documentation
    • Sass documentation
    • Component documentation (KSS? Storybook?)

Resources

RegEx revisited

In the past week or so, I delved deeply into the terrifying world of regular expressions (regex). It turns out that regex isn’t that scary, and if you play with it enough, it is actually kinda…fun? My first foray into regex was when I was working through How to Learn JavaScript Properly. It was a great primer, but what I learned recently at Bov Academy has taken my understanding of regex to an entirely new, terrifying level.

In the course of learning regex, I had two projects to complete:

  1. A simple JSON validator
  2. A link harvesting utility

I thought it might be fun to share a little of what I learned about regex through these projects.

Creating a simple JSON validator using regex

The first project I completed was a simple JSON validator. The gist is that the validator allows a user to either upload a JSON file, or paste their JSON data into a textarea. When the user clicks submit, the validator will use a regular expression to check whether the string is valid JSON. There are some caveats, however. This validator isn’t meant to check all JSON data, so mine will not correctly validate JSON arrays, but only JSON objects.

Because the regex portion of this assignment is what I really care about for this post, that is the only part I’ll cover. However, if you’re interested in the rest of the code, you can check out the Github repo.

Defining valid JSON

The first step in working with any regex project is determining what qualifies as a valid match. In the case of JSON, here are the match parameters:

  1. Starts with an opening curly brace
  2. Keys must be wrapped in double quotes
  3. Keys must be followed by a colon
  4. Values may consist of these types:
    1. Strings (wrapped in double quotes, but not containing double quotes)
    2. Numbers
    3. true / false
    4. undefined
    5. null
    6. Objects
    7. Arrays
  5. When more than one key-value pair exists, the key-value pair must end with a comma
  6. The final key-value pair must not have a comma at the end
  7. The JSON object ends with a closing curly brace

With the valid JSON structure in mind, I created a simple, yet valid object to test against.

{
	"name": "Paul Stephen Forde",
	"age": 1,
	"cute": true,
	"occupation": undefined,
	"friends": [
		"Minnie",
		"Whitney",
		"K2"
	 ],
	 "markings": {
	 	"type": "tabby",
		"color": "orange"
	 }
}

Then I headed to the must-bookmark RegExr site to start playing with my JSON regex.

Capturing the opening curly brace

The first step is pretty easy–let’s make sure there is a match for the opening curly brace:

var pattern = /^{/;

By tacking ^ onto the front of this regex, we’re making sure that our JSON object begins with that character. So whenever something must begin with a character, put a little hat on it (i.e. ^) and party on. 🎉

Identifying the keys to our JSON

Next, we’re going to check for some whitespace (anything like a space or a new line), and our key, which as mentioned above, must be wrapped in double quotes. Keys must also be followed by a colon, so we’ll check for that too.

var pattern = /^{\s*("\w+"):/;

Let’s break this \s*("\w+"): section down a bit.

\s* is what we use to check for our optional whitespace. \s will search through our string and check for any whitespace character such as a space, tab, or new line. Adding * checks whether the proceeding character set (i.e. \s) exists zero or more times. That basically means that we’ll allow as much whitespace as the user wants, including no whitespace.

Parentheses in regex allows us to group a character / search set together. In the case of ("\w+"), I want to look for the JSON key which will have a opening " any combination of one or more word characters (\w, which is A through Z, 0 through 9 and the underscore), followed by a closing ". The + holds a magic power similar to *, but instead of zero or more, + requires at least one or more matches of the previous character set. After the key group, we simply add a : to ensure that is present before checking the value.

Checking JSON values

Checking for valid values is where this regex starts looking gnarly because there are so many different types of values to check. At this stage, it’s best to break each possible value down into its own parts.

Starting with string values

We’ve already checked for strings in our key, so we can use that as a rough guide for checking valid string values. It does require modification, however, because a valid string could include a sentence with whitespace and punctuation. This updates our regex to look something like this:

var pattern = /^{\s*("\w+"):\s*(("[^"][\w\s!@#$%^&*()\-+={}[\];:',.<>?/]+"))/;

Isn’t she a beaut? 💁‍♀️ Let’s go ahead and break down the (("[^"][\w\s!@#$%^&*()\-+={}[\];:',.<>?/]+")) part.

I’m using two sets of parentheses for the capturing group because I’ll want to be able to check any of our valid values (i.e. more than just the string) and within that I want to check for a string group.

This string group starts with the double quote, then we hit this guy [^"], which basically says, “hey double quotes, buzz off you’re not invited to this string party.” So any time you see a party hat within a set of square brackets, that there is a goddamn party pooper. 🙅‍♀️ But in all seriousness, [^] is a negation set, meaning that anything that comes after the party hat but before the closing square bracket will be excluded from set.

[\w\s!@#$%^&*()\-+={}[\];:',.<>?/]+ is our heavily modified key check. And by heavily modified, I mean I added all this garbage: \s!@#$%^&*()\-+={}[\];:',.<>?/. Adding that set of characters allows our string to contain whitespace, and a boatload of characters. One might be tempted to try [\S\s], which allows for any characters, but that ends up allowing almost anything, and won’t return invalid should a double quote sneak its way into the mix. (Fun fact: I actually realized this bug in the process of writing this post.) By specifying exactly what we’re allowing, we can ensure that the regex doesn’t ignore our no double quotes within the string rule.

Numbers, truthy values, object and arrays, oh my!

Checking for strings as values is actually the most complicated part of the value regex because we need to specify what’s allowable within the string. Checking for the remaining valid values is actually relatively easy.

var pattern = /^{\s*(("\w+"):\s*(("[^"][\w\s!@#$%^&amp;*()\-+={}[\];:',.&lt;&gt;?/]+")|\d+|true|false|null|undefined|{[\S\s]*}|\[[\S\s]*]))*/;

That looks gnarly, but let’s break it down starting with |\d+. Whenever we encounter \d in regex, it means that we’re looking for any digit between 0 and 9. And you’ll remember when we add a +, it means we’re looking for one or more of a character group. So in this case, we’re looking for one or more digits. The pipe (|) that proceeds the \d is very similar to the || that we might see in JavaScript or PHP. Basically it says we want to match our string OR digits.

When we add |true|false|null|undefined, we know that we’re looking for a string OR a set of digits OR true OR false OR null OR undefined. We defined these values explicitly because they do not require double quotes like strings do.

Things get a little loosey goosey with the array and object checks, and this is why this is a simple validator. We use {[\S\s]*} to allow an object with any values within the object, and do something similar with our array check: \[[\S\s]*]. This means that we could get a valid result even though there may be invalid data within an object or array value. As I mentioned before, [\S\s] allows any characters, which includes A through Z, 0 through 9, punctuation, whitespace, etc. The * simply checks for zero or more occurrences of a character. And because square brackets are used to define character groups in regex, I had to escape the first bracket in the array check with a backslash: \[.

Capturing multiple key-value pairs

We’ve now defined parameters for keys and all allowable values. But if you plug this into RegExr using the sample valid object above, you’ll notice it only highlights the first line.

JSON validator after first key-value regex checkWhat we also notice is that the regex stops at the comma. It’s almost as simple as tacking on a comma at the end, but not quite. We need to add an opening parenthesis just after the opening curly brace for the entire regex, and we’ll add another closing parenthesis before the closing /. The comma will go between the final two closing parentheses. We’ll also add our handy zero or more * to allow for multiple key-value pairs. Now our regex is looking like this:

var pattern = /^{(\s*(("\w+"):\s*(("[^"][\w\s!@#$%^&*()\-+={}[\];:',.<>?/]+")|\d+|true|false|null|undefined|{[\S\s]*}|\[[\S\s]*])),)*/;

And now we have all but the last key-value pair and closing curly brace highlighted.

JSON regex matching all but last key-value pair

Capturing the final key-value pair

Capturing that last key-value pair isn’t too complicated. We can simply copy the key-value portion of the regex and paste that after the final * in our existing regex. But this time, we need to remove the comma and that final *.

var pattern = /^{(\s*(("\w+"):\s*(("[^"][\w\s!@#$%^&*()\-+={}[\];:',.<>?/]+")|\d+|true|false|null|undefined|{[\S\s]*}|\[[\S\s]*])),)*\s*(("\w+"):\s*(("[^"][\w\s!@#$%^&amp;*()\-+={}[\];:',.<>?/]+")|\d+|true|false|null|undefined|{[\S\s]*}|\[[\S\s]*])\s*)}$/;

I have also added the check for our closing curly brace, }$. The $ indicates that the end of the string must be the curly brace. You may also notice that I added a \s* before the closing parenthesis to allow for any amount of whitespace before we hit the end of the JSON object.

Checking invalid scenarios

The assignment provided an example of invalid data to help us on our way. It’s important to check for both valid and invalid scenarios to ensure that things are working correctly.

{
  "country": "United States",
  "capital": "Washington, DC
  "states":{{}}
}

This scenario is great, but isn’t robust enough. We see that the closing double quote is missing for the capital value, but the comma is also missing. So to test this thoroughly, I’d make sure that we get no matches in the current case, when the ending double quote is present but the comma isn’t, and when the ending quote is missing, but the comma isn’t. I’d also dream up other scenarios to ensure that the validator passes simple tests. Trying a JSON object with just a single key-value pair might be a good test, for example.

Is this JSON validator perfect? Absolutely not, but it does a pretty decent job of at least making sure that all JSON object keys are wrapped in double quotes, and that most of our values are 100 percent correct (with the exception of what’s within an object or array, of course).

Building a Link Harvester

The second regex-heavy assignment was to build a link harvester. The link harvester allows a user to upload an HTML file, or paste the contents of an HTML file into a text area. Upon submitting the data, the harvester outputs all the external links and emails addresses along with their corresponding text.

Again, I’m going to focus on the regex for this post, but if you’re interested in a deeper dive, you can find the repo on Github.

Defining valid link scenarios

As with the JSON validator, the first thing to do was identify what qualified as a valid match. In this case, I was looking for external links and email addresses. I wanted to exclude links within a site, so I’d keep that in the back of my mind when testing various scenarios.

Harvest all the links

I took a few stabs at different ways of identifying links before arriving at my final regex. I knew that a link needed to be wrapped in an a tag, and I knew that external links could start with http or https. Email addresses on the other hand could start with mailto. But what I decided after a few different attempts is that the first pass for harvesting links shouldn’t care what type of link existed, it should just focus on capturing anything wrapped in an a tag. So this is my initial regex:

var pattern = /(<a[\s\w="?:/.@-]*>)([\w\s.,;:-])+<\/a>/gi

Let’s split this up into the three main parts, starting with (<a[\s\w="?:/.@#-]*>). We’ve got this whole thing wrapped in parentheses, so we know this is a capturing group. Within the capturing group, we want to find the opening portion of our a tag <a. We’re going to follow that with optional whitespace, word characters, and a few additional characters we may find in class names, urls, etc. [\s\w="?:/.@#-]* gives us the most flexibility in harvesting the opening a tag without worrying about whether a link contains just an href, a class, an id, or any other combination of attributes. As we did several times in the JSON validator, we add a * to allow for zero or more instances of that character set. Then we’ll look for our closing angle bracket.

The next capturing group, [\s\w="?:/.@#-]* will capture our link’s text. The link text may contain whitespace, word characters and a few additional punctuation characters (I didn’t go overboard here, so it’s entirely possible it may not harvest a link it should).

The final part is simply the closing </a> for our link tag. I’m tempted to make an anchor joke here, but I think I’ll just keep going…⚓️

Weeding out the non-matches

I used the match method to store the links as an array to my links variable. The next job is to loop through all those links, identify which ones are external links and email addresses.

// Pull out the external links & email addresses.
links.forEach(function (link) {
	var address = link.match(/((https*:\/\/)[\w=?:/.@-]+)|(mailto:[\w@.-]+)/gi),
	    text    = link.match(/(?!>)([\w\s.,;:-]+)(?=<\/a>)/gi);
			
	// If after applying our second-layer regex, if empty, bail.
	if (!address) {
		return;
	}
			
	// Push links into our harvested object's links array.
	if (address[0].match(/((https*:\/\/)[\w=?:/.@-]+)/gi)) {
				
		var obj = {
			url: address[0],
			text: text[0]
		};

		harvested.links.push(obj);
	}

	// Push email addresses into our harvested object's email array.
	if (address[0].match(/(mailto:[\w@.-]+)/gi)) {

		harvested.emailAddresses.push(address[0]);
	}
});

You’ll notice that address is doing a further check on the current iteration of the link array, var address = link.match(/((https*:\/\/)[\w=?:/.@-]+)|(mailto:[\w@.-]+)/gi). Were checking for whether the link begins with http. By adding s*, we can add an optional check for an s which will also pass our https check. Then we make sure that is followed by a colon and two forward slashes (which have been escaped). The url itself can contain any combination of word characters, and a select few punctuation characters. Unfortunately, I don’t think this necessarily captures all link scenarios, but I was able to capture fairly common scenarios in my testing.

Since we want to grab email addresses, we have a | and a second capturing group to check for mailto:. I figured there are fewer allowable characters in email addresses, so limited it to word characters, the @, ., and the dash. You’ll note that there is a gi at the end of all regex in this link harvester example. The g flag is what allows us to capture more than one match, and the i flag ignores the character case, so we can match both upper and lowercase characters.

The magic of positive and negative lookaheads

The trickiest bit here wasn’t identifying potential links for harvesting, but trying to figure out how to capture just the text between an opening and closing a tag. Sure, I could have used some substring() voodoo, but why not put regex to the test here too?

You’ll notice the text variable’s regex has some weird extra characters in it, namely (?!>) and (?=<\/a>). We’ve already discussed that parentheses are used for capturing groups, and the same is true in both these instances. Adding ?!, known as a negative lookahead, to the first capturing group, however, tells our regex to look for the closing angle bracket of our opening a tag, but doesn’t actually include it on our match. We need the second part, our positive lookahead ?=, to tell our regex to keep looking until you find this closing a tag, but again, don’t actually include the </a> itself in our results. Basically, the combination of a negative and positive lookahead is creating a boundary for our text regex, and returns only the link text value. Pretty neat, huh? RegExr illustrates this really well:

Regex lookahead example

The rest of the forEach pushes our set of external websites and email addresses to an object, which is rendered to the screen by a separate function.

There is no denying that regex is still tricky, but I’ve been finding it a fun challenge to figure out these types of problems. Clearly, regex is not necessarily easy for everyone to understand, and many consider it an anti-pattern for that reason. So, if there is an easier way to accomplish something without regex, that would be the preferred route. But if you absolutely need to use a regex, hopefully this post has cleared up some confusion or offered you some ideas to solving your regex quandary. 😃

Getting started with task-running & Gulp

Front-end development typically consists of many stages, including scaffolding (setting up the project environment), development of the website or application, testing, optimization, and deployment. Setting up project environments and the rest of the project workflow from scratch project after project can become cumbersome. Task runners were introduced to solve this problem. Task runners help developers manage and automate all the tasks associated with the various stages of development. In this article, I will focus on the popular task runner Gulp, and show you how to set up Gulp with a basic tasks for compiling Sass.

Getting started with Gulp

First thing’s first–with any task runner, you will need to make sure you have Node installed on your computer. You can either visit the Node website and download the appropriate package and install from there, or use Homebrew (my preferred method) to install Node via the command line if you are using a Mac. To install Node via Homebrew, simply type brew install node in your terminal prompt.

Once you have Node installed, you’ll need to use NPM, the package manger that comes bundled with Node, to install Gulp. Several Node packages can be installed globally on your computer, and / or locally to your project. In this case, we’ll want to start by installing Gulp globally. Simply type the following into your terminal prompt:

npm install -g gulp-cli

In this command, the -g flag is what tells Node to install this as a global package.

Now that we have the Gulp CLI installed globally, we’re ready to get started configuring our project. If you already have a project for which you’d like to set up Sass, simply navigate to that project via your terminal. Something like this:

cd path/to/your/project

Otherwise, create a new directory and cd into the directory.

Setting up a Gulp project

Now we’re ready to start setting up our project to use Gulp. The first step in this process is to create a package.json file, which is a manifest that keeps track of all the packages we’re using for development of a specific project. This is particularly important when we’re working on a project across a team because it allows other team members to simply clone a Git repository and install the packages with a single command, rather than going through this entire setup process.

The first step is to ensure you’re in the correct directory for your project. Once you have ensured you’re in the correct directory, we’ll need to create our package.json file by typing the following in the terminal prompt:

npm init

This command will prompt you for information about the project. Follow the prompts and fill out the information as best as you can. If something doesn’t seem relevant at this point, simply hit Enter to accept the default. Once you have completed the steps of npm init, you will see a new package.json file at the root of your project.

Now we’re ready to start adding Node packages!

Adding packages

Earlier I mentioned that Node allows us to install packages globally on our computer, or locally to our project. At this stage, we’re going to install all the packages we need for this specific project locally.

The first package we’ll install is Gulp itself. We can do this by typing the following into the terminal window:

npm install --save-dev gulp

This command downloads Gulp into a node_modules directory in the root of your project. The --save-dev flag tells Node to save this package under the devDependencies object in our package.json file. This means that the next developer to come along can simply run npm install to grab the same dependency. If you were to only type --save in for the flag, it would save to a dependencies object, which is mean for development of Node applications; devDependencies are dependencies that are not required in the production environment.

This may be a good point to stop and add node_modules to your .gitignore file. node_modules tends to be a hefty folder with not just our packages, but their dependencies, and other developers involved in the project can just install these dependencies themselves by running npm install after they have cloned the project.

While we’re in the installation stage, let’s also install the Sass package we’ll need:

npm install --save-dev gulp-sass

Configuring Gulp tasks

Alright, now we have Gulp and our local packages installed, let’s go ahead and start configuring our Gulp tasks. The first thing you’ll need to do is create a Gulpfile.js in the root of your project.

Open the Gulpfile and add the following:

var gulp = require('gulp');

gulp.task('default', function() {
    // place code for your default task here
    console.log('Gulp is working!');
});

The var gulp = require('gulp'); line is telling Gulp to pull in the Gulp package from the node_modules folder.

The next few lines starting with gulp.task are configuring our first task, the default task, which simply prints Gulp is working! to the console. Go ahead and type gulp into the console to ensure everything is working, and that you see the Gulp is working! message.

Now that we’ve established the basic pattern for pulling in our packages and adding a task, let’s set up our Sass task.

Compiling Sass with Gulp

The first thing we need to do when adding a new package for usage with Gulp is load it into our Gulpfile:

var sass = require('gulp-sass');

Now that we have loaded sass to our file, let’s go ahead and set up the Sass task using gulp.task(), which takes two parameters: the name of the task, and a function which tells Gulp what to do to complete this task:

gulp.task('sass', function() {
    return gulp.src('./sass/*.scss')
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(gulp.dest('./'));
});

gulp.src() tells Gulp which files to process during this task using a simple glob pattern–that is, look for anything within the sass directory that has a file extension of .scss.

That information is then piped (using .pipe(), which is similar to piping via the command line) to the sass.sync() function, which is set up to log any errors that may occur during the processing of that task.

Finally, that output, if it didn’t error, is piped to our destination folder, in this case the project root, where we should find our compiled CSS file.

The “guts” of a Gulp task is essentially a function that returns our output.

Now, if we have some Sass files in the Sass directory, we can run gulp sass from the command line, and we should see our compiled file in the root of the project.

Automating with Gulp

As you can imagine, running gulp sass every time you need to compile your stylesheets becomes cumbersome quickly. Let’s go ahead and add a task which will automatically compile our Sass every time we save a file, called watch:

gulp.task('watch', function() {
    gulp.watch('./sass/*.scss', ['sass']);
});

This task simply takes our initial glob pattern from gulp sass, and tells the watch method to watch for changes within files that match this pattern (you can also pass an array of several directories), and the second parameter tells the watch method which task(s) to run when a change is detected.

So now, when we want to work on our Sass, we can simply type gulp watch into the terminal, and anytime a file is saved, Gulp will automatically run our gulp sass task.

Wrapping up

This tutorial is just the tip of the Gulp iceberg. There are so many other helpful Gulp packages that can be added and configured to automate the development process. You can process stylesheets with PostCSS, concatenate and minify JavaScript, control versioning, and even deploy your sites or applications with Gulp. I encourage anyone looking to learn more to check out the Gulp website, read the Gulp docs, or search for Gulp plugins to further explore the possibilities.

In the meantime, if you’re looking for jump start, check out my Getting Started with Task Running & Gulp Gist for a package.json and Gulpfile.js that will get you started with Sass compilation, CSS & JS minification, and more. 😀

Using cat rivalry to understand the bind method

A few weeks ago, I used the rivalry between my girl cats, Whitney and Minnie, to solidify my understanding of JavaScript’s .bind method. I thought I’d share it because let’s be honest, the MDN explanation of .bind() is confusing:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

What .bind() does–a plain English explanation

The JavaScript bind method allows developers to rebind or “rescope” the this keyword. When working with objects, and functions within objects, this refers to the object with which we are working. For example, in the the code below, this within the getKittyInfo method refers to the kitten object:

var nemesis = 'dog';
var kitten = {
    'name': 'Whitney',
    'age': 11,
    'color': 'orange',
    'markings': 'torbie',
    'nemesis': 'Minnie',
    getKittyInfo: function() {
        console.log( this.name + ' is an ' + this.age + ' year-old ' + this.color + ' ' + this.markings );
    }
}
kitten.getKittyInfo();

Output

"Whitney is an 11 year-old orange torbie"

Where things get confusing

However, whenever a function is inside another function, this is bound to the global object.

So, when we add the archNemesis() within within getKittyInfo(), our archNemesis()‘s this is instead bound to the global object (i.e. nemisis) instead of our kitten object:

var nemesis = 'dog';
var kitten = {
    'name': 'Whitney',
    'age': 11,
    'color': 'orange',
    'markings': 'torbie',
    'nemesis': 'Her younger sister, Minnie',
    getKittyInfo: function() {
        console.log( this.name + ' is an ' + this.age + ' year-old ' + this.color + ' ' + this.markings );
            function archNemesis() {
                console.log( 'Arch nemesis: ' + this.nemesis );
            }
        archNemesis();
    }
}
kitten.getKittyInfo();

Output

"Whitney is an 11 year-old orange torbie"
"Arch nemesis: dog"

When archNemesis() is called, the result of nemesis is dog because it is accessing the global object (i.e. our nemesis variable created right before our kitten object. In order to get archNemesis() to use the nemesis defined within our kitten object, we’ll need to bind the archNemesis function like so:

var boundNemesis = archNemesis.bind( this );

This tells our function that we’d prefer to use our kitten object’s this instead of the global this.

In the final example below, you can see how this was done within the kitten object’s archNemesis function:

var nemesis = 'dog';
var kitten = {
    'name': 'Whitney',
    'age': 11,
    'color': 'orange',
    'markings': 'torbie',
    'nemesis': 'Her younger sister, Minnie',
    getKittyInfo: function() {
        console.log( this.name + ' is an ' + this.age + ' year-old ' + this.color + ' ' + this.markings );
            function archNemesis() {
                console.log( 'Arch nemesis: ' + this.nemesis );
            }
        var boundNemesis = archNemesis.bind( this );
        boundNemesis();
    }
}
kitten.getKittyInfo();

Output

"Whitney is an 11 year-old orange torbie"
"Arch nemesis: Her younger sister, Minnie"

Hopefully this example has also helped you wrap your head around .bind(). If in your travels / experiments you come up with examples of your own, please feel free to share them in the comments!

Updates: Intentions and JavaScript

At the beginning of the year, I posted about my intentions for 2017, in which I laid out a set of learning and project goals. But as these things go, a lot changed in the first half of the year, and basically derailed every. damn. intention.

I quit my job

After about a year at WebDevStudios, I decided it was time to part ways. I had pretty mixed feelings about this. Most there are kind and supportive humans who are more than willing to share their passion and knowledge for all things WordPress and web development. At the same time, however, there were a variety of other factors that caused me a lot of stress and were leading me to burnout city.

Working from home might be overrated

One of the shittiest things about working from home and feeling stressed and burnt out is that you can’t get away from those feelings. EVER. Personally, I want my home to be a safe space, and I’m giving up on the idea of remote work. Well, I’m thinking about it. I’ve worked remotely most of my professional career (since 2006), and only when it wasn’t at all possible to go to an office did it become an issue.

I think completely losing face-to-face interaction is the main issue here. And while WebDev very kindly and generously organized an annual retreat, getting to see your co-workers in the flesh once a year isn’t enough. When you’re interacting through computer screens its easy to dehumanize your co-workers and forget the kind and awesome humans they are.

In a moment of, oh shit, something’s gotta change, I started looking at local opportunities. Like, super local. Right in downtown San Mateo local. And there are some great opportunities for front-end developers / engineers, but with only two years of experience under my belt and a considerable lack of JavaScript understanding, I realized I had my work cut out.

I enrolled in a dev bootcamp

Every front-end developer job in the Bay Area is heavily focused on JavaScript (JS) and JS frameworks like Angular, React, and Vue. So I while I wasn’t disheartened when I was skimming local job listings, I knew I needed to put more intention and focus behind my JS studies. So in April, I began researching different developer bootcamps, looking at both local, in-person immersive bootcamps and remote bootcamps. From a sea of potential candidates, I narrowed my choices down to Hack Reactor and Bov Academy.

Hack Reactor had loads of great reviews, and seemingly a pretty good job placement rate. However, it also came in a the hefty price of close to $20k (for a three month program). 😱 That’s more than my total tuition for the undergraduate degree I earned from the University of Wisconsin-Madison in 2005.

Bov Academy on the other hand, was about half the price, and is conducted solely online. At the time, I wasn’t sure if I wanted to keep working or not, but I did like the idea of having flexibility, a life, etc. Not to mention, the syllabus for Bov stressed teaching JS fundamentals over frameworks, which really appealed to me. Oh, and it’s run by Richard Bovell of JavaScript is Sexy fame, which I’ve talked about in previous posts. But what really sealed the deal for me is that my good friend and former colleague Eric was enrolled in Bov, and his JS knowledge is truly enviable. I wanted to channel my inner Eric, or at least the JS ninja living somewhere in my soul.

It ain’t a bootcamp if you’re not flying through the material

I started Bov in May, and got off to a slow start because not only was a still working, but I was giving a talk at WordCamp Orange County. Regardless, I tried to put in an hour or two after work most days, starting with learning about Markdown and the Command Line, and fast-forwarding through a bunch of stuff to do with HTML and CSS. I tested out of those chapters because if I don’t know that by now, what have I been doing for the past two years, right? 😏

By July, I was free of talk-writing obligations for a few weeks, so I was able to jam on all things JS. It started slow. There was a lot of review of the basics, including data types, etc. However, as I worked through each exercise, I realized things are clicking and sticking for the first time. I was confidently working through problems, and making loads of progress, but not necessarily consistent progress.

Assessing priorities and future goals

At the same time, the weight of work stress was crushing, and I wasn’t able to move through my studies as quickly as I hoped I would. I had to assess where I was professionally and where I wanted to be. I did a mental risk assessment, talked things through with my husband. Ultimately, the payoff of rejoining the Silicon Valley workforce sooner made more financial sense than staying at my job and taking more time to work through Bov. But couple that with the stress situation, and leaving was the only sensible answer.

And now I’m pretty fucking happy

I’m two weeks into studying full time, and I couldn’t be happier. I spend somewhere between four and eight hours studying / writing code. There are no more 7a.m. starts. Hell, I don’t even get out of bed until 8a.m. My overall productivity has been much better. I managed to launch my updated site, am working on refinishing an interior door in my house, and am working on my next WordCamp talks.

What the future holds

My dad is also coming to visit next month, so I’m looking forward to catching up with him, and exploring the greater Bay Area. After that, I’m giving two WordCamp talks, one in Sacramento, and the other in Salt Lake City. If you want to learn about component libraries or get some ideas for methodically approaching WordPress theme development, snap up those tickets!

Otherwise, I’m going to focus mainly on blasting through Bov, with hopes of completing the bootcamp before the end of the year. As I go, I’ll be actively thinking about what I really want to do. Lately, I’ve been loving the idea of coupling data visualizations using D3 with React dashboards.

What about open source projects?

I hope to spend more time working on my open source projects after WordCamp Salt Lake City. A few months ago, I made substantial updates to Alcatraz, where I refactored a load of the Sass and made some minor accessibility improvements.

I’ve also started a new project, the WP Component Library (repo here), which is basically a plugin that allows designers and developers to create and document components used in their WordPress projects (I’m using on this site!). This idea is the cornerstone for both my Using Component Libraries for Rapid Theme Development and Supercharge Theme Development with Component Libraries talks. I wanted to create the plugin as a basis for others to create their own component libraries, and am hoping to add more prebuilt, WordPress components to the site in the coming months.

2017 has been a doozy, but I’m hopeful that the strides I’m taking now lead me to a more fulfilling future. 😄

HTML Forms and Regular Expressions

Week 3: HTML Forms and Frames; JavaScript Strings; Build Your First Interactive Website of JavaScript.isSexy’s How to Learn JavaScript Properly course has been focused mostly on learning material from the book. Beginning JavaScript, is a very good book for learning this material. I have found the explanations of concepts to be thorough, yet easy to understand, and there are loads of examples throughout the book to help illustrate the concepts discussed. I would say that Beginning JavaScript is the best resource for this particular track.

HTML Forms

HTML forms are great. They allow users to input information into a text box, select options from a list, check some boxes, or even see their progress through a specified task. Forms themselves, however, are rather boring. They don’t really do anything unless you have a destination for the information input (a destination server). Despite this, they are an essential part of the web.

Much of Chapter 11: HTML Forms: Interacting with the User (Chapter 7 in the 4th Edition) felt more like a review of basic HTML concepts than it did JavaScript instruction. There was a lot of instruction around how to create a form using <form />, <input />, and other such tags than actual interaction with the forms, or so it seemed. But of course, there actually was a lot around interaction.

This chapter talked about different event listeners available to form objects including focus, blur, change, and input, and showed some examples of using for loops to loop over radio buttons to determine what was selected and output that information to the screen. One thing I really enjoyed about this chapter was seeing how different using event listeners and selecting DOM elements is from jQuery (because of the more roundabout nature of the JS.isSexy course, I’ve not done any reading about interacting with the DOM using vanilla JS), which is helping me appreciate why jQuery is so widely used today. Now that I have my head wrapped around HTML forms, and jQuery, I’m ready to tackle a small real-world application of using this knowledge in WordPress.

Regular Expressions and String Manipulation

String manipulation is tricky, and it’s tricky for many reasons.

One thing I’m still trying to wrap my head around after finishing Chapter 6: String Manipulation is figuring out when I’d want to use regular expressions for string manipulation. I guess I can see a case if you’re building an app or program that allows a user to do some sort of search, and I could also see using it to do something like check for duplicate words, or replace one string with another. I guess it’s not that I can’t see a use for it at all, but more that I can’t see a direct use for this my current realm of development (much like trigonometry in high school, which, shockingly I haven’t used since).

Not only am I having difficulty wrapping my head around when I might use regular expressions and string manipulation in WordPress development, but regular expressions are hard! One of the examples from the book to validate a post code looked like this:

function isValidPostalCode( postalCode ) {
    var pcodeRegExp = /^(\d{5}(-\d{4})?|([a-z][a-z]?\d\d?|[a-z{2}\d[a-z])?\d[a-z][a-z])$/i;

    return pcodeRegExp.test( postalCode);
}

Gnarly, right? But the book actually offered some good reassurance: regular expressions are tricky, and they take time and patience to get right, and are best approached by breaking things down. So let’s quickly break down the example above:

All regular expression literals start and end with forward slashes: /.

^(\d{5}(-\d{4})?

The first part of this expression ^(\d{5} is looking for something beginning with a five-digit number (\d indicates a digit, {n} indicates the number of something), while the second part is looking for an optional dash (-) and four more digits. The set of parenthesis wrapping (-\d{4})? indicates it’s a group–in this case, of a dash and four numbers), and the question mark at the end indicates that this group is optional. So basically, we’re looking for xxxxx or xxxxx-xxxx where the x represents a digit between 0 and 9. The next part is checking whether we have a UK post code:

([a-z][a-z]?\d\d?|[a-z{2}\d[a-z])?\d[a-z][a-z])

First, it’s good to know that UK post codes are formatted something like this: TW10 6UQ. The post code could have one or two letters at the beginning, followed by one or two numbers, maybe another letter, a space, then a number and two letters. So let’s look at this:

[a-z][a-z]?\d\d?

The [a-z] looks for a letter between a and z, while the second one [a-z]? looks for another optional letter (remember ? indicates the match is optional in JS). Then the \d is looking for a digit between 0 and 9, while the following \d? is checking if there is another optional digit. So in the case of my old post code, it’d be checking if TW10 is valid.

You’ll see that there is a pipe ( ) following that expression, which is like a RegEx or operator. In this case we’re looking for [a-z][a-z]?\d\d? or [a-z{2}\d[a-z])?. Let’s look at this more closely:

[a-z{2}\d[a-z])?

Here, we’re looking for two letters from a to z ([a-z{2}) followed by a number (\d), then another optional letter ([a-z])?). This is to check whether the post code is something like SW1A.

\d[a-z][a-z])

For the final part of the expressions, we’re looking for a digit, and then two letters between a and z.

Honestly, I think finding weird convoluted examples like this is one of the best ways to figure regular expressions out. Even if you’re not necessarily writing your own RegEx, trying to figure out what someone else’s RegEx is doing feels like a good workout.

An Interactive Website

I rounded out this week’s JavaScript learning with Codecademy’s Make an Interactive Website course. I found this particular exercise to be more of a review of the concepts that I have learned up to this point in the JS.isSexy course, rather than learning anything new.

The basic premise was to review a concept, and then recreate some interactivity of an existing site’s functionality, such as Flipboard’s home page, and Twitter’s status updates. The basic idea was right, but I thought some of the instruction was rather misleading. For example, in the Twitter update example they wanted to disable the post button if the remaining character count was less than 0 or equal to 140 (i.e. nothing has been typed into the status box yet). Their correct answer looked something like this:

if(charactersLeft < 0) {
 $('.btn').addClass('disabled'); 
 }
 else if(charactersLeft == 140) {
 $('.btn').addClass('disabled');
 }
 else {
 $('.btn').removeClass('disabled');
 }

when in reality, they I think they should be reiterating good, optimized practices and used this:

if(charactersLeft < 0 || charactersLeft == 140) {
 $('.btn').addClass('disabled'); 
 }
 else {
 $('.btn').removeClass('disabled');
 }

At the very least, they should have mentioned that was an alternate way to arrive at the same solution.

Week 3 Wrap up

I am really feeling very comfortable with jQuery at this point. I’ve been testing it out on some side projects that are semi-WordPress related, as well as a few other unrelated projects.

Unfortunately, the 5th Edition of Beginning JavaScript did not include a chapter on Windows and Frames, so that is something I missed out learning this week. I also didn’t complete any work on Treehouse this week because I didn’t see any sections in the Full Stack JavaScript track that corresponded well to the book’s materials.

jQuery, JavaScript Objects and the BOM

The second week of learning JavaScript properly went a bit slower than intended. Actually, much slower…I think I’ve spend three weeks reviewing the material from the book, doing the Codecademy exercises, working through the relevant Treehouse courses, and playing around with things on my own. Progress has been slow, but I think it’s been really important for me to try to apply what I’ve been learning as I’m learning it (I’ll share a few examples later).

I really enjoyed Week 2: Learn JavaScript Objects, the Browser Object Model (BOM), and Events; Learn jQuery. There was a lot of repetition around objects, especially in the Codecademy exercises, but overall, the “week” was great because I felt like I’m getting into the part of JavaScript that I will find most useful–manipulating the Document Object Model, and making truly interactive websites.

Javascript objects

In week two, I learned that JavaScript is primarily an object-based language. Initially, this struck fear in me…what if this is a repeat of trying to learn Java in university (pure trauma)? But it turns out my fears were completely unfounded.

The book, Codecademy, and Treehouse all went into great detail about objects–how to create them, how to access their properties using dot or array notation, and how to create methods for the objects. I was starting to see how my learning in the first week was coming together, and how I was building onto it by learning about objects.

I learned that there are several ways to create an object:

  • Using the object literal
    var thing = {};
  • Using the object object
    var thing = new Object();
  • Creating a reference type
    function Thing( param ) {};
    var thing = new Thing();

At this point, it’s probably been two weeks since I went through the lessons on objects, and while I don’t want to say that I forgot what I learned, I am feeling a bit fuzzy. Hopefully getting back into learning will refresh my memory, and I can start getting an idea of how objects can be utilized in more real-world circumstances.

The Browser Object Model (BOM) and Events

There was a very short lesson in the book on the Browser Object Model (BOM), which is different from the Document Object Model (DOM), despite sounding similar. The BOM refers mostly to very general things that can happen within the context of using a web browser. This includes things like tracking your location to provide you with a better user experience, or serving up a different pages depending upon your browser version and what’s supported. It was actually pretty interesting stuff, even if I’m not entirely sure how I’ll use it yet.

jQuery

Learning jQuery was the real highlight of Week 2. I’ve been dabbling in jQuery every once in awhile since I’ve been working with WordPress. Prior to learning jQuery, I would look at jQuery code, vaguely understand it, but felt so lost when it came to trying to come up with jQuery code on my own because I didn’t completely understand what was going on. After Week 2 of Learning JS Properly, however, I feel much more confident when it comes to writing jQuery.

The book did a nice job of introducing jQuery as a JS library, which makes working across browsers easier and makes manipulating the Document Object Model (DOM) easier. The only problem is that jQuery is a rather late chapter in the book, and assumes you’re reading the book in order. So the examples discuss working with AJAX (part of JavaScriptIs.sexy’s Week 5 learning), and the DOM (also Week 5) make a little less sense, and the examples in the book are not at all helpful. Still, it was useful for introducing jQuery, and I will probably go back to it once I’ve completed Week 5.

Codecademy, on the other hand, was actually pretty damn good for jQuery. I found it moved a lot faster for jQuery than it did JavaScript, and because they focused mostly on jQuery as a means of manipulating the DOM, I felt like I was finally doing something fun and useful with my new skills. In fact, after finishing the Codecademy jQuery course, I created a little pen about my cats (naturally):

Treehouse’s jQuery course was also very good. It moved a bit slowly at times, but one of the most important things I got from that course was how to think about what I was hoping to accomplish with jQuery, and using that starting point to search the jQuery documentation for the functions/methods that would get me the end result. For me, this was game changing, and addressed that gap of not knowing where to start. The second part of Treehouse’s jQuery course went through jQuery widgets including Animsition, Sticky.js, and Slick.js, which I thought was fun and helpful since I’ve been working with various jQuery widgets for awhile.

For those using Beginning JavaScript, 5th Edition

If you’re following along and also trying to learn JavaScript properly, and you happen to also be using Beginning JavaScript, 5th Edition, you’ll notice that there are a few differences in chapter numbers between the forth and fifth editions. Here are the equivalent chapters between the forth and fifth editions:

4th Edition 5th Edition
Chapter 5, JavaScript — An Object-Based Language [icon name=”arrow-right” class=”” unprefixed_class=””] Chapter 5, JavaScript — An Object-Based Language
Chapter 6, Programming the Browser [icon name=”arrow-right” class=”” unprefixed_class=””] Chapter 8, Programming the Browser
Chapter 15, JavaScript Frameworks [icon name=”arrow-right” class=”” unprefixed_class=””] Chapter 16, jQuery

Learning JavaScript

One of my main goals for 2016 is to learn JavaScript. Not only because it’s being touted as the future of WordPress, but also because I felt like JavaScript (JS) was one of those very critical web languages that was missed when I took web design and development courses during my Graphic and Interactive Design program. I’ve also come across some really instances where my lack of JS knowledge has been a bit of a roadblock, not to mention the downright awesome shit that can be done with JSt. Have you seen ustwo’s REST API-driven site? It’s fucking amazing and totally driven by JavaScript.

The Plan

If you’re going to learn something, and learn it well, you need a plan, right? After a bit of digging, and I found a really great resource called JavaScript.isSexy (oh yeah it is!). They have a [free!] program they call, How to Learn JavaScript Properly, and it’s totally legit. Not only is there a plan for total n00bs like myself, but they have a guide for experienced developers too (which my husband is currently working through–the family that learns JS together, stays together, amiright?!). So no need to start with the very basics of programming if you already know a thing or two!

The resources they suggest for the beginner track are rather simple, and the only expense is the book:

  1. A book: Beginning JavaScript
  2. Four articles on JavaScriptIsSexy.com
  3. Four Codecademy tracks
  4. Four Code School tracks

Week 1 Review

I started working through Week 1: Making a Website with HTML and CSS; Learn JavaScript Data Types, Functions, Control Flow, and Loops last week. As someone who’s been working with WordPress daily for the past year or so, writing loads of functions, loops, etc., I found this to be a relatively easy, yet interesting week.

The thing is, almost all of my PHP experience has been trial by fire. As in, I have an idea of what I want to do, and roughly how I want to do it, and then proceed to do a reasonable amount of Google searching to find the answer, or better yet, have my code reviewed by a fellow WordPress developer who could help me work through problems and optimize my code. But this week’s reading in on JavaScript has helped me better understand some of the things I’ve been doing. Like for loops, for example. To get multiple images in my portfolio posts, I use a for loop to cycle through the images and generate the markup like this:

https://gist.github.com/carrieforde/8ced7b37b5c62f4bac1a

I had a rough idea what that for loop was doing before, but now I definitely understand what it’s doing, and that’s pretty awesome. Not only that, but I’ve got conditional logic down (if / else if / else) as well as other types of loops (while / do…while).

Every time I learn something new, I try to challenge myself to come up with an original exercise to practice my new JS skills. Here’s my favorite from this week (note: if you try to run this, it will create some pop-ups for user input):

Improving this Course

I know it’s early days, and I’m really stoked about this course and the track I’m on, but I definitely think there are a few things to that could use improvement.

  1. The website refers to Edition 4 of Beginning JavaScript, and I decided to purchase Edition 5. Not a big deal, but there are definitely differences in chapters in the latest edition, and it might be helpful if the Beginning track was updated to reflect the latest edition of the book.
  2. Codecademy is really boring. They basically spoon-feed you information, and it becomes tedious really quickly. I’ve been finding that the best part of Codecademy are end of track challenges.
  3. Consider swapping Codecademy for Treehouse. Yes, I know one advantage to this plan is that the only expense is the book, but the Treehouse Full-Stack JavaScript track is legit, and a really nice supplement to this course. So for now, I’ll be using the book, Codecademy, and Treehouse as resources.

On to Week 2…

I’m really stoked about Week 2: Learn JavaScript Objects, the Browser Object Model (BOM), and Events; Learn jQuery. I’ve dabbled a very small amount in jQuery over the past few months, and what I’ve tried and learned so far has been awesome (check out the category and archive toggles on Clayton Gerard’s site for some nifty jQuery slideToggle action), and I’m looking really forward to learning some new tricks to improve the interactivity of sites I create going forward.

Is anyone else out there trying to learn JavaScript? What sources are you finding useful?