User Agent Values in jQuery
 
 

When you navigate to a web page, the browser you use sends a value called user agent to the web server. The web server is able to read this value and display content based on your browser user agent. Several other values are sent by your browser, but user agent is the primary one used to customize web page layouts based on the user's environment. In this article, we'll cover user agent and how you can use jQuery to detect this value sent to the server.

We'll also cover arrays. Arrays are a part of every programming language and framework. They represent variables that let you store multiple values in just one variable. They are distinct from objects, and they are much more useful when you just need to store several values with one data type. JQuery works with arrays similarly to other programming languages, but its syntax is slightly different when you work with loops and arrays. This article will show you how to use loops and arrays.

Browser Feature Detection

Before you get started with browser detection, you should know that user agent is not 100% reliable. Any variable sent by a browser can be spoofed. Spoofing occurs when you send a value that you want the server to read but isn't necessarily true. For instance, you can send the server a user agent of "Chrome" when you're really using Internet Explorer. This type of activity is usually done for testing, but it can be used for other purposes. We won't show you how to spoof, because it's not necessary when you're programming for browser detection, but just know that detection using user agent is not 100% reliable.

Another reason you want to detect browser information is to identify the features supported. When you detect the type of browser used to navigate to your page, you can make assumptions on what is available. However, to be more accurate it's better to detect features using the data sent from the user's browser. These features will tell you what you can do with the client side code including version support.

JQuery used to have a "browser" property that you would use to detect features compatible with the user's environment, but it's now deprecated. The jQuery engineers suggest you use third-party plugins such as Modernizr. We'll use Modernizr for the code examples to stay with the most recent version of jQuery's framework.

First, take a look at what the user agent string looks like. The following user agent tells you that the user has Chrome installed on an Apple Mac.

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36

You can use vanilla JavaScript to detect the browser's user agent. Because the user agent string is filled with information without any kind of parsing character, you must use the JavaScript "indexOf" property. Here is an example of detecting Chrome from the above user agent string.

<script>

if(navigator.userAgent.indexOf("Chrome") != -1 )

{

            console.log ("User has Chrome installed.");

}

</script>

In the above code, we just detect if Chrome is in the user agent string, but we mentioned that this type of detection isn't reliable. For the most part, the above code works but it can break your site if the user spoofs the agent string or you work with bots that crawl your site with faked user agent strings. You should use this type of browser detection with caution, but it's still widely used in some older application.

With user agent so untrustworthy, designers need another way to properly work with the different browser versions and compatible features. You can't neglect to detect browser especially with mobile compatibility and the numerous browser versions available today. The new way designers work with browser detection is to detect browser features rather than browser versions and operating system. When you detect specifically for features, you can more accurately design a page specific for each of your users without relying on a user agent string that can be knowingly spoofed.

You can use a combination of third-party tools and jQuery to detect feature availability in the browser. In some cases, you can use straight jQuery with no third-party tools. First, let's take a look at the standard jQuery feature detection for the HTML5 canvas. The HTML5 canvas is taking over for Adobe Flash integration. The HTML5 canvas lets you create animations in your web applications without requiring the user to install third-party applications, but it's only available if the browser supports HTML5. If you can support native browser features, it's better to work with them rather than extensions that your users might not have installed.

The following jQuery code detects if the user has HTML5 canvas support.

var canvas = document.createElement( "canvas" );

if (canvas.getContext && canvas.getContext( "2d" ) ) {

    drawAnimation();

} else {

    showWarning();

}

In the above code, we first dynamically create a canvas tag in the user's browser. If the browser supports the element, then you can retrieve the canvas element and work with its properties and methods. The "if" statement in this jQuery code detects if the canvas tag is active. If it is, then the "drawAnimation" function contains the statements to display the animation. If the tag does not exist, it indicates that the feature is not supported. You can display a warning to the user or show an alternative element.

This is just one example of detecting features rather than relying on user agent browser detection. We mentioned that the jQuery developers refer to Modernizr as a third-party tool that can make feature detection a bit easier. It's not completely necessary, but it does reduce the amount of code you need to write to detect feature support.

The following Modernizr code performs the same action as the previous jQuery code. Notice that it reduces the amount of code you need to write.

if ( Modernizr.canvas ) {

    drawAnimation ();

} else {

    showWarning ();

}

Notice it still runs the same functions if the canvas is supported or not supported, but you have reduced code. If you want to use Modernizr, you can download it from here. You choose the features you want to detect and download the libraries. The code is always the same as the previous example. You just need the name of the feature that you want to detect.

Array Functions

Working with arrays is a combination of using standard JavaScript syntax and the jQuery framework to loop through each value. Arrays are considered one of the more difficult concepts to master in any programming language, but once you understand the way they work you can write array code for any language.

You know the concept of storing a single value in a variable. Arrays take your code a step further and let you store multiple values in one variable. Let's first take a look at a standard JavaScript variable.

var total = 22;

That's all it takes. You create one variable name and assign it a value. What if you have several totals that you want to work with. With standard variables, you would need to work with the following statements.

var total1 = 22;

var total2 = 23;

var total3 = 24;

If you have 20 values to work with, you can see that this type of coding can be tedious and could lead to confusing, cumbersome scripts. Instead, you can use arrays. Let's take the three variables we created in the previous statement and combine it into one array.

var totals = [22, 23, 24];

You can also use arrays for strings. The following array holds three color values.

var colors = ["Red", "Blue", "Purple"];

The JavaScript language gives you an alternative way to create arrays. Some programmers think it makes the code easier to read, but both array statements create an array. The following code is also valid.

var colors = new Array ("Red", "Blue", "Purple");

The way you create an array will be your preference. If the above code is easier to read, then use it. However, both array statements have the same result.

Now that you know how to create an array, it's time to retrieve values. You need to retrieve the array's values to either send them to the server, store them in a database or just display the data to the user.

If you recall, we mentioned that all indexes start with 0. In any programming language, you'll access the first value of an array using the index 0. The second value is stored in index 1. The third is stored in index 2. The same structure is used in jQuery arrays. Let's say you want to display the first color value in a div container. The following jQuery code displays "Red" in a div with an ID of "main."

var colors = ["Red", "Blue", "Purple"];

$("#main").text(colors[0]);

The following code shows the second color in the array.

var colors = ["Red", "Blue", "Purple"];

$("#main").text(colors[1]);

Notice that each time we move up the index tree within the array variable, we add 1 to the index number. The index is the number showing within the brackets after the variable name.

What if you have 20 values in an array? It's not even uncommon to have a hundred or more values stored in an array. As you can see, writing code that retrieves indexes for an array with 100 values could be tedious and unnecessary. The jQuery framework saves you time and offers the "each" method. This method loops through each array index and lets you retrieve and edit the values stored.

Let's take a look at the code that works with the colors array.

$.each(colors, function( index, value ) {

 console.log( index + ": " + value );

});

In the code above, we call the each function that requires two parameters. The first one is the array we want to work with. In this example, we want to loop through the array "colors." The next parameter is the function that runs as you work through the array. The function takes the index and value parameters. The index is what you use to reference the values. In this example, we just write the index and its associated value to the console log, but you can send the data to a database or write it to the DOM. The point of the "each" method is that you don't need to manually reference each array value. It's necessary when you don't know the number of values you need to store in an array and you have several of them.

You can also use the each method to store values in an array. If you only have a few values to fill, you can use the index directly. The following JavaScript code stores the value "Orange" in the first array element.

var colors = ["Red", "Blue", "Purple"];

colors [0] = "Orange";

In this code, the array is initialized with "Red" as the first element value. We then change it to "Orange." We used the same basic syntax that we had for retrieving array values. You just need to reference the array with the right index.

If you need to fill an array dynamically, you can use the each method. It's also useful when you need to fill several array elements at a time. You can fill an array from a list of input values or even from a database. To illustrate the way the each method works for filling an array, the following code fills an array with numeric values.

$.each(colors, function( index, value ) {

 colors[index] = index + 1;

});

In this code, we're looping through each array index. We then assign the index a value of 1 + index. Therefore, index 0 contains the value of 1, index 1 contains the value of 2, and index 3 contains the value of 3. The loop continues until all array indexes are filled with a value.

One issue to note with arrays is that they are much different than the values they can contain in other languages. In other languages, arrays can only store values of the same data type. With jQuery, arrays are objects, so they can store different data types without causing syntax errors. However, objects work with a key and value pair in JavaScript.

For instance, the following code would normally cause syntax errors in other programming languages.

var colors = ["Red", "Blue", "Purple", 22];

Since 22 is an integer, this would normally give you an error in other languages. In JavaScript and jQuery, however, it will allow you to store the integer value with the string values. Just remember that you must account for these different values. If you tried to add a string and integer value, you could cause a bug in your code. This makes storing different data types in an array less preferable. If you do need to store different data types, it's better to use an object with key-value pairs.

The following code is an example of using an object instead of an array for mixed data types.

var colors = {

 "color1": "Red",

 "color2": "Blue",

 "color3": "Purple",

 "total":22

};

The above code is an object where you can reference a key (the first column) and retrieve the associated value. These objects are preferred when you need to work with mixed data types.

Arrays are more complicated than basic variables, but you will work with them in most of your applications. With browser feature detection, you can ensure that your code is fully functional with all of your users. Both of these tasks are common in everyday jQuery coding.