Tag: JavaScript

This follow up to the basic Webpack 3 Sass preprocessor workflow I wrote about here includes how to handle processing of relative URLs in the Sass for things like fonts and images. Ken Wheeler’s popular Slick carousel contains these asset types in its Sass, so let’s use that for this exercise.

Getting Started

Enter npm init to interactively create a package.json file. Accepting the default options is okay for now. The metadata in this file can be updated later as needed.

npm init

A package.json file should now exist in the root of the project. This json file is used to manage the project dependencies, set configuration options for supported modules and run npm scripts.

Create an index.html file in the project root with an unordered list of placeholder images. Include the dist/style.css link in the document head and dist/app.js link before the closing body tag. Add a class attribute with the value slider to the unordered list element. This sets it apart for selecting with our script and style code: <ul class="slider">

Note that the ellipsis … in the code snippet above is not a part of the actual code and is there only to denote code that is being skipped and not applicable to the example. Keep this in mind when you encounter an ellipsis in the remaining snippets. To view the entire file, examine the source code.

Using the npm-run-scripts alias npm run to execute the build.

npm run build

For development, use npm run dev to watch for changes and build incrementally when changes are saved.

You should now have a new dist folder in the root of the project where the Webpack bundle is output.

How to layout and lazy load images in a flexible grid similar to how facebook displays them in a post. Selected images open a lightbox for previewing within a carousel. Image alt text is converted into a caption below the image.

Enter npm init to interactively create a package.json file. Accepting the default options is okay for now. The metadata in this file can be updated later as needed.

npm init

A package.json file should now exist in the root of the project. This file will be used later with the npm command when installing modules and running scripts.

Create an index.html file in the root of the project. Add an unordered list of images to the body with the .photogrid style class. For lazy image loading, instead of using a src attribute, put the image path in a data attribute named data-src. Also include the dist/style.css link in the document head and dist/app.js link before the closing body tag.

Lazy Image Loading

Create a folder named src. In that folder, create both a js folder and a sass folder.

Within the js folder, create an index.js app entry point file and a lazyimage.js module file.

Within the sass folder, create a style.scss file that will be used as the entry point for Sass processing. Add three Sass partials, _base.scss, _photogrid.scss and _lazyimage.scss. The leading underscore in the filename denotes that the file is a Sass partial and therefore will only be processed if imported.

Google Map application that uses a draggable location marker to set address, longitude and latitude geocode inputs. This post covers some of the Webpack tools for both a local development environment and production build of the app constructed of a few JavaScript modules and css.

For application details, I encourage you to read my Google Maps API with Browserify post from a year ago. The following overview highlights building the refactored code with Webpack. This refactor brings the application more up to date with ES6 standards. Other changes include the removal of jQuery as a dependency. All of the source code is available for download and browsing at GitHub.

NPM

Here is the updated package.json for installing webpack, loaders and other dependencies. This file also defines scripts to start and run commands.

The npm start command is using the cross-env plugin to set the Node environment variable properly for the platform. The webpack-dev-server then bundles the modules and launches a static web server inline for live reloading.

The npm run build command uses cross-env to set the environment flag. Then webpack bundles the modules according to the webpack.config below optimized with a source-map for production.

In the webpack.config file, the output.publicPath property is used by the webpack-dev-server to determine where the bundles should be served from.

The devtool property controls if and how source maps are generated. eval-source-map is for faster rebuild when in development. In production mode, devtool is set to use the appropriate source-map style instead.

To test drive the app and experiment with the dev server and live reloading, follow these steps assuming you have Node.js installed.

This post documents how to add Ajax form validation to Laravel User Authentication that is generated by the Artisan console.

Requirements

An instance of Laravel 5.2 setup for local development is required. Head over to the Laravel 5.2 docs to get setup as needed. For my setup on Windows 10, I am using XAMPP 5.6.12 which meets all of the requirements. Note that your document root will need to be the laravel/public directory. Here is the virtual hosts configuration I am using for Laravel.

User.php

Throughout this tutorial you will encounter an ellipsis … in the code examples. These are not a part of the code and are there only to denote code that is being skipped and not applicable to the example. To view the entire file, examine the source code.

Edit app/Http/Controllers/Auth/AuthController.php, update use App\User to use App\Models\User.

Database

Edit the .env configuration file to access the database. I have already created a database named laravel on the MySQL Server that is part of XAMPP.

.env

DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

The settings above are the only ones I needed to update for my setup, I do not have a password set for MySQL Server and will just use the root account for local development. Now run php artisan migrate to create the tables for users.

Run Migration

Validation Rules

The validation rules are currently located in the AuthController, I would like to be able to share them with the new controller we will create later for ajax validation. Since these rules apply to the User, and that model is already being used by the AuthController, it seeems to be the best place for them.

Edit app/Models/User.php, adding the public function rules() to the class.

Edit app/Http/Controllers/Auth/AuthController.php. Locate the validator function and replace the array of rules being passed to the Validator make method with a call to the newly created rules method in our User model.

Before going further, now would be a good time to test registering a new user, login, logout etc.. to make sure everyting works. All we have done so far aside from the code that artisan generated is move the User model and move the validation rules from the AuthController into it.

The next page covers using the api middleware in routes, creating the Validation\UserController for handling the XHR request and finally updating the templates and adding the JavaScript for Ajax.

Resource

This post documents how to use local JavaScript modules with Browserify and the Google Maps JavaScript API. In this example, the Google Map contains a marker that can be dragged to reset the browser form with the marker position location data. Additionally, Browserify shim is used to require jQuery since it is already being loaded from a CDN.

Application Entry Point

The index module is the starting point for the map application. The module dependency requirements are defined followed by a call to the load function exported by the gapi module. gapi.load uses a callback function before the location.init.

index.js

Google Map JavaScript API

Loading the Google Maps JavaScript API requires a global callback. For this I have created a jsonp module which accepts three parameters, a URL (url), a global callback function name (callbackname), and a callback function (done).

Location Module

The location module initiates the google map using the gmap.init function exported by the gmap module. The gmap.init callback results data is handled by the location module to populate the address inputs.

Create a gulpfile.js in the project root to define and configure the Gulp tasks. The default task is simply gulp. When gulp is executed, it will run the bundle task, start a local web server with livereload and open the app in a web browser.

After discovering yet another interesting Javascript framework for the web application development recently (Vue.js), I decided to put together this short list of some the emerging and more popular frameworks out there today for building user interfaces.

Emerging

Mithril is a light-weight robust MVC framework with no dependencies, a small API and small learning curve. Mithril implements a virtual DOM tree similar to React.js, however Mithril’s uncompiled templates run natively in the browser and compile into static Javascript data structures. Mithril.js was initially released in March, 2014 by Leo Horie. Source available at https://github.com/lhorie/mithril.

Popular

AngularJS a framework by Google that binds HTML (views) to Javascript objects (models). AngularJS usage rivals that of BackboneJS, according to JavaScript analytics service Libscore, AngularJS is used on over 10,000 websites including The Weather Channel, Lego, Intel, Sprint and ABC News. AngularJS was initially released in September 2009 by Misko Hevery. Source available at https://github.com/angular/angular.js.

File

Version

Size

angular.min.js

1.4.8

145 kb

Ember.js is a framework based on the model-view-controller (MVC) pattern and follows Convention over Configuration (CoC). Ember has a large API that covers traditional MVC patterns and a broad range of helper utilities. Ember 2.0 has a brand new high performance rendering engine named Glimmer, and server-side rendering is provided with FastBoot. After Handlebars in 2010, on December 8, 2011, Yehuda Katz released Ember.js. Source available at https://github.com/emberjs/ember.js.

File

Version

Size

ember.min.js

2.2.0

435 kb

React.js is the framework that powers Facebook and Instagram’s user interface and is one of the fastest growing JavaScript frameworks today. Features include one-way data flow and a virtual-DOM using an in-memory data structure cache process so only applicable nodes on the client browser’s DOM are updated for high performance complex user interfaces. React.js was created by Jordan Walke, a ‎Software Engineer at Facebook and was initially released in May, 2013 by Facebook and Instagram. Source available at https://github.com/facebook/react.

File

Version

Size

react.min.js

0.14.6

133 kb

react-dom.min.js

0.14.6

1 kb

Total

134 kb

Backbone.js is a light weight framework that provides a RESTful JSON interface for data models, views, collections, and events. Backbone.js is used on over 12,000 websites according to Libscore including Linkedin, Pinterest, ESPN, Walmart, Target and Best Buy. Backbone.js was initially released on October 13, 2010 by Jeremy Ashkenas. Source available at https://github.com/jashkenas/backbone/.

From the Backbone.js website: Backbone’s only hard dependency is Underscore.js ( >= 1.7.0) also created by Jeremy Ashkenas. For RESTful persistence and DOM manipulation with Backbone.View, include jQuery ( >= 1.11.0).

Libraries such as Lo-Dash instead of Underscore.js and Zepto instead of jQuery work with varying degrees of compatibility.

This post documents how to create a RequireJS module that loads the Google Maps JavaScript API and is used by a web page to populate form inputs with location data. The Google Map contains a marker that can be dragged to reset the form with the marker position location data.

The package.json file contains project metadata and lists dependencies that are available on npm. This is useful to have when you want to re-install or update the dependencies with the npm install command.

Google Map JavaScript API

This module is dependent upon the RequireJS async plugin to load the google maps api. The gmap function accepts three parameters: the default latitude, default longitude and a callback function to handle the result data.

require.build.js

This is the RequireJS Optimizer build configuration file. Once the entry point and modules are created, run node node_modules/requirejs/bin/r.js -o require.build.js to compile the modules into a single js/main.js file.

Browserify lets you write modular JavaScript in node.js style. At the beginning of each module you write, the respective dependencies are added using require statements. Then Browserify compiles the modules along with all of the dependencies into an optimized JavaScript file for use in the browser.

If jQuery has already been loaded by a CDN or otherwise, a Browserify Shim can be used to include global jQuery as a module.

The package.json file contains project metadata and lists dependencies that are available on npm.

# create package.json
npm init

Install both jQuery and Lo-Dash from npm

# install dependencies
npm install jquery lodash --save

Updated on October 24, 2015

Local Modules

In the /src/js/modules folder, create a local application module. In this example, the service.js local module uses jQuery ajax to get data from a rest endpoint that returns json data. Then Lo-Dash is used to output the json data in the browser with a simple template.

In the /src/js/modules folder, create a second local application module. This module depends on jQuery and contains a small function to update element HTML. Here we are simply using it to change the page heading as various steps are completed in this small application. It also shows how multiple module dependencies are defined and how they interact with each other.

Run

Using a Command shell, run the gulp javascript task to Browserify the modules into a single JavaScript file, /js/app.js, with respective source map file, /js/app.js.map.

# run the task
$ gulp javascript

Server

Run the gulp server task to load the app in the browser using a BrowseSync static server. The gulp.watch event handler provides live reloading when the /js/app.js file is regenerated by the gulp javascript task.

White Space

Follow these recommendations so commits and diffs will be easier to read.

Do not mix spaces and tabs.

Configure the editor to “show invisibles”. For example, in Sublime Text, the setting is "draw_white_space": "all".

Configure the editor to remove end of line whitespace.

Choose one, spaces or tab indentation for all JavaScript the team is writing for the project. Consider this, a space is always just one column. The code editor setup pages linked below have info on how to configure for consistent formatting of tabs to spaces and vice versa.

Use a consistent value throughout the project for the indent size, e.g., 4 columns.

Code Editor Setup

Comparison Operators

Use === and !==

The equality operator == implicitly tries to convert the values before comparing. The identity or “strict equals” operator === does not convert the values when comparing. Use the equality operator == and != only as needed.

Semicolons

Include all necessary semicolons. Configure your editor to use JSHint, a fork of JSLint, used to detect errors and potential problems in JavaScript.

Global Scope

Any variable that is defined outside of a function body is global in scope. Global variables can be accessed and altered in any scope. Global variables should be declared only as needed. For more information, read this YUI blog post.

Namespace

Using a namespace is a good practice to keep your code out of the global scope.

Line Length

80 characters per line should be sufficient enough to work with. When a statement will not fit on a single line, it may be necessary to break it. Place the break after an operator, ideally after a comma.

The <script src="filename.js"></script> element or script tag as it is often referred to should be placed as far down in the body as possible. Ideally, just before the closing </body> tag. Some browsers try to load script files when they hit the script tag and the rest of the page is not parsed until script loading has finished. Additionally, async and defer attributes can be used to control when requested scripts are loaded.

async downloads the file during HTML parsing. The HTML parser will pause to execute the script when the download is completed.

defer downloads the file during HTML parsing. The script will execute after the HTML parser has completed. Multiple defer scripts execute in the order they appear in the document.

Resources

This post shows how to combine and minify multiple javascript files in a WordPress theme into one javascript file. The benefit is a single request to a javascript file that has been compressed by minification instead of multiple request to larger javascript files.

package.json

The package.json file contains meta data about your app or module and it includes the list of dependencies to install from Node Package Manager (NPM) when running npm install. NPM is bundled with Node.js; if you have not done so already, install Node.js so you have it. Then create and save this file in your themes root directory, for example /wp-content/my-theme/package.json. Then when you run npm install, the package.json file is read and the respective node modules are installed. More information is available here.

file structure

Here is what the themes javascript file structure looks like for this example. The /js/src folder contains all of the individual javascript files for your theme. When you run grunt, these are all combined and minified into /js/main.js

Partial view of themes files showing location of javascript

functions.php

The functions.php file controls the loading of the themes javascript resources. In the functions.php file, the wp_enqueue_script() function links the script to the page. The pre-existing wp_enqueue_script() function calls are no longer valid since the javascript files have been moved to the /js/src/ folder. Here is an example of the code from the pre-existing functions.php that was linking the scripts:

Here is an example of the code from functions.php after making the changes to link /js/main.js instead. Since /js/src/deflist.js depends on jQuery, so does /js/main.js and the $deps array parameter is set to ‘jquery’. For more information, refer to the wp_enqueue_script function reference

This tutorial describes how to setup and use the Grunt JavaScript task runner to automate repetitive tasks such as minification and compilation. Grunt is installed using npm, the Node.js package manager. You will also need Git to work with the tagged source code. This makes it easy to reset and compare your working copy of the code at each step. I discovered commit tags while using the AngularJS tutorial.

If you have not done so already, make sure that you have Node.js, Grunt CLI and Git installed. For Windows systems, after installing Git, you may decide to use the Git bash shell for your CLI (command line interface) instead of the Command Prompt.

Install Grunt’s command line interface (CLI) globally.

#install grunt CLI
$ npm install -g grunt-cli

Source Code

Using Git, clone the GruntTutorial repository. This contains all the source code for the tutorial. As you work through the tutorial, you will be instructed to use git to reset the source code so it matches the step at that point. This will revert the source code to it’s original state for the respective tag and thus overwrite any changes you have made to it.

GruntTutorial – bash

Step 2: Combine and Minify Javascript files

# reset to step 2
$ git checkout -f step-02

Gruntfile.js is added to root of the project to specify the modules configuration, define tasks and load plugins. This Gruntfile.js specifies an uglify plugin to perform JavaScript minification. The banner option creates a comment on the first line of the minified file that is output. The JavaScript source (src) and destination (dest) paths are set in the build properties. Since our build source path has a wildcard * before the js filename extension, all of the js files in that directory will be minified into a single JavaScript file named grunt-tutorial.min.js as specified in the build destination property.

For the Sass compile with the Compass & Watch Grunt plugins, you will need to have the RubyInstaller for Windows. As of this writing, use Ruby 1.9.3 installers. These provide a stable language and a extensive list of packages (gems) that are compatible and updated. During the setup, check the option to Add Ruby executables to your PATH. After installing Ruby, install Sass and Compass using the Start Command Prompt with Ruby.

Start Command Prompt with Ruby

Install compass and watch Grunt plugins

By running these npm install commands with –save-dev, the package.json file will automatically be updated to include these two new dependencies.

Edit and save one of the Sass (.scss) files. The watch task waits for changes to files and then fires a task. In our Gruntfile, the watch is configured to run the the compass task whenever a .scss file is updated. The compass task is configured to compile the Sass files specified in the sassDir property (src/sass/) and output to the cssDir specified (build/css/).

Screen

Document

The Document object represents the root node of HTML, XHTML and XML documents. The nodes of every document are organized in a tree structure, called the DOM tree. Objects in the DOM tree may be addressed and manipulated by using methods on the objects.