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.

How to Use jQuery’s .delay() Method

jQuery’s .delay() method is one that can be used, probably quite obviously, to delay code from being executed. In particular, it can be used to make certain actions or animations last longer because the code is delayed. As a developer, there are a bunch of different reasons that you might want to use a delay. Maybe you want things to load or animate a certain amount of time after a page load or an event trigger. Using this method is also a really easy way to have something happen, have a short delay, and then go back to the way that it was.

For example, if you want a div to hide after a certain trigger event and then show again after a certain delay, you would use the delay method in a similar context to the way its used in the snippet below:

$("div").click(function{
    $(this).hide().delay(5000).show();
})

So in the snippet above, the div will be hidden after you click it for 5000 milliseconds (5 seconds) and then after the 5000 ms delay, it will appear again. The first line with the .click() method is the trigger event, which is followed by a function that executes the hide/delay/show events. So the div is hidden, then there is a 5 second delay where no code is executed, and then it is shown again.

This is just one example of how to use this versatile method. The speed parameters taken by the method (in the example above it’s “5000) can either be a number value (in milliseconds) or a fixed value (slow or fast). This is quite important, as it determines the length of time of the delay and, in the example above, the duration of the hide/show effect. Remember when using number values that the time is measured in milliseconds, so multiply the amount of seconds you want the delay to last by 1000 to be sure that you’ve got the right time.

How to Use JavaScript to Detect Devices

The great thing about JavaScript is how it enables you to dynamically make changes to your code based on certain events or conditions. One such condition that might cause you to want to make changes to  your code (or at least some slight modifications) is which type of device is being used to view your projects or web pages. This is because each mobile device (iPhone, Android, iPad, etc) have different dimensions and aspect ratios that unfortunately don’t always respond to your code and display your designs in exactly the way you’d like. Luckily, JavaScript provides a very easy and simple way to test for a particular type of device and execute some code based on whether or not your user is using the particular device you’ve singled out.

Check out the snippet below to see how it works:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
 // Do something
} else {
 // Do something else
}

Obviously, the snippet as it stands wouldn’t really do anything. You ned to choose one of the 7 device options provided and use that with the .test() method to test for that one particular device you’re trying to compensate for (if you want to set code specific to another type of device, you’ll have to add another if statement). Then, once you’ve selected the type of device you’re trying to write code for, you can insert the code you want to be executed into the if statement. You can be trying to change the color, shape, or dimensions your elements so that they better fit within the viewports of your chosen type of device, or you can simply use the code to troll iPhone users (see example below) — it’s totally up to you.

Check out the example below to see one way in which you can use the device detector code.

if( iPhone.test(navigator.userAgent) ) {
 alert("Androids Rule");
} else {
 alert("Congratulations, you're not using an iPhone");
}

How to Find the Coordinates of Your Mouse Position

Did you know you can use jQuery to find the coordinates of your cursor? It only takes a few lines of code to get the x and y coordinates of where the mouse is positioned on a page. With these coordinates, you can execute other functions and lines of code based on where the cursor is located on the page. It’s also just a cool trick to offer your users — for example, you can choose to allow them to click a button that will reveal the x and y coordinates of their mouse.

Check out the code snippet below to see how it’s done:

function cursorPosition(elementID, mouseX, mouseY) {
  var offset = $('#'+elementID).offset();
  var x = mouseX - offset.left;
  var y = mouseY - offset.top;

  return {'x': x, 'y': y};
}

Insert the above function into your code to reveal the values of the x and y coordinates of your cursor’s position. This code can be customized to be used however you like it — if you want to execute a function based on the cursor’s position, you’ll probably need an if statement. If you want to reveal the cursor’s coordinates to your users, you might want a click event (or some sort of trigger event) and code that will make the data available to the user (perhaps an alert box). The possibilities are endless.

Handy jQuery Code Snippets for Textboxes

Code snippets are great time savers as these are essentially just reusable pieces of code. Implementing client side validations can be done using jQuery, as well as some other basic tasks like clearing value or enabling and disabling textboxes. This post provides a list of useful jQuery code snippets for handling textbox related tasks with ease. These snippets are useful for validation, clearing out values on key stroke, copying one textbox value to another in real time and several other tasks. Check it out!

1. Clear input textbox value using ESC key

The ESC key is mainly used for cancelling your current process, closing popups, or clearing out input. If you wish to implement textbox value clearing when the ESC key is pressed, then following jQuery code will help you achieve this. It checks for the ASCII code of the key and if it matches with the ASCII code of the ESC key, then it simply clears the value of the textbox in focus. Like this:

$(document).ready(function() {
    $('input[type="text"]').keyup(function(e){
        if(e.keyCode == 27) {
            $(this).val('');
        }
    });
});​

2. Clear input textbox on page load

Following jQuery code will clear all the input-type textboxes, when DOM is ready. It loops through all the textboxes present on the page and within the loop, clearing its value.

$(document).ready(function() {
    $('input[type=text]').each(function() {
        $(this).val('');
});
});​

If you want to clear the value of the event in focus, then use the following jQuery code:

$('input[type=text]').focus(function() {
      $(this).val('');
   });

3. Allow only numbers in textbox

As part of some form validations, there may be a restriction that only allows numbers in the textboxes. For example, when the value represents age, price, number of days, etc. The following jQuery code will allow only numbers in the textbox with ID “txtNumber”. It uses the keydown event to detect the user input value’s ASCII code. In this case the ASCII code must be in a range of numbers. The following code allows keys like backspace for clearing the value and TAB keys for moving out of the textbox:

$(document).ready(function(){
   $("#txtNumber").keydown(function(e)
   {
       if (e.shiftKey)
           e.preventDefault();
       else
       {
           var nKeyCode = e.keyCode;
           if (nKeyCode == 8 || nKeyCode == 9) //Ignore Backspace and Tab
               return;
           if (nKeyCode < 95)
           {
               if (nKeyCode < 48 || nKeyCode > 57)
                   e.preventDefault();
           }
           else
           {
               if (nKeyCode < 96 || nKeyCode > 105)
                 e.preventDefault();
           }
       }
   });
});
4. Disable Cut, Copy and Paste operation

The following jQuery code will disable ‘cut’, ‘copy’ and ‘paste’ operations on the input text boxes. Using the jQuery .on() method, the ‘cut’, ‘copy’ and ‘paste’ events are attached to all input text boxes and the code will prevent the default behavior, like this:

$(document).ready(function(){
  $('input[type="text"]').on("cut copy paste",function(e) {
      e.preventDefault();
  });
});

5. Set focus on the first textbox of the page

The following code will set the focus to the very first enabled input textbox on the page, when the page is originally loaded:

$(document).ready(function(){
   $('input[type=text]:enabled:first').focus();
});

But if the very first textbox is not visible, for example if it is set to “display:none;” then the above code will fail. So the best solution is to check for visible and enabled textboxes and then set the focus. Like this:

$(document).ready(function(){
   $('input[type=text]:visible:enabled:first').focus();
});

6. Turn off autocomplete for all textboxes

These days most modern browsers cache every single input and smartly houses a list based on the input, like a list of email addresses for an email address inbox. When you visit any website, the browsers will display a list of all previously used inputs. When this is not necessary for your work, it can be quite frustrating. If you wish to disable autocomplete for all textboxes present on the page, the following jQuery code will help:

$(document).ready(function(){
  $('input[type="text"]').attr("autocomplete", "off");
})

Though you can set the autocomplete=”off” attribute on textboxes, you will have to set it for all the text boxes and that takes time. Instead, use the single line of jQuery code and you can achieve the same for all the text boxes present on the page at once!

7. Copy value from one textbox to another while typing

If you wish to copy the content of one input textbox to another in real time, the following jQuery code will do the job. This jQuery code attaches a keyup event to the source and then assigns its value to the destination textbox:

$(document).ready(function() {
    $('#txtSource').keyup(function(e) {
        $('#txtDestination').val($(this).val());
    });
});

The above code will copy the text from one textbox to another. But if you wish to sync multiple textboxes then assign a CSS class to every textbox which should be part of syncing and then bind the keyup event to the CSS class selector. The HTML code will look something like this:

<input type="text" id="txt1"/>
<input type="text" id="txt2" />

Below is the jQuery code that binds the event to copyText and assigns the same value to all the elements that have copyText CSS class:

$(document).ready(function() {
    $('.copyText').keyup(function(e) {
        $('.copyText').val($(this).val());
    });
});

8. Convert textbox value to uppercase

The following jQuery code will convert the textbox’s value to uppercase lettering when the focus goes out of the textbox. toUpperCase() is a JavaScript method which converts the string to upper case letters:

$(document).ready(function() {
    $('#txtSource').blur(function(e) {
        $(this).val($(this).val().toUpperCase());
    });
});

You can also set to lower case using the toLowerCase() method. Like this:

$(this).val($(this).val().toLowerCase());

9. Change textbox width on focus and restore on focus out

The following jQuery code will change the textbox width to 350px and then restore again to 200px when the focus goes out. This code makes use of the jQuery animate method, which provides simple animation while changing width:

$(document).ready(function() {
  $('#txtValue').focus(function() {
    $(this).animate({ width: '300px'}, 'fast');
  });
  $('#txtValue').blur(function() {
    $(this).animate({ width: '200px'}, 'fast');
  });
});

Using the animate() method, duration can be assessed. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The default duration is 400 milliseconds. The strings ‘fast’ and ‘slow’ can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

10. Disable all textboxes

The following jQuery code will disable all the textboxes present on the page by setting the “disabled” property to true:

$(document).ready(function() {
    $('input[type="text"]').prop("disabled", true);
});

If there are multiple forms on your page and you wish to disable textboxes of a particular form, then all you need to do is supply the form Id to jQuery selector. Like this:

$(document).ready(function() {
    $('#frm1 input[type="text"]').prop("disabled", true);
});

In this case, all the input textboxes for “frm1” will be disabled.

 

To sum up, these jQuery code snippets for input textboxes are handy when implementing validations, disabling and enabling, setting focus for providing a better user experience and, from a security point of view, to disable copying. These tiny snippets can save you valuable minutes, and allow you to complete tasks with ease!

How to Refresh One Section of a Page

There are plenty of times where you might want to refresh only part of your page’s content, leaving the static content to be, well, static, and refreshed at the user’s discretion. Reloading an entire page on a user can be jarring, confusing, and doesn’t make for a great user experience. However, if your page features timely news stories or breaking news, featured content that is updated often, or even promotional or dynamic content that you’d like to reload to give your users more opportunities to see everything you’ve got to offer, refreshing just these particular areas of a page is a good option. This way, you can make sure your targeted content is updated, without alienating any users.

If you’d like to reload just a section (or a few sections) of a page, you can do so relatively easily and simply with jQuery. Check out the lightweight snippet below to easily add this functionality to any of your projects:

setInterval(function() {
$("#reloadContent").load(location.href+" #reloadContent>*","");
}, 200000);

As you can see, in the example above, we’re choosing to refresh the #reloadContent element. If you’d like to refresh an element with a different class or ID (note: it’s probably wise to only refresh elements using their IDs, rather than classes, so you don’t accidentally end up refreshing several different elements at once),  you can simply replace the #reloadContent with the name of your chosen element. You can then use the second parameter of the function (in the example above, 200000) to set the amount of milliseconds that should pass in between the initial page load and when you want your content and elements to refresh. Remember — the time interval is in milliseconds, so be sure to keep that in mind when setting your refresh time, so it doesn’t end up refreshing too often.

Use this snippet as many times as you’d like in your code to refresh several different elements at different time intervals.