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. 5 Typical JavaScript Interview Exercises

    JavaScript developers are in high demand in the IT world. If this is the role that best expresses your knowledge, you have a lot of opportunities to change the company you work for and increase your salary. But before you are hired by a company, you have to demonstrate your skills in order to pass the interview process. In this article I’ll show you 5 typical questions asked for a front end job to test the JavaScript skills of the candidate and their relative solutions. It’ll be fun!

    Question 1: Scope

    Consider the following code:

    [js]
    (function() {
    var a = b = 5;
    })();

    console.log(b);
    [/js]

    What will be printed on the console?

    Answer

    The code above prints 5.

    The trick of this question is that in the IIFE there are two assignments but the variable a is declared using the keyword var. What this means is that a is a local variable of the function. On the contrary, b is assigned to the global scope.

    The other trick of this question is that it doesn’t use strict mode ('use strict';) inside the function. If strict mode was enabled, the code would raise the error Uncaught ReferenceError: b is not defined. Remember that strict mode requires you to explicitly reference to the global scope if this was the intended behavior. So, you should write:

    [js]
    (function() {
    ‘use strict';
    var a = window.b = 5;
    })();

    console.log(b);
    [/js]

    Question 2: Create “native” methods

    Define a repeatify function on the String object. The function accepts an integer that specifies how many times the string has to be repeated. The function returns the string repeated the number of times specified. For example:

    [js]
    console.log(‘hello’.repeatify(3));
    [/js]

    Should print hellohellohello.

    Answer

    A possible implementation is shown below:

    [js]
    String.prototype.repeatify = String.prototype.repeatify || function(times) {
    var str = ”;

    for (var i = 0; i < times; i++) {
    str += this;
    }

    return str;
    };
    [/js]

  2. A Guide to the HTML5 ‘time’ Element

    Time – one of the few known things that is infinite. Human beings, as well as animals and plants, have dealt with time since the beginning of their existence.

    On the web this need isn’t different. Even in this medium, we need to communicate to other people that something happened at a certain point, on a specific date, or in relation to another set time.

    Prior to HTML5 we had no element to semantically mark up a date or time. In recent years, other solutions, most notably Microformats and Microdata, have tried to fill this gap for specific situations (date of birth, publication of a book, and so on).

    In this article I’m going to cover HTML5’s <time> element, which helps address the need just discussed.

    What’s the <time> element?

    The <time> element was introduced in the HTML5 spec in 2009. It was then dropped in 2011 in favor of <data>. Then <time> was reintroduced, and then improved to allow new date/time formats. From this you can see that specifications can be quite controversial.

    The <time> element represents a date and/or a time in the Gregorian calendar. It’s an inline element (like <span> and <a>) and must have a closing tag (like <div> and <span>). When used in its simplest form, the content of the element must be a valid date and/or time string.

    An example is shown below:

    [code language="html"]


    [/code]

    In the code above, I’m defining a date, specifically February 1, 2009. The format employed in the code (yyyy-mm-dd) should be familiar to you if you have spent some time on Linux but, as we’ll see later in this article, this isn’t the only valid format.

    In the first draft of the specifications, precise dates were one of the few formats you could write. For example, you couldn’t specify a date like “November 2014” or “476” (the start of the Middle Ages). This was a big issue for several cases like the dating of a painting or a historical event because a precise date isn’t known.

    Fortunately, this type of date is now permitted in the spec. So today we can describe a given month of a year without a day:

  3. Creating Autocomplete datalist Controls

    If you have seen a decent number of websites in your life, you have surely noted a set of recurring widgets in most of them. Among these widgets are the search box, the newsletter widget, and the text box autocomplete widget. The latter is a widely used component, especially when the website needs a field that has several possible values but also needs to allow to create a completely new value. This component is so adopted that many JavaScript frameworks have their own autocomplete widget.

    Until few years ago, there wasn’t a native HTML element to deal with this situation and developers have implemented the concept in different ways. This piece of the HTML puzzle isn’t lacking anymore. Today, we have an HTML element called datalist that serves this purpose. In this article, we’ll discover what it is and how to use it.

    What’s the datalist Element?

    The datalist element represents a set of option elements that embody predefined options for other controls. So, this element can be seen as a wrapper for a set of options that express the possible values an input can assume, without restricting it to those values only. By default datalist and its children are hidden, so you won’t see them in a web page. In fact, datalist must be linked to another element through the use of a list attribute set on these other elements. The value of this attribute must be set to the ID of the datalist to use.

    A simple example of HTML code that uses this element is shown below:

    [html]


    [/html]

    The code above defines an input and a datalist element that contains several options. As you can see, the datalist has “cities” as its ID and the input is linked to it by using the list attribute (that has “cities” as its values as well).

  4. Introducing the Screen Orientation API

    Everyone uses the web in a different way. There are people who use it to chat, others use it to watch movies, and others use it to play games. For those of you who access the internet to play games on their mobile device, I have a question: have you ever played a game that asks you to rotate the screen to start? I bet the answer is yes.

    The reason you have to rotate the screen is that the UI has been developed for a specific mode, portrait or landscape. If your web application has the same need, or you are developing one of these games, I have a JavaScript API for you: the Screen Orientation API. In this article I’ll discuss what it is and what it is good for.

    What is the Screen Orientation API?

    The Screen Orientation API provides the ability to read the screen orientation state, to be informed when this state changes, and to be able to lock the screen orientation to a specific state. In other words, you are now able to detect the orientation of a user’s device (in terms of portrait and landscape) and lock in the mode you need. Doing so, you don’t need to show your users weird animations and labels to specify the orientation needed. In fact, you can now set the device’s screen in the orientation needed so that the user will understand how to rotate the device.

    The Screen Orientation API is at a very early stage, as it’s a W3C Working Draft. The current specifications may be superseded in a few months by a newer version that is currently in progress. The new version is slightly different from the old one because it introduces a new property and a different return type for one of the methods.

    It’s also worth noting that to lock the screen, the web page must be in full-screen mode (you can achieve this using the Fullscreen API).

    Now that you know what the Screen Orientation API is, let’s discover more about its properties and methods.

    Properties and Events

    The Screen Orientation API extends the screen object of window with a property, orientation, and two methods, lockOrientation() and unlockOrientation().

    The orientation property returns a string representing the orientation of the screen. Its value can be one of the followings:

    • portrait-primary: The orientation is in the primary portrait mode. For a smartphone this values means that it’s in a vertical position with the buttons at the bottom.
    • portrait-secondary: The orientation is in the secondary portrait mode. For a smartphone this value means that it’s in a vertical position with the buttons at the top (the device is down under)
    • landscape-primary: The orientation is in the primary landscape mode. For a smartphone this value means that it’s in a horizontal position with the buttons at the right.
    • landscape-secondary: The orientation is in the secondary landscape mode. For a smartphone this value means that it’s in a horizontal position with the buttons at the left.

    The lockOrientation() and unlockOrientation() methods are complementary in what they do. The first method locks the device’s screen as if the device was physically rotated in a certain position, as shown in the figure below. It returns a Boolean which is true in case of success of the operation and false otherwise.

  5. Creating Nice Notifications with jQuery

    Notifications are one of the most used features when developing a dynamic website. Whether your application is injecting a snippet of HTML in the web page or it’s sending the data of a form filled by a user, your application needs to give some feedback to the users. There are a lot of different techniques you can employ to provide feedback to your users such as alert messages and dialog boxes.

    In this article, I’ll explain how you can integrate nice notifications in your web pages through the use of a jQuery plugin called noty.

    What’s noty?

    noty is a jQuery plugin that makes it easy to create several types of feedback like alerts, success or failure messages, and requests of confirmation. My choice to discuss this plugin is not random. In fact, noty is one of the most watched and starred plugins that you can find on the jQuery plugin registry. One of the best features of noty is that it’s highly customizable thanks to the many options it exposes, some of which will be discussed in this article. Another interesting feature is that it allows you to queue the notifications so that you don’t have to wait until the life cycle of a previously showed notification ends. However, if you don’t need this feature you can disable it.

    Getting Started with noty

    Just like many jQuery plugins, it’s very easy to start using noty. The first step is to download the plugin and include it in your pages after the jQuery library. To download noty you can either visit its GitHub repository and download the latest version available, or type the following Bower command:

    [code]
    bower install noty
    [/code]

    Once you have downloaded the plugin, you can include it on your page using the following code:

    [html]


    [/html]
  6. QUnit Advanced Concepts: Modules and Configuration

    In the past weeks I’ve covered several features of QUnit in the tutorials Getting Started with QUnit and How to test asynchronous code in QUnit. I described how to set up the QUnit testing framework to start testing your JavaScript project, what an assert is, what methods QUnit provides, and how to create tests for synchronous or asynchronous code.

    In this article I’ll discuss how you can organize your test code in modules, and how you can tweak QUnit to better fit your needs using the configuration properties exposed by the framework.

    Organizing QUnit in Modules

    The ability to organize a project in smaller, more manageable parts isn’t a new concept in software development. Developers have always strived to keep their code simple and organized by splitting the codebase in multiple files or modules. Testing is no different. Keeping our tests organized and in multiple modules, especially if we’re writing tests for a large project, is very useful and usually enhances its maintainability.

    QUnit provides a method named QUnit.module() that allows us to group our tests into modules. The signature of this method is shown below:

    [js]
    QUnit.module(name[, lifecycle])
    [/js]

    The name parameter is a string used to identify the module, while lifecycle is an object containing two optional functions to run before (setup) and after (teardown) each test.

    To specify which tests belong to a given module, you don’t need to do any sort of wrapping of the tests like this:

    [js]
    // No, it’s not like that!
    QUnit.module(‘My first module, {
    setup: function() {},
    teardown: function() {},
    tests: function() {
    // Tests here
    }
    });
    [/js]

    A test belongs to a given module simply if it’s defined after a call to QUnit.module() but before another call to QUnit.module() is found. In the next example, we have tests named “Test 1″ and “Test 2″ that belong to module “Module 1″, and another test, “Test 3″, that belongs to “Module 2″.

    [js]
    // It’s like that and that’s the way it is
    QUnit.module(‘Module 1′);

    QUnit.test(‘Test 1′, function(assert) {
    // assertions here
    });

    QUnit.test(‘Test 2′, function(assert) {
    // assertions here
    })

    QUnit.module(‘Module 2′);

    QUnit.test(‘Test 3′, function(assert) {
    // assertions here
    });
    [/js]

    Ideally, module names express an isolated part of your project. For example, the jQuery library has the following modules: ajax, core, css, event, selector, etc.

  7. 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.

  8. 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.

  9. 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:

  10. 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: