Beginner

Handling JSON with jQuery

JSON (JavaScript Object Notation) is a way to store information in an organized manner. It is the preferred data-interchange format as its shorter, lightweight, human-readable and requires no tags like XML. This allows faster processing and transmission, and also the serializing and deserializing becomes much faster when compared to XML. JSON returned via REST APIs is used in different ways on the client side. You can populate data in HTML elements, display the JSON on the UI after formatting and convert it to CSV for exporting. This post provides jQuery solutions for formatting the JSON, converting it to CSV format, and showing the JSON data in an HTML table. Let’s begin!

Format JSON in jQuery

Unformatted JSON is not human-readable and most of the time the JSON returned by REST APIs are not formatted, hence can’t be displayed directly on the UI. There are different ways to format it. Either using your own implementation or third-party plugins. Formatting the JSON using jQuery can be done easily and requires only 2 function calls.

  1. JSON.parse() – To parse a JSON string and convert it to a JavaScript object.
  2. JSON.stringify() – Convert a JavaScript object into a string. You can also apply indentation by passing an optional value.

The following jQuery code formats a JSON string:

var jData = '[{"fname":"Mark", "lname":"Wood", "company":"Apple"},' +
'{"fname":"Steve", "lname":"Jones", "company":"Amazon"},' + 
'{"fname":"Bill", "lname":"Peterson", "company":"HP"},' +
'{"fname":"Peter", "lname":"Jacobs", "company":"Dell"}]';

var tmpData = JSON.parse(jData);
var formattedJson = JSON.stringify(tmpData, null, '\t');

Here, the formattedJson variable will have the formatted JSON string, indented using tab. To display formatted JSON on UI, use the <pre> tag only. If you want to display inside a div, you would need to first append the <pre> tag in the div element. Like:

$('#dvText').append($('<pre>').text(formattedJson));

You can check out the demo here.

Convert JSON to CSV

If you want to convert JSON data to CSV for export purpose, the following jQuery code will help you. The following jQuery code defines a function called ConvertToCSV which takes JSON string, converts to CSV and returns it. Since it’s not compulsory to have comma as a delimiter for CSV, the delimiter is passed from outside which helps in changing the delimiter in the future without changing the actual function. The function first converts the JSON data into an array and then loops through the array to create a delimited string.

var jData = '[{"fname":"Mark", "lname":"Wood", "company":"Apple"},' +
  '{"fname":"Steve", "lname":"Jones", "company":"Amazon"},' +
  '{"fname":"Bill", "lname":"Peterson", "company":"HP"},' +
  '{"fname":"Peter", "lname":"Jacobs", "company":"Dell"}]';

var seperator = ',';
var sCSV = ConvertToCSV(jData, seperator);

function ConvertToCSV(jData, delimiter) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var sReturnVal = '';
  for (var i = 0; i < arrJSON.length; i++) {
    var sLine = '';
    for (var index in arrJSON[i]) {
      if (sLine != '') sLine += delimiter;
      sLine += arrJSON[i][index];
    }
    sReturnVal += sLine + '\r\n';
  }
  return sReturnVal;
}

You can check out the demo here.
The above function just creates a delimited string, it doesn’t allow you to save it as a .csv file. If you wish to export/download the JSON data into a CSV file with column headings and an optional report title, the following jQuery code provides a solution for the same. The modified function now expects 3 more parameters: report title, flag to display header, and a file name. While calling the function, please consider following things:

  • If you don’t wish to have a report title, pass an empty string.
  • In case you don’t need a column header, pass ShowHeader as false.
  • Pass the file name without the .csv extension.

The function does the following things:

  • First, parses the JSON data in an object, if not already.
  • If report title is not empty, appends the title to the variable.
  • If ShowHeader is true, then loop through the array’s 0th element to get the header columns and then appends them in the variable.
  • Then loop the array to get the data and creates a delimiter separated string.
  • Once the loop is completed, check the variable for any errors. An empty value means the JSON data is not correct. In such a case, it logs the error and exits the function.
  • If everything is correct, then initialize file format. The file format is CSV in this case.
  • Then it creates a temporary anchor tag and appends it to the HTML body with hidden visibility. Assigns the href and download attribute values and calls the anchor click function. Finally, removes it again from the body as it’s no longer needed.
function ConvertToCSV(jData, title, ShowHeader, fileName, delimiter) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var strCSV = '';
  //Set title first.
  if (title.length > 0)
    strCSV += title + '\r\n\n';
  if (ShowHeader) {
    var headerRow = "";
    for (var index in arrJSON[0]) {
      if (headerRow != '') headerRow += delimiter;
      headerRow += index;
    }
    strCSV += headerRow + '\r\n';
  }
  for (var i = 0; i < arrJSON.length; i++) {
    var sLine = '';
    for (var index in arrJSON[i]) {
      if (sLine != '') sLine += delimiter;
      sLine += arrJSON[i][index];
    }
    strCSV += sLine + '\r\n';
  }
  if (strCSV == '') {
    console.log('Error while converting due to invalid data');
    return;
  }
  var uri = 'data:text/csv;charset=utf-8,' + escape(strCSV);
  var link = document.createElement("a");
  link.href = uri;
  link.style = "visibility:hidden";
  link.download = fileName + ".csv";
  $('body').append(link);
  link.click();
  $('body').remove(link);
}

Call this function on any event to convert the JSON data into a downloadable CSV file like:

ConvertToCSV(jData, "Employee Data", true, "EmployeeReport", seperator);

You can check out the code in action here.

Convert JSON to HTML Table

The following jQuery code will create a table element, populates the table data from JSON data and appends the table element to the HTML body. The function uses jQuery syntax for different table elements like header row and table row. Inside the JSON array loop, it appends the data in appropriate objects, and finally it is added to the HTML body.

function ConvertToTable(jData) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var $table = $('');
  var $headerTr = $('');

  for (var index in arrJSON[0]) {
    $headerTr.append($(' ').html(index));
  }
  $table.append($headerTr);
  for (var i = 0; i < arrJSON.length; i++) {
   var $tableTr = $('');
    for (var index in arrJSON[i]) {
      $tableTr.append($(' ').html(arrJSON[i][index]));
    }
    $table.append($tableTr);
  }
  $('body').append($table);
}

Here the table formatting needs to be handled via CSS. You can also incorporate the same in this code with slight modifications.
You can check out the code in action here.

Conclusion

This post provides simple solutions for handling JSON on the client side in different ways. The jQuery implementation helps in formatting the unstructured JSON, converting the JSON data into a CSV string or downloadable CSV file with customization and displaying the JSON data in an HTML table. These jQuery codes are not dependent on any third-party plugins, which helps you to modify them as per your need without any hassle.

JavaScript-Equivalent jQuery Code for Simple Tasks

Introduction

There are developers who love jQuery and there are some who hate jQuery. The benefits of using jQuery now are debatable, but there was a time when solving the cross-browser issue was a nightmare and using JavaScript was painful. If you had been through that phase, you might understand the importance of jQuery. jQuery was born to overcome the biggest issues of JavaScript. Over the years, JavaScript has also evolved but we should be thankful for the fact that modern browsers are also becoming more and more standard-compliant. jQuery is still a powerful library and it can still reduce your efforts for client-side programming.

The aim of this post is not to discourage your use of JavaScript, but rather to give you an insight into how jQuery can help to solve simple tasks compared to JavaScript. jQuery can help in reducing the lines of code and your efforts, lessen cross-browser compatibility issues, result in faster development, and it makes AJAX calls and animations dead simple. To start with, we’ll take a look at the most basic requirements like selecting elements on the page by their ID, class, and tag name and then we will look at some complex examples. Let’s dive in!

Selecting an Element by ID

JavaScript code

document.querySelector('#elmID'); // Modern Way - IE8 and above 
document.getElementById('elmID'); // Older Way 

jQuery code

$('#elmID');

As you can already see, we’ve used less code to select the element in jQuery.

Selecting an Element by Tag

Consider a use case to select all the paragraph elements on the page:

JavaScript code

document.getElementsByTagName('p'); 

jQuery code

$('p');

Again, shorter code in jQuery!

Selecting Elements by Class Name

To select all elements having dummy CSS class:

JavaScript code

document.getElementsByClassName('dummy'); // Older Way 
document.querySelectorAll('.dummy'); // Modern Way - IE8 and above

jQuery code

$('.dummy');

We can see a continuing trend of fewer and shorter lines of code in jQuery.

Change Body Background Color on Load

JavaScript code

function changeBackground(color) {
    document.body.style.background = color;
}
<body onload = "changeBackground('green');" >

jQuery code

$ ('body').css('background-color', 'green');

A single line of code accomplishes what takes four lines of code to accomplish in JavaScript.

Adding a CSS Class to Element

JavaScript code

if (el.classList)
  el.classList.add(className);
else
  el.className += ' ' + className;

jQuery code

$(el).addClass(className);

That’s three fewer lines!

Making an Ajax Call

JavaScript code

function loadValues() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById(“demo”).innerHTML = this.responseText;
        }
    };
    xhttp.open(“GET”, “/api/values”, true);
    xhttp.send();
}

jQuery code

function loadValues() {
    $.ajax({
        url: "/api/values",
        type: "GET",
        dataType: "json",
        success: function(data) {
            $('#demo').html(data);
        },
        error: function(response) {
            alert(response.responseText);
        }
    });
}

The jQuery version looks much cleaner and more readable, it also offers a better method for error handling.

Making a Simple Fade-Out Animation

JavaScript code

function fadeOut(element) {
    var op = 1; // initial opacity
    var timer = setInterval(function() {
        if (op < = 0.1) {
            clearInterval(timer);
            element.style.display = ‘none’;
        }
        element.style.opacity = op;
        element.style.filter = ‘alpha(opacity = ’+op * 100 + “)”;
        op -= op * 0.5;
    }, 500);
}
var element = document.getElementById(‘elm’);
fadeout(element);

jQuery code

$("#elm").fadeOut();

There is no need to judge here who is better: jQuery is the clear winner.

Conclusion

We’ve just seen how jQuery can make life much simpler for easy tasks. Some functionality can be achieved by just one line of code in jQuery that requires 15-20 lines of JavaScript to achieve the same result. jQuery is an awesome library and it’s still very popular among developers. You should consider it as an alternative for fast development and without worrying about cross-browser issues. However, you should also be careful as it's large file to load! 

Using jQuery to Delete All Inline HTML Styling

Inline HTML styling (when the style attributes for a particular element are written within the HTML tag) is not something that’s considered a best practice when it comes to HTML and CSS, and it’s becoming less and less common. You don’t often come across inline styling unless a site’s code hasn’t been touched since the 90s or early 2000s, but it’s certainly not unheard of. If you find yourself trying to do a redesign of an older site that contains inline styling within the HTML, you’ll almost absolutely find that overriding the inline styling can be a huge pain.

Rather than go through every HTML file to remove inline styling, all of your inline styling woes can be eradicated using a very simple jQuery code snippet, which will completely get rid of all of the style attributes that can be found within your HTML tags. To see how it works, take a look at the code snippet below:

$("*[style]").attr("style""");

The code snippet above uses jQuery to select every single style attribute (using the * selector in combination with the [style] attribute) and, using the .attr method, removes all of the values from the inline style elements by replacing the text with nothing (thanks to those empty quotation marks).

This is a super simple solution to getting rid of inline styling that can save you tons and tons of time and aggravation. If you’re working on a smaller site with less instances of style attributes within the HTML tags, then it might be wiser to just go through and remove them manually, but if you’ve got a big size with inline styling on every single page, then this is a great, super straightforward, and rather lightweight solution that will easily and quickly remove every single instance of inline style attributes so that the site in question can be updated to look its very best.

How to Use jQuery to Dynamically Open Links in New Tabs

Even if you’re a new or beginning developer, you probably know that you can easily make links open in new tabs by using the target attribute with your anchor tags. To make a link open in a new tab, all it takes is to make your HTML look like this:

<a href="/link/" target="_blank"></a>

The target=”_blank” attribute is all you need to make your links open in new tabs. But what if your anchor tags weren’t written this way, and you still want your links to open in new tabs? You can go back through your HTML and hand code it yourself, but if you’ve got a lot of anchor tags this could take you a really long time. Luckily, jQuery is here to save the day.

With jQuery,  you can use some really straightforward snippets to dynamically open all external links in new tabs without having to go through every line of your HTML with a fine-toothed comb. To see the snippet for yourself, check out the code below:

$('a[@rel$='external']').click(function(){
     this.target = "_blank";
});

That’s it. All it takes are two lines of  jQuery to make sure that all of your external links open in new tabs. The function is triggered by the .click() event method, so the function won’t run unless any of the external links are clicked on, so it’s a pretty lightweight solution. You can see that the snippet above uses the ‘a[@rel$='external']‘ selector. This can be used to select all of the external links, and apply the target=”_blank” attribute to it. But, if you find yourself wanting to select all of the anchor tags on your page, you can remove the rel code and simply use ‘a’ as the selector. You can also use a similar concept to select all links of one class or ID type by placing the class or ID name in the selector.

How to Use JavaScript to Detect Browser

Wouldn’t it be nice if all of our code looked the same and worked the same no matter what browser our users are viewing our projects or web pages on? That’s the dream, right? Unfortunately, cross browser compatibility isn’t something that a site can achieve without adding some extra code.

There a few ways that you can use code to compensate for different browsers. You can us CSS selector browser hacks, which is a good option, especially if any changes you need to accommodate for are mostly cosmetic and can be fixed with CSS. For more dynamic browser selections, JavaScript is actually a valid way to go.

Below, you’ll find a code snippet that you can use to check for Internet Explorer, Chrome, Firefox, Safari, and Opera. The function checks for these browsers, and will execute any code you insert within the if/else if statements for each browser if the code is run on any of the browsers in question. Use the code to dynamically add classes to your HTML based on the browser, to send alerts to the user based on the browser, to trigger events based on the browser.

The code snippet is lightweight and straightforward, so even the most beginner coders should be able to add it to their projects. Play around with it and see if you can’t achieve that elusive cross-browser compatibility!

function BrowserDetection() {
    //Check if browser is IE
    if (navigator.userAgent.search("MSIE") & gt; = 0) {
        // insert conditional IE code here
    }
    //Check if browser is Chrome
    else if (navigator.userAgent.search("Chrome") & gt; = 0) {
        // insert conditional Chrome code here
    }
    //Check if browser is Firefox 
    else if (navigator.userAgent.search("Firefox") & gt; = 0) {
        // insert conditional Firefox Code here
    }
    //Check if browser is Safari
    else if (navigator.userAgent.search("Safari") & gt; = 0 & amp; & amp; navigator.userAgent.search("Chrome") & lt; 0) {
        // insert conditional Safari code here
    }
    //Check if browser is Opera
    else if (navigator.userAgent.search("Opera") & gt; = 0) {
        // insert conditional Opera code here
    }
}

How to Use jQuery’s Mouse Methods

jQuery has 4 event methods that have to do with cursor movement. The methods are .mouseenter(), .mouseleave(), .mouseup() and .mousedown(). All of these methods can be used to trigger events and execute code based on when and where the user’s cursor moves. In terms of syntax, they’re fairly simple and straightforward to use, but they can also be really versatile and used to achieve some pretty cool functionalities and effects.

In this tutorial, we’re going to go over how to use each of the mouse event methods. Take a look at the code snippets below to for examples of how to use them in the context of your code.

.mouseenter() and .mouseleave()

The .mouseenter() and .mouseleave() methods are two that are often used together. You can probably guess what they do, but here’s a brief explanation. The .mouseenter() method is triggered when the cursor enters the selected element (here, the word “enters” means that the cursor moves over the element), and the .mouseleave() method is triggered when the cursor leaves, or stops moving over, the selected element.

There are many different effects you can achieve with these two methods. To see an example of how you might use them, check out the code below:

$("h1").mouseenter(function(){
     $(this).css("color", "red");
})
$("h1").mouseleave(function(){
     $(this).css("color", "blue");
})

In the code snippet above, the color of the h1 element that the cursor moves over turns red when the cursor is on top of it. When the cursor moves off of it, the color of the h1 element changes to blue.

.mouseup() and .mousedown()

The .mousedown() event is triggered when the mouse button is pressed down over a selected element (essentially, this is very close to the .click() method), and the .mouseup() event occurs when the mouse button is released over a particular element. Basically, it’s a click and release type of deal. Like .mouseenter() and .mouseleave(), these two event methods are often used in conjunction with one another. To see an example of how you would use it, take a look at the code below:

$("p").mousedown(function(){
     $(this).css("color", "orange");
})
$("p").mouseup(function(){
     $(this).css("color", "green");
})

In the code snippet above, the text color of the p element changes to orange when it’s clicked, and green when the click is released.