All Levels

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.

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");
}