I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML5, CSS3, JavaScript and PHP. I mainly use the LAMP stack and frameworks like jQuery, jQuery Mobile, and Cordova (PhoneGap). My interests also include web security, web accessibility, SEO and WordPress. Currently I'm self-employed working with the cited technologies and a regular blogger for several networks (SitePoint, Tuts+ and FlippinAwesome) where I write articles about the topics I usually work with and more. I'm also the author of the books jQuery in Action, third edition and Instant jQuery Selectors.

Aurelio's articles

  1. How to Test Asynchronous Code with QUnit

    A few weeks ago, I published an article titled Getting Started with QUnit where I discussed the main concepts of unit testing and how we can test our JavaScript code with QUnit. In that article, I focused on the assertions provided by the framework and how to test code that runs synchronously. However, if we want to discuss real world cases we can’t avoid talking about asynchronous functions.

    Just like synchronous functions, asynchronous ones need love, and even more tests. In this article I’ll teach you how to test asynchronous code with QUnit. In case you don’t recall the assertion methods available, or you totally missed my article, I suggest you read Getting Started with QUnit. The material covered in it will be a prerequisite to this article.

    Creating Asynchronous Tests with QUnit

    Every non-trivial project that is written in JavaScript contains asynchronous functions. They are used to perform a given action after a certain amount of time, to retrieve data from a server, or event to send data to a server. QUnit provides a method, called QUnit.asyncTest(), whose purpose is to test asynchronous code. The signature of the method is:

    [js]
    QUnit.asyncTest(name, testFunction)
    [/js]

    The meaning of the parameters is the same as QUnit.test(), but I’m reporting them here for your convenience:

    • name: A string that helps us identify the test created.
    • testFunction: The function containing the assertions that the framework will execute. The framework passes to this function an argument that exposes all of QUnit’s assertion methods.

    The fact that this method accepts the same parameters as QUnit.test() might be misleading. You might think that the principle is the same and that all you have to do to test an asynchronous function is to replace the calls to QUnit.test() with QUnit.asyncTest() and you’re done. Not so fast!

    In order to do its job, QUnit.asyncTest() needs to be used with two other methods: QUnit.start() and QUnit.stop(). Let’s discover more about them.

  2. 5 Grunt Tasks that Improve the Performance of Your Website

    Many times on SitePoint I’ve mentioned how achieving good performance is a main concern today and how you should strive for fast web pages. In some articles of mine about JavaScript APIs, such as Introduction to the Resource Timing API and Discovering the User Timing API, I gave you all the power you need to know what’s slowing down your project. Earlier this year, Craig Buckler covered this topic too, with his article The Complete Guide to Reducing Page Weight.

    If you aren’t stuck in the past, you’re likely using a task runner like Grunt or Gulp to improve your workflow by automating a lot of operations we used to perform manually. In this article I’ll describe five Grunt tasks that help us enhance the performance of our web pages.

    grunt-contrib-imagemin

    The first task I want to mention is grunt-contrib-imagemin. The reason why I want to discuss it first is that images are killing the web. Seriously!

    If you take a look at HTTParchive.org statistics you’ll see that images represent more than 63% of the total size of a page. The reason for such bloat is that often images aren’t compressed to have a weight as low as possible. grunt-contrib-imagemin is one of the tasks you can use to solve this issue.

    This task comes with the following optimizers to be able to compress most of the image formats employed on the web:

    • gifsicle to compress GIF images
    • jpegtran to compress JPEG images
    • optipng to compress PNG images
    • svgo to compress SVG images

    An example of configuration for this task is shown below:

    [js]
    imagemin: {
    dist: {
    options: {
    optimizationLevel: 5
    },
    files: [{
    expand: true,
    cwd: 'src/images',
    src: ['**/*.{png,jpg,gif}'],
    dest: ‘dist/’
    }]
    }
    }
    [/js]

    This configuration allows for a high level of optimizations by using the optimizationLevel option. This value ranges from 0 to 7, with 3 as the default. In this case the images optimized are those with the extension png, jpg, or gif, and located in the “src/images” folder and all its subfolders. The result of the optimization will be stored in the “dist” folder.

  3. How to Use jQuery’s $.ajax() Function

    Without any doubt Ajax has taken web development by storm and it’s one of the most successful paradigms ever. In my article An Introduction to jQuery’s Shorthand Ajax Methods, I discussed some of jQuery’s most used Ajax shorthand methods: $.get(), $.post(), and $.load(). They are convenient methods for making Ajax requests in a few lines of code.

    Sometimes, we need more control over the Ajax calls we want to make. For example, we want to specify what should happen in case an Ajax call fails or we need to perform an Ajax request but its result is only needed if retrieved within a certain amount of time. In such situations, we can rely on another function provided by jQuery, called $.ajax(), that is the topic of this tutorial.

    The $.ajax() Function

    The jQuery’s $.ajax() function is used to perform an asynchronous HTTP request. It was added to the library a long time ago, existing since version 1.0. The $.ajax() function is what every function discussed in the previously mentioned article calls behind the scene using a preset configuration. The signatures of this function are shown below:

    [js]
    $.ajax(url[, options])
    $.ajax([options])
    [/js]

    The url parameter is a string containing the URL you want to reach with the Ajax call, while options is an object literal containing the configuration for the Ajax request.

    In its first form, this function performs an Ajax request using the url parameter and the options specified in options. In the second form, the URL is specified in the options parameter, or can be omitted in which case the request is made to the current page.

    The list of the options accepted by this function, described in the next section, is very long. So, I’ll keep their description short. In case you want to study in-depth their meaning, you can refer to the official documentation of $.ajax().

    The option Parameter

    There are a lot of different options you can specify to bend $.ajax() to your need. In the list below you can find their names and their description sorted in alphabetic order:

  4. An Introduction to jQuery’s Shorthand Ajax Methods

    Raise your hand if you’ve never heard the term Ajax. I’ll bet almost all of you have your arms down, close to their body. Ajax, which originally stood for Asynchronous JavaScript and XML, is one of the most used client-side methodologies, helping to create asynchronous websites and web applications.

    Performing Ajax calls using raw JavaScript is of course possible, but dealing with all the different parts of the code can be a pain. This is even more true if you have to support a prehistoric browser like Internet Explorer 6.

    Fortunately for us, jQuery provides a set of methods that deal with these issues for us, allowing us to focus on the task we want accomplish with the code. jQuery offers a primary method, called $.ajax(), which is highly configurable to fit whatever need you may have. It also provides a set of [shorthand methods](http://api.jquery.com/category/ajax/shorthand-methods/), called shorthand because they are simply wrappers for the $.ajax() method with a preset configuration, each serving a single purpose.

    All except the $.ajax() method have one feature in common: they don’t operate on a set of DOM elements, but are called directly from the jQuery object. So, instead of having a statement like:

    [code language="javascript"]
    $('p').ajax(...);
    [/code]

    which selects all the paragraphs in the page and then calls the ajax() method, we’ll write:

    [code language="javascript"]
    $.ajax(...);
    [/code]

    In this article, we’ll discuss three of the most used jQuery shorthand methods: load(), $.post(), and $.get().

    load()

    The first method we’ll discuss is load(). It enables us to load data from the server and place the returned data (often HTML code) into the elements matched by the selection. Before seeing it in action, let’s see its signature:

    [code language="javascript"]
    load(url[, data][, callback])
    [/code]

    The meaning of each parameter is described below:

  5. How to Test Your Site Locally with Modern.IE

    This article was sponsored by Modern.IE. Thanks for supporting the sponsors that make SitePoint possible!

    There’s no shortage of front end tools to help us test the quality of our code. Some examples of these tools are JSHint and JSLint, to test our JavaScript files, the W3C Markup validator, to test that our HTML code is valid and written according to the specifications, and the W3C CSS validator to verify our style sheets, but there are many more.

    Recently on SitePoint, we’ve been highlighting another such tool: Microsoft’s Modern.IE. The service includes the ability to scan your website to identify common coding problems and generate a report (also available as a .pdf file). This report contains the result of each test and some recommendations about how to fix or improve it. This way you can ensure your code adheres to the current best practices, performs well, and implements features specifically designed to target Windows 8. All you have to do is to provide the URL of the web page you want to analyze.

    Louis Lazaris wrote a great guide to this scan tool in his article Using modern.IE to Identify Common Coding Problems. His article covered live sites. In this tutorial, we’ll look at how you can perform the scan on a project hosted on your machine.

    What’s Modern.IE?

    Modern.IE is a service that provides a collection of different tools to test our web pages from different points of view and for different purposes. For example, Modern.IE offers several free Windows virtual machines to run any edition of Internet Explorer from a Windows, Mac, or Linux host.

    Another feature is a free screenshot automation tool powered by BrowserStack. This tool loads up a given website on a range of mobile and desktop devices and presents captured screenshots in a few minutes. This means you can get screenshots of your website as it would be seen on the Android browser running on Android, on Firefox and Opera running on Windows 8, or even on devices you might not easily have access, to, like an iPhone 4S using mobile Safari.

    If you want to know more about this and other features, you can read the articles Quick Browser Screenshot Testing at Modern.IE by Craig Buckler and Browser Testing with Modern.IE by James George.

    Now that you have the context, let’s delve into scanning a local project.

    Recently on SitePoint, we’ve been highlighting another such tool: Microsoft’s Modern.IE. The service includes the ability to scan your website to identify common coding problems and generate a report (also available as a .pdf file). This report contains the result of each test and some recommendations about how to fix or improve it. This way you can ensure your code adheres to the current best practices, performs well, and implements features specifically designed to target Windows 8. All you have to do is to provide the URL of the web page you want to analyze.

    Louis Lazaris wrote a great guide to this scan tool in his article Using modern.IE to Identify Common Coding Problems. But his article was on a live site, in this tutorial we’ll look at how you can perform the scan on a project hosted on your machine.

    What’s Modern.ie

    Modern.IE is a service that provides a collection of different tools to test our web pages from different points of view and for different purposes. For example, Modern.IE offers several free Windows virtual machines to run any edition of Internet Explorer from a Windows, Mac, or Linux host.

    Another feature is a free screenshot automation tool powered by BrowserStack. This tool loads up a given website on a range of mobile and desktop devices and presents captured screenshots in a few minutes. This means you can get screenshots of your website as it would be seen on the Android browser running on Android, on Firefox and Opera running on Windows 8, or even on an iPhone 4S using mobile Safari.

    If you want to know more about this and other features, you can read the articles Quick Browser Screenshot Testing at Modern.IE by Craig Buckler and Browser Testing with Modern.IE by James George.

    Now that you have the context, let’s delve into scanning a local project.

    How to analyze a local website

    Installing the scan tool

    The Modern.IE tool to scan a website is available for free on GitHub. To get a copy of the source, you can open the command-line and run the command:

    git clone https://github.com/InternetExplorer/modern.IE-static-code-scan.git

    You can grab a copy, install it and then start scanning your projects locally using a Git client.

    Alternatively, you can click on the Download button on the right side of the page as shown in the figure below.

    Downloading Modern.ie

    Once you have downloaded the tool, you’ll need to download and install Node.js (version 0.10 or higher). If you already have a version of Node.js installed, well, you’re one step closer to using this tool.

  6. CSS “position: sticky” – Introduction and Polyfills

    If you’ve read the article Obvious Design always wins by Annarita Tranfici, you might agree with her statement:

    People expect to see common patterns: find the main menu in the top of the page, a search box at the top-right corner, a footer at the bottom, and so on.

    I agree that people expect certain components of a website to be placed in a particular location and, in my opinion, this is even more true when it comes to the main menu.

    Sometimes, due to a client request or because we have determined this is the best approach, we may require that a main navigation stay visible at all times on the page, without it being fixed in place, essentially following the page content. In recent years, a lot of JavaScript-based solutions have seen the light of day because CSS alone was unable to achieve this task.

    In this article we’ll discuss position: sticky, the new CSS solution to this problem.

    What Problem are We Solving?

    Before discussing this new value for the position property, let’s better understand what is the problem we’re trying to solve.

    Let’s pretend the main menu of our amazing website is right after the header but still at the top of the page (not in a sidebar) and that it occupies all the width available. This might look like this:

    See the Pen Example with no sticky menu by SitePoint (@SitePoint) on CodePen.

    What we want to achieve is that when the user scrolls the page, as soon as the menu is positioned at the top of the viewport, instead of the menu scrolling out of view, it will stick at the top position — as if it had a position: fixed applied to it only when it reached the top of the viewport).

    To achieve this with traditional code we need to add some JavaScript. We listen for the scroll event of the page and use JavaScript to change the value of the position and top properties according to the current position of the viewport. Specifically, we need to add top: 0 and position: fixed to the menu when it’s at the top of the viewport, and then revert the properties back to their defaults otherwise.

    An alternative, but similar, approach is to create a class in our CSS where those values are present, and then add and remove the class as needed, with JavaScript, which might look like this:

    [code language="javascript"]
    var menu = document.querySelector('.menu')
    var menuPosition = menu.getBoundingClientRect().top;
    window.addEventListener('scroll', function() {
    if (window.pageYOffset >= menuPosition) {
    menu.style.position = 'fixed';
    menu.style.top = '0px';
    } else {
    menu.style.position = 'static';
    menu.style.top = '';
    }
    });
    [/code]

    Please note that this snippet doesn’t deal with older versions of Internet Explorer. If you need to deal with those browsers (poor you!), I’ll provide a foolproof polyfill that you can use.

    A live demo of this second step is shown below:

  7. Getting Started with QUnit

    Software testing is the process of evaluating a piece of software to detect differences between expected and actual outputs for a given set of inputs. Testing, and unit-testing in particular, should be an essential part of every developer’s life. Unfortunately, many developers seem to be scared of this activity.

    In JavaScript there are a lot of frameworks we can choose from to test our code base. Some examples are Mocha, Selenium, and QUnit. In this article, I’ll introduce you to QUnit. QUnit is the unit-testing framework developed and maintained by the jQuery team, which is the same team behind projects like jQuery and jQuery UI.

    Setting up QUnit

    One of the main reasons why a lot of developers use QUnit is its ease of use. Starting off with this framework is very simple, and the main concepts can be grasped in a few hours.

    The obvious first step to perform in order to employ QUnit is to download it. There are several ways to do that: downloading it manually from the website, using a CDN, using Bower, or using npm. My suggestion is that unless you’re developing a simple live demo, you should not rely on the CDN to test your code. So, stick with the other options.

    For this article I don’t want to set any prerequisite (read Bower and npm), so we’ll employ the first method. Therefore, go to the QUnit website and download the latest version of both the JavaScript file (named qunit-1.14.0.js) and the CSS file (named qunit-1.14.0.css).

    Place them into a folder where you’ll also create an index.html. In this file we’ll place the HTML code shown in the homepage of the website that I’m repeating below for your commodity.

    [html]
    < !DOCTYPE html>







    [/html]

    As you can see, this code uses the CDN to include the CSS and JavaScript files. So, you have to update the links to include the files you have previously downloaded.

    In the markup you can see that there are a couple of <div>s in place. The first, having qunit as its ID, is used by the framework to show its user interface where the results of the tests are displayed. The second <div>, whose ID is qunit-fixture, should be used by you, the developer. This element allows a developer to test code that adds, edits, or removes elements from the DOM without having to worry about cleaning up the DOM after each test. If you put the elements created by the code inside this <div>, QUnit will take care of the reset for us.

    Finally, we have the inclusion of a tests.js file that represents the file containing the tests. My advice is to use a file to store your tests when working on a real project. In the live demos I’ve created for this tutorial I’ve used JSBin, which of course doesn’t allow file uploads. Therefore, in the demos you’ll see that I’ve inlined the code of the tests.

    Now that you know the meaning of each part of the markup, open up the index.html page in your browser and see what happens.

    If everything went well, you should see the interface as shown by the live demo below, which is also available as a JSBin:

    QUnit Example

  8. 5 Little Known Details About jQuery Methods

    jQuery is the most used JavaScript library in the world, but all of us already knew that. Despite the fact that in recent months a lot of criticisms have been raised, it still attracts a lot of attention among developers. Whether you’re a jQuery beginner or a JavaScript expert (Dave Methvin and other team members are excluded), you might not know some peculiarities of jQuery. In this article we’ll discuss five of them.

    Returning false in Event Binders

    As we all know, jQuery’s first aim is to standardize the way different browsers behave using a unified set of methods. Where possible, jQuery enhances the features of a browser, integrating those that aren’t supported natively. Think of the selectors that you can use thanks to jQuery that aren’t natively supported by Internet Explorer 6 and 7 (the attribute selectors, :not, :last-child, and so on).

    Sometimes, although these are rare exceptions, jQuery slightly diverges from standard behavior. An example is that returning false in a jQuery event handler (for example one attached to on()) is the same as calling:

    [js]
    event.stopPropagation();
    event.preventDefault();
    [/js]

    On the contrary, returning false in native event handlers like addEventListener() is equivalent to writing:

    [js]
    event.preventDefault();
    [/js]

    This behavior can be proven by taking a look at the relevant part of jQuery’s source:

    [js]
    if ( ret !== undefined ) {
    if ( (event.result = ret) === false ) {
    event.preventDefault();
    event.stopPropagation();
    }
    }
    [/js]

    Pseudo-selectors Do More Than You Think

    In the jQuery documentation of many pseudo-selectors you can find the following note (in this case in relation to the :checkbox pseudo-selector):

    $( “:checkbox” ) is equivalent to $( “[type=checkbox]” ). As with other pseudo-class selectors (those that begin with a “:”) it is recommended to precede it with a tag name or some other selectors; otherwise, the universal selector (“*”) is implied. In other words, the bare $(‘:checkbox’) is equivalent to $( “*:checkbox” ), so $( “input:checkbox” ) should be used instead.

    Now, let’s take a look at the actual code in jQuery:

    [js]
    function createInputPseudo( type ) {
    return function( elem ) {
    var name = elem.nodeName.toLowerCase();
    return name === “input” && elem.type === type;
    };
    }
    [/js]

    As you can see from the code, the documentation is slightly incorrect. $(':checkbox') is actually equivalent to $('input[type="checkbox"]') with regards to what it searches (note the name === "input"), but tests all the elements of the page as if you called it specifying the universal selector or nothing at all.

    With this in mind, you may be tempted to not prepend the element selector anymore when using filters like this and write:

    [js]
    var $checkboxes = $(‘:checkbox’);
    [/js]

    However, for performance reasons, it’s still worth it to use it so that jQuery won’t scan every element of the page. Thus, you should still write a statement like:

    [js]
    var $checkboxes = $(‘input:checkbox’);
    [/js]
  9. 3 New JavaScript APIs You May Want to Follow

    If you’re a frequent SitePoint reader and perhaps a follower of mine, you’re aware that I’ve written a lot of articles about HTML5 and JavaScript APIs. So far, I’ve published articles discussing APIs that you can start using today, even if with the use of a polyfill.

    Today I’ll break this habit by giving you a preview of some APIs that are still at a very early stage. To give you an idea of how cutting edge these APIs are, consider that 2 out of 3 were announced just few days ago. Because of this, the bad news is that none of them can be used right now. However, if you’re interested in what they do, you may want to follow the development of the specifications and maybe provide your feedback.

    Without further ado, let’s start!

    Web Alarms API

    The Web Alarms API provides access to the device alarm settings, which can schedule a notification or for an application to be started at a specific time. The typical use case for this API involves applications like alarms, calendars, or any other software that needs to perform an action at a specific time.

    Starting from last year, this API is a W3C Working Draft. So, the specifications are at the first stage of the process to become a W3C Recommendation. This API is exposed through the alarms property of the window.navigator object. The alarms property offers three methods:

    • getAll(): Retrieves all the alarms added to the device as an array of Alarm objects.
    • add(): Registers an alarm based on a Date object and returns an AlarmRequest object.
    • remove(): Removes a previously added alarm based on the unique ID (unique within the application origin).

    Just to give you an idea of how you could ideally call these methods, here is an example that adds an alarm (remember that at the moment this code won’t work in any browser):

    [js]
    var alarmId;
    var request = navigator.alarms.add(
    new Date(“June 29, 2012 07:30:00″),
    “respectTimezone”,
    );

    request.onsuccess = function (e) {
    alarmId = e.target.result;
    };

    request.onerror = function (e) {
    alert(e.target.error.name);
    };
    [/js]

    Then, if you want to remove the same alarm, you can write:

    [js]
    var request = navigator.alarms.remove(alarmId);

    request.onsuccess = function (e) {
    alert(“alarm removed”);
    };

    request.onerror = function (e) {
    alert(e.target.error.name);
    };
    [/js]

  10. 5 JavaScript APIs to Empower Your Mobile Web Pages

    Statements like

    “The mobile market is increasing”

    and

    “People accessing the web through a mobile device (smartphones, tablets etc.) will overtake those accessing it through a desktop or a laptop”

    don't impress anymore.

    Today we're all aware, at least we should be, that the mobile market is significant when developing anything for the web.

    For years there has been discussion and differing points of view about native applications versus web applications and on which is the best. Regardless of your opinion, it used to be a fact that native mobile applications allowed to access hardware components that web pages couldn't. But is this gap still valid today? Have web technologies improved to the point where we, as developers, can code with just HTML, CSS, and JavaScript?

    In this article I'll introduce some JavaScript APIs that allow your web pages to access hardware components of mobile devices or that can empower your web application on mobile devices.

    Battery Status API

    The Battery Status API provides information about the system's battery level or status. Thanks to this API you are able to know if the battery is charging or not, how long before the battery will be fully discharged, or simply its current level. These details are accessible through four properties that all belong to the window.navigator.battery object. This API also defines events that can be fired when there are changes in the mentioned properties.