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

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

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

  4. 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]
  5. 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]

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

  7. Introduction to the Resource Timing API

    SitePoint has published some good articles on performance recently. In particular, Craig Buckler wrote an article entitled Average Page Weights Increase by 32% in 2013 along with another one called some easy wins to reduce the weight of a website.

    But improving the speed of our websites and apps isn’t just a matter of minifing JavaScript files and employing an image compressor. In many cases we have to deal with external resources (libraries from a CDN, videos from YouTube, images from Flickr, and so on) or internal resources that need to be accurately measured to establish what’s slowing down the loading of our pages.

    I’ve previously covered some APIs that can help in testing the performance of a website. For example, the High Resolution Time API and the User Timing API. In this article, I’ll introduce you to another API in this category: The Resource Timing API.

    What’s the Resource Timing API?

    The Resource Timing API allows you to collect complete timing information related to resources in a document. It enables you to measure user latency, which is crucial to benchmark web pages. This API is a W3C Candidate Recommendation so we can be sure that significant features are mostly locked, but there could be minor changes to the spec in the future.

    Using the Resource Timing API allows us to retrieve and analyze a detailed profile of all the network timing data for every resource on the page. We’ll cover what these data are in the next section. For the moment, it’s important that you understand how this API can help us in tracking the performance of the resources of our page, and determine how many and what resources we have to optimize.

    Now that we know what this API is, let’s delve into its features.

    Methods, Properties, and Events

    The Resource Timing API is exposed through the performance property of the window object. We can retrieve the information collected for each resource using the getEntriesByType() method. If this sounds familiar to you, this is because it’s the same method used by the User Timing API. The difference is that to retrieve information about these resources we have to pass the string resource to getEntriesByType().

  8. A Guide to the jQuery animate() Method

    jQuery is a lovely library, and for many years now it has changed the way thousands of developers approached their projects. When jQuery was created, CSS wasn’t able to create complex animations, leaving JavaScript as the way to go. jQuery helped a lot with animations thanks to the several methods created for this purpose. Although it comes with a few simple animations (fadeIn(), hide(), slideDown(), and so on), to keep its weight low, the library provides a very flexible method called animate(), which allows us to create any animation we desire. This method is the topic of this article.

    jQuery’s animate() is a wrapper method, meaning that it operates on a set of previously selected DOM elements, wrapped by jQuery. This method allows you to apply your own custom animation effects to the elements in the set. To do that, we have to provide a set of CSS style properties and values that those properties will reach at the end of the animation. The intermediate values that the style achieves during the effect (automatically handled by the animation engine) are determined by the duration of the effect and the easing function, two options we’ll discuss soon.

    The list of CSS style properties that can be animated is limited to those that accept numeric values. The value can be an absolute value (like 200), or a relative value from the starting point. In the case of an absolute value, jQuery assumes pixels as the default unit. We can also specify other units like em, rem, or percentages. To specify relative values, we have to prefix it with += or -= to indicate relative target values in the positive or negative direction, respectively.

    Now that we know a little about animate(), it’s time to look at its signatures and its parameters.

    Signatures and Parameters

    This method comes in two main forms, and most of its parameters are optional (denoted using the usual square brackets):

    • animate(properties[, duration][, easing][, callback])
    • animate(properties[, options])

    There is also a lot to say about the parameters:

    • properties (Object): A hash containing the values that should be reached at the end of the animation.
    • duration (Number|String): The duration of the effect in milliseconds or one of the predefined strings: “slow” (600ms), “normal” (400ms), or “fast” (200ms). The default is “normal”.
    • easing (String): The easing function name to use when performing the transition. The default value is “swing”.
    • callback (Function): A function to execute when the animation is completed for each animated element.
    • options (Object): A hash containing a set of options to pass to the method. The options available are the followings:

      • always (Function): A function called when the animation completes or stops without completing.
      • complete (Function): A function executed when the animation is completed.
      • done (Function): A function called when the animation completes.
      • duration (String|Number): Same as previously described.
      • easing (String): Same as previously described.
      • fail (Function): A function executed when the animation fails.
      • progress (Function): A function run after each step of the animation. The function is called only once per animated element.
      • queue (Boolean): If the animation has to be placed in the effects queue (more on this in a few moments). The default value is true.
      • specialEasing (Object): A hash of one or more CSS properties whose values are easing functions.
      • start (Function): A function executed when the animation begins.
      • step (Function): A function to invoke for each animated property of each animated element.

    The term easing is used to describe the manner in which the processing and pace of the frames of the animation are handled. The queue option allows us to run animations in sequence when it’s set to true, or in parallel when set to false. That’s quite a lot of power in our hands that we can use as we like.

    In the remainder of this article, we’ll demonstrate some of these arguments in action to give you a taste of what’s possible with animate().

    Example Uses

    In this section we’ll build some demos to unleash the power of animate(). Keep in mind that this method isn’t a good fit for very, very complex animations because of issues concerning the performance and the smoothness of the animations.

    Running a Single Animation

    Running a single animation is pretty easy, and involves just one call of the method. For example, we may want to move an element from one side of a box to the other. To illustrate this animation we’ll set up two div elements, one inside the other. We’ll style them so that the inner div has a red background. The code to complete this is shown below.

  9. Easily Improving jQuery Animations

    We’ve all used jQuery’s animate() to create nice effects on our web pages. Then, with the introduction and the rise of CSS3 they told us that our code was rubbish. They suggested that we dump all of our jQuery-based animations (and in general JavaScript-based animations) in favor of CSS-based ones.

    This change forced us to deal with a lot of browser (in)compatibility issues and lack of features; not to mention the impossibility to run them on older versions of Internet Explorer. The pain was justified by the fact that CSS animations are faster than JavaScript ones. At least they told us so. It this true? Is jQuery’s animate() so slow? Is there a way to enhance it easily without changing our code? The answer is yes.

    In this article we’ll see some of the limitations of both ways of creating animations and then how we can achieve better performance with our jQuery code.

    What’s the Problem With jQuery?

    We all know and love jQuery (actually some people don’t). This library, designed to simplify the client side scripting of HTML, has helped hundred of thousands (no real data intended) developers all over the world. It makes things like HTML document traversal and manipulation, event handling, Ajax, and much more a piece of cake, taking the burden to deal with all the browsers’ incompatibilities and bugs.

    Among its features, jQuery also allows to create animations and effects. With it, we can animate CSS properties, hide elements, fade them, and other similar effects. However, jQuery’s design goal has never been to be a performant animation engine, and it was never meant to support really complex, cpu/gpu-consuming animations. As a confirmation of this fact, jQuery’s memory consumption often triggers garbage collections that cause issues while an animation is performed. In addition, behind the scene jQuery uses setInterval() instead of requestAnimationFrame() (read more about requestAnimationFrame()) to run animations, that doesn’t help in producing high frame rates.

    Due to these factors, people “who know best” evangelized the use of CSS to create our animations and effects.

  10. 5 Grunt Tasks You Won’t Want to Miss!

    Unless you’ve lived under a stone for the past few months, you’ve surely heard about Grunt or one of the other task runners released like Gulp.js (more on this topic in our article An Introduction to Gulp.js). This family of tools has taken the frontend landscape by storm, revolutioning the way thousands of developers deal with tedious activities like concatenation, minification, image optimization, and so on.

    If you’re new to the world of task runners, and particularly to Grunt, you can either refer to the article Automate Recurring Tasks with Grunt or the Grunt getting started guide.

    In this article I’ll show you five Grunt tasks (sometimes referred as Grunt plugins) that you won’t want to miss!

    grunt-autoprefixer

    If you’ve recently spent some time writing CSS, you know that we have to deal with a lot of experimental properties and vendor prefixes. This activity is so painful that it has contributed to the success of websites such as Can I Use and CSS3 Please. Thanks to grunt-autoprefixer, this activity won’t be such a pain anymore.

    grunt-autoprefixer is a task based on the Autoprefixer library that parses CSS and adds vendor-prefixed CSS properties. The data that determines if a property needs one or more prefixes are extracted from the Can I Use database. In grunt-autoprefixer we can specify several options, but the most important one is surely browsers. The latter accepts an array of values that allows us to specify which browsers and versions we’re targeting in our project. The aim is to add only the prefixes we really need so our CSS will be as lightweight as possible.

    A basic configuration example for this task is shown below. In this configuration, we’ve specified a file to parse named main.css. The output is written to a file named `main-prefixed.css`. Additionally, the output will contain the prefixes for the last two versions of each browser supported, plus Internet Explorer 8, Internet Explorer 9, and Opera 12.1 (the last version to use the Presto engine).

    [js]
    grunt.initConfig({
    autoprefixer: {
    options: {
    browsers: ['last 2 version', 'ie 8', 'ie 9', 'Opera 12.1']
    },
    dist: {
    src: ‘src/css/main.css’,
    dest: ‘dest/css/main-prefixed.css’
    }
    }
    });
    [/js]