BDD in JavaScript: Getting Started with Cucumber and Gherkin

By now, everyone has heard about Test Driven Development (TDD), and the benefits that this can have on your product and your development lifecycle. It’s a no-brainer really. Every time you write a test for a piece of code, you know that code works. And, what’s more, you will know in the future if that code breaks.
Behavior Driven Development (BDD) is an extension to this concept, but instead of testing your code you are testing your product, and specifically that your product behaves as you desire it to.
In this article, I’m going to show you how to get up and running with Cucumber, a framework that runs automated acceptance tests written in a BDD style. The advantage of these tests is that they can written in plain English and consequently understood by non-technical people involved in a project. After reading, you will be in a position to decide if Cucumber is a good fit for you and your team and to start writing acceptance tests of your own.
Ready? Then let’s dive in.
BDD vs TDD — so, What’s the Difference?
Primarially in the way that tests are structured and written.
In a TDD setting, the tests are written, maintained and understood by the developers who wrote the code they are testing. It might well be that nobody else ever needs to read the tests at all, and that’s fine.
In a BDD setting, the tests need to be understood by a lot more than just the developer writing the functionality. There are many more stakeholders who have an interest that the product behaves as it should.
These might include QA people, product analysts, sales, even upper management.
This means that, in an ideal world, BDD tests need to be written in a way that anyone who understands the product will be able to pick up the tests and understand them as well.
It’s the difference between:
const assert = require(‘assert’);
const webdriver = require(‘selenium-webdriver’);
const browser = new webdriver.Builder()
.withCapabilities({‘browserName’: ‘chrome’ })

assert.equal(19, links.length); // Made up number

Given I have opened a Web Browser
When I load the Wikipedia article on "Wiki"
Then I have "19" Wiki Links

The two tests do exactly the same thing, but one is actually human readable and the other is only readable by someone who knows both JavaScript and Selenium.
This article will show you how you can implement BDD Tests in your JavaScript project, using the Cucumber.js framework, allowing you to benefit from this level of testing for your product.
What Is Cucumber / Gherkin?
Cucumber is a testing framework for behavior driven development. It works by allowing you to define your tests in Gherkin form, and makes these gherkins executable by tying them to code.
Gherkin is the Domain Specific Language (DSL) that is used for writing Cucumber tests. It allows for test scripts to be written in a human readable format, which can then be shared between all of the stakeholders in the product development.
Gherkin files are files that contain tests, written in the Gherkin language. These files typically have a .feature file extension. The contents of these Gherkin files are often referred to as simply "gherkins".
In a Gherkin defined test, you have the concept of features and scenarios. These are analogous to test suites and test cases in other testing frameworks, allowing for a clean way to structure your tests.
A scenario is literally just a single test. It should test exactly one thing in your application.
A feature is a group of related scenarios. As such, it will test many related things in your application. Ideally the features in the Gherkin files will closely map on to the Features in the application — hence the name.
Every Gherkin file contains exactly one feature, and every feature contains one or more scenarios.
Scenarios are then comprised of steps, which are ordered in a specific manner:

Given – These steps are used to set up the initial state before you do your test
When – These steps are the actual test that is to be executed
Then – These steps are used to assert on the outcome of the test

Ideally each scenario should be a single test case, so the number of When steps should be kept very small.
Steps are entirely optional. If you have no need to set anything up at all, you might have no Given steps, for example.
Gherkin files are designed to be human readable, and to give benefit to anyone involved in the product development. This includes non-technical people, so the Gherkin files should always be written in business language and not technical language. This means, for example, that you do not refer to individual UI components, but instead describe the product concepts that you are wanting to test.
An Example Gherkin Test
The following is an example Gherkin for searching Google for Cucumber.js
Given I have loaded Google
When I search for "cucumber.js"
Then the first result is "GitHub – cucumber/cucumber-js: Cucumber for JavaScript"

Straight away we can see that this test tells us what to do and not how to do it. It is written in a language that makes sense to anyone reading it, and — importantly — that will most likely be correct no matter how the end product might be tweaked. Google could decide to completely change their UI, but as long as the functionality is equivalent then the Gherkin is still accurate.
You can read more about Given When Then on the Cucumber wiki.
Once you have written your test cases in Gherkin form, you need some way to execute them. In the JavaScript world, there is a module called Cucumber.js that allows you to do this. It works by allowing you to define JavaScript code that it can connect to the various steps defined inside of your Gherkin files. It then runs the tests by loading the Gherkin files and executing the JavaScript code associated with each step in the correct order.
For example, in the above example you would have the following steps:
Given(‘I have loaded Google’, function() {});
When(‘I search for {stringInDoubleQuotes}’, function() {});
Then(‘the first result is {stringInDoubleQuotes}’, function() {});

Don’t worry too much about what all of this means – it will be explained in detail later. Essentially though, it defines some ways that the Cucumber.js framework can tie your code to the steps in your Gherkin files.
Including Cucumber.js in Your Build
Including Cucumber.js in your build is as simple as adding the cucumber module to your build, and then configuring it to run. The first part of this is as simple as:
$ npm install –save-dev cucumber

The second of these varies depending on how you are executing your build.
Running by Hand
Executing Cucumber by hand is relatively easy, and it’s a good idea to make sure you can do this first because the following solutions are all just automated ways of doing the same.
Once installed, the executable will be ./node_modules/.bin/cucumber.js. When you run it, it needs to know where on the file system it can find all of its required files. These are both the Gherkin files and the JavaScript code to be executed.
By convention, all of your Gherkin files will be kept in the features directory, and if you don’t instruct it otherwise then Cucumber will look in the same directory for the JavaScript code to execute as well. Instructing it where to look for these files is a sensible practice however, so that you have better control over your build process.
For example, if you keep all of your Gherkin files in the directory myFeatures and all of your JavaScript code in mySteps then you could execute the following:
$ ./node_modules/.bin/cucumber.js ./myFeatures -r ./mySteps

The -r flag is a directory containing JavaScript files to automatically require for the tests. There are other flags that might be of interest as well — just read the help text to see how they all work: $ ./node_modules/.bin/cucumber.js –help.
These directories are scanned recursively so you can nest files as shallowly or deeply as makes sense for your specific situation.
npm scripts
Once you have got Cucumber running manually, adding it to the build as an npm Script is a trivial case. You simply need to add the following command — without the fully qualified path, since npm handles that for you — to your package.json as follows:
"scripts": {
"cucumber": "cucumber.js ./myFeatures -r ./mySteps"

Once this is done, you can execute:
$ npm run cucumber

And it will execute your Cucumber tests exactly as you did before.
There does exist a Grunt plugin for executing Cucumber.js tests. Unfortunately it is very out of date, and doesn’t work with the more recent versions of Cucumber.js, which means that you will miss out on a lot of improvements if you use it.
Instead, my preferred way is to simply use the grunt-shell plugin to execute the command in the exact same way as above.
Once installed, configuring this is simply a case of adding the following plugin configuration to your Gruntfile.js:
shell: {
cucumber: {
command: ‘cucumber.js ./myFeatures -r ./mySteps’

And now, as before, you can execute your tests by running grunt shell:cucumber.
Continue reading %BDD in JavaScript: Getting Started with Cucumber and Gherkin%


How to Create Interactive JavaScript Charts from Custom Data Sets

Charts are a great way of visualizing complex data quickly and effectively. Whether you want to identify a trend, highlight a relationship, or make a comparison, charts help you communicate with your audience in a precise and meaningful manner.
In my previous article — Getting Started with AnyChart: 10 Practical Examples — I introduced the AnyChart library and demonstrated how it is a great fit for your data visualization needs. Today, I want to dig a little deeper and look at AnyChart’s data mapping features which allow you to create beautiful charts from custom data sets with a minimum of fuss.
I also want to look at the many ways you can customize AnyChart to suit your requirements, as well as how you can change the look and feel of AnyChart charts by using themes. There are currently 17 out-of-the-box themes to choose from, or you can create your own. And if you’ve not got the best eye for design, why not buy our book to get a leg up.
As the Head of R&D at AnyChart, I could spend all day talking about this library, but now it’s time to get down to business.
Data Mapping in AnyChart
To facilitate the integration of custom data sources into charting applications, AnyChart has special objects called data sets. These objects act as intermediate containers for data. When data is stored in data sets, AnyChart can track changes to it, analyze it, and work with this data in a more robust and effective manner. In short: interactive JavaScript charts have never been easier!
No matter if you have an array of objects, an array of arrays, or a .csv file, you can use data sets to:

ensure full and explicit control over the series created
define which column is an argument (x-axis)
define which columns hold values for which series
filter data
sort data

Basics of Data Mapping
The best way to learn how data mapping works in AnyChart is to look at an example. Let’s imagine an array with the following custom data set:
var rawData = [
[“A", 5, 4, 5, 8, 1, "bad"],
["B", 7, 1, 7, 9, 2, "good"],
["C", 9, 3, 5, 4, 3, "normal"],
["D", 1, 4, 9, 2, 4, "bad"]

There’s nothing too wild going on here — this kind of custom data structure is common in a lot of existing applications. But now you want to use this array in AnyChart. With many other charting libraries you would be forced to transform the data to a format that the library can work with. Well, with AnyChart things are a lot simpler — just look what we can do. First, load the array into a data set:
var rawData = [
["A", 5, 4, 5, 8, 1, "bad"],
["B", 7, 1, 7, 9, 2, "good"],
["C", 9, 3, 5, 4, 3, "normal"],
["D", 1, 4, 9, 2, 4, "bad"]

var dataSet =;

And then, once the data has been loaded into the data set, the real magic begins: you can now create so called views. These are data sets derived from other data sets.
var rawData = [
["A", 5, 4, 5, 8, 1, "bad"],
["B", 7, 1, 7, 9, 2, "good"],
["C", 9, 3, 5, 4, 3, "normal"],
["D", 1, 4, 9, 2, 4, "bad"]

var dataSet =;

var view1 = dataSet.mapAs({x: 0, value: 1});
var view2 = dataSet.mapAs({x: 0, value: 2});
var view3 = dataSet.mapAs({x: 0, high: 3, low: 4});
var view4 = dataSet.mapAs({x: 0, value: 5, meta: 6});

You’ll notice that when defining a view, you determine which columns from the original array are included and what names these columns get. You can then use them to create whichever kind of charts you like. For example, here’s how to create a pie chart from the custom data in the 5th column.
Note: AnyChart needs only x and value fields to create a pie chart, but the views also contain a meta field with the data from the 6th column. You can map any number of optional fields and use them as you like. For example, these fields can contain additional data to be shown as labels or as tooltips:
anychart.onDocumentLoad(function() {
var rawData = [
["A", 5, 4, 5, 8, 3, "Bad"],
["B", 7, 1, 7, 9, 5, "Good"],
["C", 9, 3, 5, 4, 4, "Normal"],
["D", 1, 4, 9, 2, 3, "Bad"]

var dataSet =;
var view4 = dataSet.mapAs({x: 0, value: 5, meta: 6});

// create chart
var chart = anychart.pie(view4);
chart.title("AnyChart: Pie Chart from Custom Data Set");
chart.labels().format("{%meta}: {%Value}");

And this is what we end up with:
See the Pen AnyChart Pie Chart from Data Set by SitePoint (@SitePoint) on CodePen.

Note: You can find all of the demos in this article as a CodePen collection.

Multi-Series Combination Chart with Custom Data Set
Now, let’s see how we can use the same custom data to create a combination chart with line and range area charts on the same plot. This section is going to be very short since now you know what views are. All you need to do is choose the proper views and create the necessary series explicitly:
anychart.onDocumentLoad(function() {
var rawData = [
["A", 5, 4, 5, 8, 3, "Bad"],
["B", 7, 1, 7, 9, 5, "Good"],
["C", 9, 3, 5, 4, 4, "Normal"],
["D", 1, 4, 9, 2, 3, "Bad"]

var dataSet =;

var view1 = dataSet.mapAs({x: 0, value: 1});
var view2 = dataSet.mapAs({x: 0, value: 2});
var view3 = dataSet.mapAs({x: 0, high: 3, low: 4});

// create chart
var chart = anychart.line();
// create two line series
// create range area series

// set title and draw chart
chart.title("AnyChart: Combined Chart from Data Set");

This is what it looks like:
See the Pen AnyChart Combined Chart from Data Set by SitePoint (@SitePoint) on CodePen.

Continue reading %How to Create Interactive JavaScript Charts from Custom Data Sets%


A Beginner’s Guide to Testing Functional JavaScript

Functional programming and testing. Maybe you’ve given them a try in isolation, but somehow you never made either a part of your regular practice. They may sound innocent by themselves, but together testing and functional programming can create an irresistible temptation, almost compelling you to write cleaner, tighter, more maintainable code.

Well the good news is that working with both techniques together can offer some real advantages. In fact, once you’ve tasted how sweet this combination can be, you might find yourself as addicted to it as I am, and I’d be willing to bet that you’ll be coming back for more.
In this article, I’ll introduce you to the principles of testing functional JavaScript. I’ll show you how to get up and running with the Jasmine framework and build out a pure function using a test-driven approach.
Why Test?
Testing is about making sure that the code in your application does what you expect it to do, and keeps doing what you expect it to do when you make changes so you have a working product when you’re done. You write a test that defines your expected functionality under a defined set of circumstances, run that test against the code, and if the result isn’t what the test says it should be, you get a warning. And you keep getting that warning until you’ve fixed your code.
Then you get the reward.
And yes, it will make you feel good.
Testing comes in a lot of flavors, and there is room for healthy debate about where the borders are drawn, but in a nutshell:

Unit tests validate the functionality of isolated code
Integration tests verify the flow of data and the interaction of components
Functional tests look at the behavior of the overall application

Note: Don’t get distracted by the fact that there’s a type of testing called functional testing. That’s not what we’ll be focusing on in this article about testing functional JavaScript. In fact, the approach you’ll use for functional testing of the overall behavior of an application probably won’t change all that much whether or not you’re using functional programming techniques in your JavaScript. Where functional programming really helps out is when you’re building your unit tests.
You can write a test at any point in the coding process, but I’ve always found that its most efficient to write a unit test before writing the function you’re planning to test. This practice, known as test-driven development (TDD), encourages you to break down the functionality of your application before you start writing and determine what results you want from each section of code, writing the test first, then coding to produce that result.
A side benefit is that TDD often forces you to have detailed conversations with the people who are paying you to write your programs, to make sure that what you’re writing is actually what they’re looking for. After all, it’s easy to make a single test pass. What’s hard is determining what to do with all the likely inputs you’re going to encounter and handle them all correctly without breaking things.
Why Functional?
As you can imagine, the way you write your code has a lot to do with how easy it is to test. There are some code patterns, such as tightly coupling the behavior of one function to another, or relying heavily on global variables, that can make code much more difficult to unit test. Sometimes you may have to use inconvenient techniques such as “mocking" the behavior of an external database or simulating a complicated runtime environment in order to establish testable parameters and results. These situations can’t always be avoided, but it is usually possible to isolate the places in the code where they are required so that the rest of the code can be tested more easily.
Functional programming allows you to deal with the data and the behavior in your application independently. You build your application by creating a set of independent functions that each work in isolation and don’t rely on external state. As a result, your code becomes almost self-documenting, tying together small clearly defined functions that behave in consistent and understandable ways.
Functional programming is often contrasted against imperative programming and object-oriented programming. JavaScript can support all of these techniques, and even mix-and-match them. Functional programming can be a worthwhile alternative to creating sequences of imperative code that track the state of the application across multiple steps until a result is returned. Or building your application out of interactions across complex objects that encapsulate all of the methods that apply to a specific data structure.
How Pure Functions Work
Functional programming encourages you to build your application out of tiny, reusable, composable functions that just do one specific thing and return the same value for the same input every single time. A function like this is called a pure function. Pure functions are the foundation of functional programming, and they all share these three qualities:
Continue reading %A Beginner’s Guide to Testing Functional JavaScript%


Redux Logging in Production with LogRocket

Setting up LogRocket
Setting up LogRocket is easy, and only requires adding a few lines of code to your app:

Install with npm: npm i –save logrocket.
Create a free account at, and take note of your application id.
Initialize LogRocket in your app:
import LogRocket from ‘logrocket’;
// Initialize LogRocket with your app ID

Add the Redux middleware.
import { applyMiddleware, createStore } from ‘redux’;
const store = createStore(
reducer, // your app reducer
applyMiddleware(middlewares, LogRocket.reduxMiddleware()),

That’s it for the basic setup- this is all you need to get started with LogRocket!
LogRocket also has plugins for alternate Flux implementations like ngrx and vuex, which you can read about here.
Replaying User Sessions

Replaying a session in LogRocket is like seeing it happen in your own browser. You can inspect Redux actions with the full action payload as well as the previous and next states.

LogRocket captures both network requests and responses and lets you dig in to specific requests and see the headers and body. The waterfall chart shows timings, making it easy to see which requests were slow, or if a potential race condition occurred.

Sometimes Redux logs alone aren’t enough to understand a bug, especially when dealing with user-reported issues. LogRocket’s video replay helps here by letting you see exactly what a user saw in your app.
Since this video is actually a reconstruction of the DOM (and not a real video) you can inspect HTML/CSS to understand visual bugs, or play at 2x speed to gain a quick understanding of what a user did in the app when handling support issues.
Integrating Redux Logging into Your Workflow
Being able to replay user sessions and see Redux logs is helpful across the development workflow.
Continue reading %Redux Logging in Production with LogRocket%


Introduction to FuseBox — a Faster, Simpler Webpack Alternative

Webpack has arguably become the de facto JavaScript module bundler, but it has a reputation for being confusing and difficult to learn. In this article I want to present a faster, simpler Webpack alternative — FuseBox. FuseBox is a next generation ecosystem of tools that provides for all of the requirements of the development lifecycle. […]
Continue reading %Introduction to FuseBox — a Faster, Simpler Webpack Alternative%


What Is Event Bubbling in JavaScript? Event Propagation Explained

Event bubbling is a term you might have come across on your JavaScript travels. It relates to the order in which event handlers are called when one element is nested inside a second element, and both elements have registered a listener for the same event (a click, for example).
But event bubbling is only one piece of the puzzle. It is often mentioned in conjunction with event capturing and event propagation. And a firm understanding of all three concepts is essential for working with events in JavaScript — for example if you wish to implement the event delegation pattern.
In this post I will explain each of these terms and demonstrate how they fit together. I will also show you how a basic understanding of JavaScript event flow can give you fine-grained control over your application. Please note that this is not a primer on events, thus a familiarity with the topic is assumed. If you’d like to learn more about events in general, why not check out our book: JavaScript: Novice to Ninja.
What is the Event Propagation?
Let’s start with event propagation. This is the blanket term for both event bubbling and event capturing. Consider the typical markup to build a list of linked images, for a thumbnails gallery for example:

    <li><a href=”…"><img src="…" alt=""></a>
    <li><a href="…"><img src="…" alt=""></a>

    <li><a href="…"><img src="…" alt=""></a>

    A click on an image does not only generate a click event for the corresponding IMG element, but also for the parent A, for the grandfather LI and so on, going all the way up through all the element’s ancestors, before terminating at the window object.
    In DOM terminology, the image is the event target, the innermost element over which the click originated. The event target, plus its ancestors, from its parent up through to the window object, form a branch in the DOM tree. For example, in the image gallery, this branch will be composed of the nodes: IMG, A, LI, UL, BODY, HTML, document, window.

    Note that window is not actually a DOM node but it implements the EventTarget interface, so, for simplicity, we are handling it like it was the parent node of the document object.

    This branch is important because it is the path along which the events propagate (or flow). This propagation is the process of calling all the listeners for the given event type, attached to the nodes on the branch. Each listener will be called with an event object that gathers information relevant to the event (more on this later).
    Remember that several listeners can be registered on a node for the same event type. When the propagation reaches one such node, listeners are invoked in the order of their registration.
    It should also be noted that the branch determination is static, that is, it is established at the initial dispatch of the event. Tree modifications occurring during event processing will be ignored.
    The propagation is bidirectional, from the window to the event target and back. This propagation can be divided into three phases:

    From the window to the event target parent: this is the capture phase
    The event target itself: this is the target phase
    From the event target parent back to the window: the bubble phase

    What differentiates these phases is the type of listeners that are called.
    The Event Capture Phase
    In this phase only the capturer listeners are called, namely, those listeners that were registered using a value of true for the third parameter of addEventListener:
    el.addEventListener(‘click’, listener, true)

    If this parameter is omitted, its default value is false and the listener is not a capturer.
    So, during this phase, only the capturers found on the path from the window to the event target parent are called.
    Continue reading %What Is Event Bubbling in JavaScript? Event Propagation Explained%


How to Make a Simple JavaScript Quiz

“How do I make a JavaScript quiz?" — this is one of the most common questions I hear from people who are learning web development, and for good reason. Quizzes are fun! They are a great way of learning about new subjects and allow you to engage your audience in a fun, yet playful manner.

And coding your own JavaScript quiz is a fantastic learning exercise. It teaches you how to deal with events, handle user input, manipulate the DOM, provide the user with feedback and keep track of their score (for example, using client-side storage). And when you have your basic quiz, there are a whole host of possibilities to add more advanced functionality, such as pagination. I go into this at the end of the article.
In this tutorial I will walk you though creating a multi-step JavaScript quiz which you will be able to adapt to your needs and add to your own site. If you’d like to see what we’ll be ending up with, you can skip ahead and see the working quiz.
Things to be Aware of Before Starting
A few things to know before starting:

This tutorial is entirely on the front end, meaning that the data is in the browser and someone who knows how to look through the code can find the answers. For serious quizzes, the data needs to be handled through the back end, which is beyond the scope of this tutorial.
The code in this article uses ES2015 syntax, meaning the code will not be compatible with any versions of Internet Explorer. However it does work for modern browsers, including Microsoft Edge.
If you need to support older browsers, I’ve written a JavaScript quiz tutorial that’s compatible back to IE8. Or, if you’d like a refresher on ES2015, check out this course by Darin Haener over on SitePoint Premium.
You’ll need some familiarity with HTML, CSS, and JavaScript, but each line of code will be explained individually.

The Basic Structure of Your JavaScript Quiz
Ideally, we want to be able to list our quiz’s questions and answers in our JavaScript code and have our script automatically generate the quiz. That way, we won’t need to write a bunch of repetitive markup, and we can add and remove questions easily.
To set up the structure of our JavaScript quiz, we’ll need to start with the following HTML:


to hold the quiz
A <button> to submit the quiz
A <div> to display the results

Here’s how that would look:
<div id="quiz"></div>
<button id="submit">Submit Quiz</button>
<div id="results"></div>

Then we can select these HTML tags and store references to these elements in variables like so.:
const quizContainer = document.getElementById(‘quiz’);
const resultsContainer = document.getElementById(‘results’);
const submitButton = document.getElementById(‘submit’);

Next we’ll need a way to build a quiz, show results, and put it all together. We can start by laying out our functions, and we’ll fill them in as we go:
function buildQuiz(){}

function showResults(){}

// display quiz right away

// on submit, show results
submitButton.addEventListener(‘click’, showResults);

Here, we have functions to build the quiz and show the results. We’ll run our buildQuiz function immediately, and we’ll have our showResults function run when the user clicks the submit button.
Displaying the Quiz Questions
The next thing our quiz needs are some questions to display. We’ll use object literals to represent the individual questions and an array to hold all of the questions that make up our quiz. Using an array will make the questions easy to iterate over.
const myQuestions = [
question: "Who is the strongest?",
answers: {
a: "Superman",
b: "The Terminator",
c: "Waluigi, obviously"
correctAnswer: "c"
question: "What is the best site ever created?",
answers: {
a: "SitePoint",
b: "Simple Steps Code",
c: "Trick question; they’re both the best"
correctAnswer: "c"
question: "Where is Waldo really?",
answers: {
a: "Antarctica",
b: "Exploring the Pacific Ocean",
c: "Sitting in a tree",
d: "Minding his own business, so stop asking"
correctAnswer: "d"

Feel free to put in as many questions or answers as you want.
Now that we have our list of questions, we can show them on the page. We’ll go through the following JavaScript line by line to see how it works:
function buildQuiz(){
// we’ll need a place to store the HTML output
const output = [];

// for each question…
(currentQuestion, questionNumber) => {

// we’ll want to store the list of answer choices
const answers = [];

// and for each available answer…
for(letter in currentQuestion.answers){

// …add an HTML radio button
<input type="radio" name="question${questionNumber}" value="${letter}">
${letter} :

// add this question and its answers to the output
`<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join(”)} </div>`

// finally combine our output list into one string of HTML and put it on the page
quizContainer.innerHTML = output.join(”);

First, we create an output variable to contain all the HTML output including questions and answer choices.
Next, we can start building the HTML for each question. We’ll need to loop through each question like so:
myQuestions.forEach( (currentQuestion, questionNumber) => {
// here goes the code we want to run for each question

Continue reading %How to Make a Simple JavaScript Quiz%


Create an Animated Sticky Navigation Menu with Vanilla JavaScript

When adding a navigation menu to a webpage, there are a lot of things to take into consideration. For example where to position it, how to style it, how to make it responsive. Or maybe you want to add some kind of animation to it (tastefully, of course). At this point you might be tempted to grab a jQuery plugin which does most of that for you. But that needn’t be! It’s actually pretty simple to create your own solution in a few lines of code.
In this post, I will demonstrate how to create an animated, sticky navigation menu with vanilla JavaScript, CSS and HTML. The final product will slide up out of your way as you scroll down the page, then slide back into view (with a stylish see-through effect) when you scroll back up. This is a technique used by such popular sites, such as Medium and Hacker Noon.
After reading you’ll be able to employ this technique in your own designs, hopefully to great effect. There’s a demo at the end of the article for the impatient.
The Basic HTML Structure
The following is the skeleton HTML code that we will be working with. Nothing too exciting going on here.

How to Write Shell Scripts with JavaScript

This week I had to upgrade a client’s website to use SSL. This wasn’t a difficult task in itself — installing the certificate was just the click of a button — yet once I had made the switch, I was left with a lot of mixed content warnings. Part of fixing these meant that I had to go through the theme directory (it was a WordPress site) and identify all of the files in which assets were being included via HTTP.
Previously, I would have used a small Ruby script to automate this. Ruby was the first programming language I learned and is ideally suited to such tasks. However, we recently published an article on using Node to create a command-line interface. This article served to remind me that JavaScript has long since grown beyond the browser and can (amongst many other things) be used to great effect for desktop scripting.
In the rest of this post, I’ll explain how to use JavaScript to recursively iterate over the files in a directory and to identify any occurrences of a specified string. I’ll also offer a gentle introduction to writing shell scripts in JavaScript and put you on the road to writing your own.
Set Up
The only prerequisite here is Node.js. If you don’t have this installed already, you can head over to their website and download one of the binaries. Alternatively, you can use a version manager such as nvm. We’ve got a tutorial on that here.
Getting Started
So where to begin? The first thing we need to do is iterate over all of the files in the theme directory. Luckily Node’s native File System module comes with a readdir method we can use for that. It takes the directory path and a callback function as parameters. The callback gets two arguments (err and entries) where entries is an array of the names of the entries in the directory excluding . and .. — the current directory and the parent directory, respectively.
const fs = require(‘fs’);

function buildTree(startPath) {
fs.readdir(startPath, (err, entries) => {


If you’re following along with this, save the above in a file named search_and_replace.js and run it from the command line using node search_and_replace.js. You’ll also need to adjust the path to whichever directory you are using.
Adding Recursion
So far so good! The above script logs the directory’s top level entries to the console, but my theme folder contained subdirectories which also had files that needed processing. That means that we need to iterate over the array of entries and have the function call itself for any directories it encounters.
To do this, we first need to work out if we are dealing with a directory. Luckily the File System module has a method for that, too: lstatSync. This returns an fs.Stats object, which itself has an isDirectory method. This method returns true or false accordingly.
Continue reading %How to Write Shell Scripts with JavaScript%


Back to Basics: JavaScript Operators, Conditionals & Functions

Table of Contents JavaScript Operators Assignment Operators Arithmetic Operators Addition Subtraction Multiplication Division Modulus Increment Decrement Comparison Operators Equal Strict Equal Not Equal Strict Not Equal Less Than Less Than or Equal To Greater Than Greater Than or Equal To Logical Operators And Or Not Operator Precedence Conditional Statements If / Else If Else Else […]
Continue reading %Back to Basics: JavaScript Operators, Conditionals & Functions%