All Levels

How to Use Media Queries with jQuery

The evolution of smartphones and tablets has forced website owners to integrate mobile/tablet friendly (or responsive design) techniques. The creation of responsive design websites has subsequently evolved with new tools and frameworks. Media queries play an important role to create a responsive design as it allows content rendering to adapt to conditions such as screen resolution (e.g. smartphone screen vs. computer screen). Media query is a CSS module which was introduced with CSS3. But, did you know it can still be used with jQuery? It can! Let’s learn more about media queries and how you can implement them with jQuery.

What are media queries?

Before we look at jQuery, here is a brief introduction about media queries. CSS Media queries allow you to target CSS rules based on – for instance – screen size, device-orientation or display-density. This means you can use CSS Media Queries to tweak CSS for an iPad, printer or create a responsive site. It uses [email protected] to include a block of CSS properties only if a certain condition is true.

As an example, if the browser window is smaller than 300px, the background color will change to yellow:

@media only screen and (max-width: 300px) {
     body {
         background-color: yellow;
     }
 }

The above is a pretty familiar piece of CSS3 code for handling screen sizes. Media queries can handle the responsive UI design pretty well, but what if you want to change some of the functions of the site based on screen size? What if you need to use different code blocks or JS functions based on different screen sizes? In a case like this, you’ll need a way to run these media queries via jQuery. Unfortunately, at this point there are no solid predefined methods which provide actual information about screen size. Therefore, you’ll need to use a third party library named Modernizr with jQuery in order to implement media queries.

What is Modernizr 

Modernizr is a JavaScript library which is designed to detect HTML5 and CSS3 features in various browsers, which lets JavaScript avoid using unimplemented features or use a workaround such as a shim to emulate them. Modernizr aims to provide this feature detection in a complete and standardized manner.

According to the official site, “Modernizr is a small piece of JavaScript code that automatically detects the availability of next-generation web technologies in your user’s browser. Rather than blacklisting entire ranges of browsers based on “UA sniffing,” Modernizr uses feature detection to allow you to easily tailor your user’s experiences based on the actual capabilities of their browser.”

In other words, it detects browser features to find out if things are supported or not. It tells you what HTML, CSS and JavaScript features the user’s browser has to offer.

Let’s see an example of the program in action. Imagine if you wanted to detect whether an audio feature introduced with HTML 5 is supported by the browser…

How to use Modernizr? 

First, download the Modernizr library from the download page. Select the features which are required for your project and select “Build.” This will ensure that you no longer need to include features which you may not use, and it reduces the library file size also. Once downloaded, include the reference in your page:

<script src="modernizr.js" type="text/javascript"></script>
And then in your JavaScript code, you can check it like this:
if (Modernizr.audio) {
   /* Audio supported */
}
else{
/* Audio not supported */
}

Simple and easy. Now let’s see how modernizer can help when jQuery allows the use of media queries!

 How to use media queries with jQuery

Before we get into Modernizer with jQuery, you may want to think about using the inbuilt width() function which returns the width of any matched element. This can be used with $(window) object to get its width like this:

if($(window).width() < 481)
{    // It’s a Phone.}
elseif($(window).width() < 769)
{    // It’s a tablet.}
else { // It’s a desktop/laptop.}

But, the issue with the width() function is that it doesn’t return the correct value of the window as it takes into effect things like body padding and scroll bars on the window. Therefore, we need Modernizer in order to get the correct information about the screen size.

Modernizer has lots of API to play with, one of which is Modernizr.mq. Modernizr.mq allows you to systematically check if the current browser window state matches a media query. Following JavaScript function returns the device type based on the screen size via running min-width media query. https://modernizr.com/download

var checkMod = function(){
   if(Modernizr.mq('(min-width: 480px)')){
     return “phone”;
   }
   else if(Modernizr.mq('(min-width: 768px)')){
     return “tablet”;
   }
   else{
     return “desktop”;
   }

Then you can call this function on the initial load, as well as the window resize event:

 $(document).ready() (function() {
     // Call on every window resize
     $(window).resize(checkMod);
     // Call once on initial load
     checkMod ();
 });

Remember, only calling this function on page load will not work when the window is resized. Therefore, you must call for it in both places (page load and window resize.)

Also remember only valid media queries will be supported, therefore you should always include the value with media query with ‘px’ suffixed to it.  For example,

Modernizr.mq('max-width: 640px') //Valid
Modernizr.mq('max-width: 640') //Invalid
Modernizr.mq('max-width') //Invalid

This way, you can also use media queries with jQuery.

What if browser doesn’t support media queries? You can use modernizer to detect the same, like this:

if(Modernizr.mq('only all')) {
 // returns true if MQ are supported, false if not
}

Or you can use the following test:

Modernizr.addTest,
Modernizr.addTest("cssmq", function(){
   return !!Modernizr.mq("only all");
});

The most common way of creating your own feature detects is by calling Modernizr.addTest with a string (preferably just lowercase, without any punctuation), and a function you want to execute that will return a boolean result.

That’s it!

To conclude, CSS3 media queries help in handling different UI based on size and orientation. But sometimes we need to execute different code blocks based on the screen size and none of the inbuilt jQuery methods give correct details about this factor. Hence, a third party library called Modernizr comes to the rescue in this case. Modernizr is the most popular library for creating a responsive website design. It can help to run media queries with jQuery to handle responsive design and it can also detect whether media queries are supported by the browser.

How to Sort HTML Table Using jQuery Code

HTML tables are useful for displaying data in a tabular format. Tables tend to look elegant and clean. However, HTML tables are even more useful when data is sorted in columns in an ascending or descending order. In this post, we’ll learn how to sort an HTML table using jQuery without using any jQuery plugins. Though, there are plenty of jQuery plugins available which can perform the same task, but as a best practice if things can be achieved via plain jQuery code, you should avoid using jQuery plugins.

HTML Markup

First of all, create a standard HTML table on the page. For the demo, our table has 3 columns: Name, Age, Country and some random data. Our goal is to make these columns clickable and then sort the table data accordingly.

<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Maria Anders</td>
    <td>30</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Francisco Chang</td>
    <td>24</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Roland Mendel</td>
    <td>100</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Helen Bennett</td>
    <td>28</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Yoshi Tannamuri</td>
    <td>35</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Giovanni Rovelli</td>
    <td>46</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td>Narendra Sharma</td>
    <td>56</td>
    <td>India</td>
  </tr>
  <tr>
    <td>Alex Smith</td>
    <td>59</td>
    <td>USA</td>
  </tr>
</table>

CSS

The following CSS classes are used to style the tables:

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}
td,th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}
tr:nth-child(even) {
  background-color: #dddddd;
}

Now, the HTML table will look like this,

Screen Shot 2017-03-21 at 10.15.52 AM

Let’s add the CSS classes required for highlighting the clicked column, adding up or down symbols, indicating the sorting order and a CSS class to highlight columns on mouse over event:

.focus {
  background-color: #ff00ff;
  color: #fff;
  cursor: pointer;
  font-weight: bold;
}
.selected {
  background-color: #ff00ff;
  color: #fff;
  font-weight: bold;
}
.asc:after {  content: "\25B2"; }
.desc:after { content: "\25BC"; }

jQuery Code

To sort the HTML table, the solution would be to get the complete table data in an array and then perform the sort operation on the array based on the clicked column and considering the sort order.

Below is the complete jQuery code:

$(document).ready(function() {
  $('th').each(function(col) {
    $(this).hover(
    function() { $(this).addClass('focus'); },
    function() { $(this).removeClass('focus'); }
  );
    $(this).click(function() {
      if ($(this).is('.asc')) {
        $(this).removeClass('asc');
        $(this).addClass('desc selected');
        sortOrder = -1;
      }
      else {
        $(this).addClass('asc selected');
        $(this).removeClass('desc');
        sortOrder = 1;
      }
      $(this).siblings().removeClass('asc selected');
      $(this).siblings().removeClass('desc selected');
      var arrData = $('table').find('tbody >tr:has(td)').get();
      arrData.sort(function(a, b) {
        var val1 = $(a).children('td').eq(col).text().toUpperCase();
        var val2 = $(b).children('td').eq(col).text().toUpperCase();
        if($.isNumeric(val1) && $.isNumeric(val2))
        return sortOrder == 1 ? val1-val2 : val2-val1;
        else
           return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;
      });
      $.each(arrData, function(index, row) {
        $('tbody').append(row);
      });
    });
  });
});

The following is the outline of the jQuery solution.

First, check each table heading to see if it is hovered over. If any of the table headings are hovered over, then add .focus CSS class to it to highlight it. When the mouse is moved away from the heading column, remove the focus CSS class, which brings the column heading back to the initial style. This is done by attaching the hover event to column headings, to toggle the .focus CSS class.

Since the column heading has to be clickable, attach a click event to each column heading. In the click event, first check for the current sort order. If the column heading is clicked for the first time, the table must be sorted in ascending order by that column, and if the column is clicked again, the table must be sorted in descending order by that column. We defined 2 CSS classes: asc and desc. These classes are responsible for adding up/down arrows to the column headings and also tell us about the current sorting order.

Inside the click event, check if the column heading has asc class applied to it. If yes, then remove it and assign desc class. Along with this, apply the selected CSS class, which highlights the column on the UI. We also set the value -1 to the sortOrder variable. This sortOrder variable will be used while sorting in descending order. If the current sort order value is descending, then add asc CSS class and remove desc class. Also, set sortOrder value to 1.

Once we’ve sorted the column, remove the asc and desc classes from all the column headings except the selected one. Create an array variable arrData to store the complete table data. Here, exclude the header row and get data only for TD elements using jQuery get(). The get()returns an array of all of the elements.

Now, on the array variable arrData, call the sort function to sort items inside the array. The default implementation of the sort() method sorts the values as strings in alphabetical and ascending order. Since we want to sort on descending order also, the default implementation will not work.  The default implementation also fails to accurately sort the numerical values. The sort function takes an optional parameter: a compare function. We can leverage this parameter to fix all of the above problems.  If we define a comparison function, then a pair of values from the array will be repeatedly sent to the function until all the elements of the array are processed. In the comparison function we then write a statement considering the pair of values passed to it so that the function returns any of the following three values: <0, =0, or >0.

  • When the function returns the value <0, the second value (of the pair of array values sent to the function) is larger than the first value and hence must be pushed down the sorting order.
  • When the function returns the value >0, the first value is larger than the second value, so it must be pushed down the sorting order.
  • When the function returns the value =0, it means there is no need to change the sorting order since the two values are same.

When this sort function is complete, the arrData array will have all the rows sorted by the selected column and value assigned to the sortOrder variable for ascending/descending order. Finally, the sorted rows from the arrData array are retrieved and appended to the tbody element of the table for display.

If you want to play around with the code yourself, check out the demo example on jsFiddle!

Conclusion

To sum it up, this post provides an easy jQuery solution that enables sorting on the HTML table columns in ascending and descending order. The solution also takes care of issues with the default implementation of sort() function on an array. The best thing about this is, it is achieved without using any jQuery plugins (which are an overhead).

3 Useful jQuery Snippets for Handling Table Data

Do you want the ability to be able to dynamically edit and manage your tables? With jQuery, it’s pretty easy to get data and change table elements dynamically using only a few lines of code. The snippets below will show you how to add a new row to your table, how to retrieve all values in a row from a click event, and how to count the number of rows that a table has by using simple and lightweight plain jQuery code.

Counting Table Rows

If you find yourself wanting to know how many rows are in your table, you can use the following snippet to let jQuery do all the calculations for you:

$("#my-table").after(function () {
 console.log($('tr', this).length + " rows.");
});

The code above logs to the console how many rows are in your table with the ID of “my-table”, and it only takes two lines of jQuery to do it!

Get Row Values from Click Event

What if you want to be able to click on a table row and have all the data within the cells of that row be logged to the console? Achieving this is actually pretty straightforward. Check out the code snippet below to see how it’s done using jQuery:

$(“#my-table tbody”).on(“click”, “tr”, function () {
var rowdata = $(this).closest(‘tr’).find(‘td’).map(function () {
return $(this).text();
}).get().join();
console.log(rowdata);
});

In only 5 lines of jQuery, you can log all the data of a table row to your console just by clicking on it. As you can see, the trigger is a click event, and then we use other jQuery methods like find, map, and join events to gather all the data before logging it to the console.

Add Row on Click Event

This code will add a new row below any row that you click on using jQuery. Be sure to customize the row variable so that the amount of cells the new row has matches the amount of your table. Check out the code snippet below.

$(function () {
 $("#my-table tbody").on("click", "tr", function (e) {
 if (e.target.type != "text") {
 var row = $("<tr><td><input /></td><td>-</td><td>-" +
 "</td><td>-</td><td>-</td></tr>");
 $(this).after(row);
 }
 });
});

 

How to Implement Automatic Scrolling with jQuery

Automatic scrolling is a feature that causes a web page to scroll down automatically at a predetermined and configurable rate. This is quite a useful feature for websites that contain long articles, posts or some other lengthy web content. This feature saves users from having to scroll the page using their mouse or keyboard. In this post, let’s look at a few ways to implement automatic scrolling for any website using jQuery.

HTML Markup

First of all, we want this feature to be easily configurable so that the user has the option to…

  • start and stop automatic scrolling
  • set the rate
  • set how much pixel the screen should scroll automatically.

Therefore, we need 2 input boxes to get time and pixel value:

Time (in Seconds) :

<input type="text" id="txtTime" value="3" />

Pixel :

<input type="text" id="txtPixel" Value="100"/>

By default, the time is set to 3 seconds and the pixel value is set to 100 pixels.

We also need 2 HTML buttons to start and stop scrolling:

<input type="button" id="btnStart" value="Start Scrolling" />
<input type="button" id="btnStop" value="Stop Scrolling" />

Finally, we will also require another button that will become visible only when ‘stop scrolling’ is clicked:

<input type="button" id="btnStartHidden" style="display:none;" value="Start Scrolling" />

By default, this button will be hidden. When ‘stop scrolling’ is selected this button becomes visible in the top-left section of the page. This is necessary so that when the user wants to start scrolling again they can easily do so by clicking here. The stop scrolling button scrolls along with the content of the webpage so that the user can stop scrolling at any time without backtracking to the top of the page.

The HTML will look like this:

Screen Shot 2017-03-08 at 3.56.33 PM

CSS

The following CSS classes are used to style and position the elements present on the HTML page. These CSS classes both style the buttons and set their positions. There is also a CSS class defined for the hidden button to position it at the top left of the page:

input[type="text"] { width:50px; }
 #btnStop {
position: absolute;
right:0px;
top: 0px;
background-color: red;
}
#btnStartHidden {
position: absolute;
left:0px;
top: 0px;
}
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 10px 12px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}

jQuery Code

To implement this functionality, we will need to use JavaScript setInterval() and clearInterval().The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds). The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.  The clearInterval() method clears a timer set with the setInterval() method.

The following is the outline of the jQuery solution:

  • Define the global variable as scrollInterval. This will be responsible for handling the setInterval() and clearInterval() timer.
  • Retrieve the time value now as it will be used in different parts of the code so better to fetch it once and store it in a global variable. Since setInterval takes the timer value in milliseconds, you’ll want to multiply the seconds by 1000 to get the millisecond value:
var scrollInterval = false;
var iSeconds = $('#txtTime').val();
iSeconds = parseInt(iSeconds) * 1000;
  • Create a function named AutomaticScroll. This will scroll the page and set the position of the ‘Stop Scrolling’ button to inline with the page scroll position. This function also reads the input value of pixels and use time defined in a global variable to get the correct scroll position based on user preference. It is also responsible for stopping the scroll once the end of the page is reached. If we don’t set the scrolling function to stop the setInterval will keep on calling this function, which is not required.
function AutomaticScroll() {
     var nScrollTop = $(window).scrollTop();
     if (parseInt(nScrollTop + $(window).height()) == $(document).height()) {
clearInterval(scrollInterval);
return;
}
      var nPixel = $('#txtPixel').val();
nScrollTop = nScrollTop + parseInt(nPixel);
$('html, body').animate({ scrollTop: nScrollTop }, 1000);
$('#btnStop').animate({"top": nScrollTop + "px"}, 1500);
 }
  • On click of Start Scrolling button, make a call to the AutomaticScroll function using setInterval(). Here the scrollInterval variable holds the reference of setInterval(). So if we wish to stop the scrolling, we pass this reference to the clearInterval() function:
$('#btnStart').click(function() {
scrollInterval = setInterval(AutomaticScroll, iSeconds);
 });
  • On click of Stop Scrolling button, the reference of the setInterval() variable is cleared using clearInterval(). At this point the hidden button will also appear so that the user can begin scrolling again at any time. The hidden button will be visible on the top left corner of the page. Like this:

 

$('#btnStop').click(function() {
clearInterval(scrollInterval);
var nScrollTop = $(window).scrollTop();
if(nScrollTop != 0)
{
$('#btnStartHidden').show(500);
$('#btnStartHidden').animate({"top": nScrollTop + "px"}, 500);
}
  });
  • When the hidden button is selected, we again call the AutomaticScroll function with setInterval to start scrolling again. At this point we also hide this button again with some animation:
$('#btnStartHidden').click(function() {
scrollInterval = setInterval(AutomaticScroll, iSeconds);
$(this).hide(1000);
 });
  • We also need to handle the positioning of the stop scrolling button when scrolling is stopped by the user and the user moves to the top of the page using the browser’s scrollbar. Since the stop scrolling button’s position is absolute, we need to move it to the top of the page as well. So, attach a scroll event to the window object and check for the scroll position using scrollTop. ScrollTop reads the current vertical position of the scroll bar for the first element in the set of matched elements or sets the vertical position of the scroll bar for every matched element.

As an example, scrollTop value 0 would be the top of the page. So we hide the hidden button and also set the position of the ‘stop scrolling’ button so that it is shown in the top right corner, like this:

$(window).scroll(function(){
var nScrollTop = $(window).scrollTop();
if(parseInt(nScrollTop) == 0)
{
$('#btnStartHidden').hide();
$('#btnStop').animate({"top": nScrollTop + "px"}, 1500);
}
 });

Finally, here is the complete jQuery code:

$(document).ready(function () {
  var scrollInterval = false;
  var iSeconds = $('#txtTime').val();
  iSeconds = parseInt(iSeconds) * 1000;
  function AutomaticScroll() {
     var nScrollTop = $(window).scrollTop();
     if (parseInt(nScrollTop + $(window).height()) == $(document).height()) {
clearInterval(scrollInterval);
return;
}
      var nPixel = $('#txtPixel').val();
nScrollTop = nScrollTop + parseInt(nPixel);
$('html, body').animate({ scrollTop: nScrollTop }, 1000);
$('#btnStop').animate({"top": nScrollTop + "px"}, 1500);
 }
 $(window).scroll(function(){
var nScrollTop = $(window).scrollTop();
if(parseInt(nScrollTop) == 0)
{
$('#btnStartHidden').hide();
$('#btnStop').animate({"top": nScrollTop + "px"}, 1500);
}
 });
 $('#btnStart').click(function() {
scrollInterval = setInterval(AutomaticScroll, iSeconds);
 });
 $('#btnStartHidden').click(function() {
scrollInterval = setInterval(AutomaticScroll, iSeconds);
$(this).hide(1000);
 });
 $('#btnStop').click(function() {
clearInterval(scrollInterval);
var nScrollTop = $(window).scrollTop();
if(nScrollTop != 0)
{
$('#btnStartHidden').show(500);
$('#btnStartHidden').animate({"top": nScrollTop + "px"}, 500);
}
  });
});

You can also check the demo at following link!

 

<h2>Conclusion</h2>

To sum it up, we saw how to implement the automatic scrolling functionality based on user defined time and pixel value. The solution also gives the flexibility to the user to stop the scrolling at any point, and then start it again if they wish. This functionality is useful for lengthy articles and it will save user’s time in scrolling the page.

3 jQuery Snippets for Handling CSS Classes

CSS isn’t really a very dynamic or flexible language, but with the help of jQuery, it’s easy to make certain styles dynamic and changeable with just a few simple lines of code. What follows are 3 really useful and easy ways to manipulate CSS classes using jQuery.

Check for Class

In jQuery, there’s a built in method that allows you check if a certain selected HTML element has any particular CSS class assigned to it. If it does, then you can execute other jQuery code (for example, removing the class, adding HTML, changing the class) based on this fact. See the snippet below for an example of how it would look to check a div for a class called “.main”:

if ($("div").hasClass("main")){
  // insert code here
}

Remove Class

Removing a CSS class from an HTML element is another easy thing to do using jQuery. Often this removal of a class will happen as the result of a trigger event, and once that trigger takes place, the code to remove a class from an element will be executed. To see how to remove a class (“.this-class”) from a div element after it’s been clicked, check out the snippet below:

$("div").click(function{
   $(this).removeClass("this-class");
})

Toggle Class

You can also use jQuery to toggle between classes, meaning that you can have one class assigned to an HTML element, and then based on a trigger event (a click event like we used above, perhaps), the class can be removed. When the trigger event occurs again, the original class will be assigned to the element once more. The difference between .toggleClass and something like .removeClass is that toggle will keep removing and adding the class as the trigger event keeps occurring, but .removeClass will simply remove the class, never add it back. See the snippet below for an example of how you’d toggle the class “.toggle-class” when a div is clicked:

$("div").click(function{
   $(this).toggleClass("toggle-class");
})

Different Methods of Error Handling in jQuery

Errors are part and parcel for code. That being said, they can certainly result in a very bad user experience, especially if errors are not handled properly. Every code becomes perfect or bug free after a couple rounds of testing and fixing errors. Client side errors are difficult to handle, as most of the time they don’t occur at the time of compilation and instead rear their ugly heads at runtime only. The big problem with client side errors is that they are silently blocked. Client side errors are either displayed in the browser status bar or in the browser console, which makes them difficult to report. In this post we’ll look at different methods of handling errors in jQuery.

Types of Errors

Basically, there is no categorization when it comes to the types of errors, but some potential errors include syntax errors, coding errors, typos, incorrect business logic or incorrect input. The worst part about errors is that further execution of the code is halted and an error message is displayed. This will always throw a wrench in your plans, so let’s look at ways of handling it!

Using Try Catch

We all know jQuery is a library written on top of JavaScript. So traditional JavaScript techniques or functions are available within jQuery also. As a developer, you must be familiar with ‘try/catch’ and ‘finally’, which can both help you easily detect and handle errors.  All you need to do is put your error prone code inside a try block and catch block will catch the error. The syntax is quite simple.

try {
  // Your code goes here…
}
catch(err) {
 // Handle the error here.
}

Along with ‘try/catch’, there is also a ‘finally’ block. The finally statement lets you execute code, after try/catch, regardless of the result. In other words, it’s always executed.

try {   // Your code goes here… }
catch(err) { // Handle the error here. }
finally { // Code always executed regardless of the result.
}

The try block must be followed by either exactly one catch block or one finally block (or one of each). When an error occurs in the try block, the error is placed in err (argument passed in the catch block) and the catch block is executed. The finally block executes unconditionally after try/catch.

Let’s look at an example:

Here, we will try to reference two undefined variables. So when the code reaches to that line, an error is thrown and the call goes directly to the catch block. The catch block will catch the error and then display it in a DOM element with id “error”:

try {
 var iResult = j/k; // Undefined variables will cause an error.
}
catch(e) {
   $('#error').val(Error Name: ' + e.name + ' Error Message: ' + e.message);
}

Remember, the catch block will get executed only when there is an error thrown by the try block. The error object passed into the catch block has 2 properties: name and message. The name property holds the error type, while the message property holds the actual error message. Please read this link for more details about the error object.

Normally, we don’t have any control on the error message displayed by the JavaScript as its part of the Error object. However, it’s always nice to have your own custom error messages rather than the standard error message, and there is actually a way to do this. Along with the try/catch blocks, there is also another option: the throw statement. The throw statement allows you to create a custom error. It is like throwing an error, which the catch block catches and handles, like so:

try {
  var iVal = $('#txtVal').val();
  if (iVal == '') throw "Value is empty.";
  if ($.isNumeric(iVal) == false) throw "Not a number";
}
catch(e) {
   $('#error').val(e);
}

When throw is used, then the error object will contain the custom message only and it will log the same.

Using window.onError

“Window.onerror” acts like a global try/catch block which means that it can catch an error from anywhere in the code. It’s indeed one of the easiest ways to log client-side errors and report them to your server. When there is an uncaught exception or compile-time error, the window.onerror event handler is called with information about the error. The syntax is as follows:

window.onerror = function (message, source, lineno, columnNo, error) {
    // perform error handling here with file name and line number
    // for later processing
    return true; // The exception is handled, don't show to the user.
}

Here is a list outlining the descriptions of arguments passed to onerror:

  • Message – The message associated with the error, e.g. “Uncaught ReferenceError: j is not defined”
  • Source – The source of the script or document where the error was generated. 
  • LineNo – The line number where the error is found.
  • ColumnNo – The column number.
  • Error – The error object associated with this error.

Here’s an example to make this concept a little easier to understand:

function func1() {
 var iResult = j/k; // Undefined variables will cause an error.
}
window.onerror = function (message, source, lineno) {
  console.log("Error: " + message + " at line " + lineno + " in " + source);
}

The above code will log the error to the console with all the information. This function can be customized and server side logging can be done via making Ajax calls and passing the error objects.

jQuery.readyException()

If you are using the latest version of jQuery (3.1), then you can take advantage of the newly introduced handler called jQuery.readyException() which handles the errors thrown synchronously in functions wrapped in $.jQuery.

From jQuery documentation,

“This method is fired when an error is thrown synchronously in a function wrapped in jQuery() or jQuery( document ).ready(), or equivalent. By default it re-throws the error in a timeout so that it’s logged in the console and passed to window.onerror instead of being swallowed. Overwrite this method if you want to handle such errors differently.”

Let’s look at another example.

The following jQuery code tries to call a method named “doSomething()” on an object which is null:

$(document).ready(function() {
  var obj = null;
  obj.doSomething();
})
jQuery.readyException = function(error) {
  console.error(error);
};

When the error occurs, it reaches to the readyException handler which simply logs the error to the console. Here you can add code to perform server side logging or writing to a file.

Conclusion

Regardless of the nature of the client-side error, it is essential that all errors be handled swiftly. Here we learned a few different methods for handling errors, including: try/catch or windows.onerror, or the newly introduced jQuery.readyException handler (available with jQuery 3.1.0). You can customize the error handling based on your needs for server side logging, simply logging it to the console or writing to a file.