Intermediate

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.

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

6 Unique jQuery Plugins for Background Effects

Ever feel like the backgrounds of your web pages always end up being just a little bit boring? As a web developer, it can be hard to determine how to add some life into your backgrounds, and it can also be time consuming to write your own code to do so. If you’re looking for a quick fix to spice up your projects, check out this curated list of 6 jQuery plugins that will add fun, free, and unique touches to the background of your pages.

1. Particleground

Screen Shot 2017-02-16 at 3.35.47 PM

 

Particleground is a really fun plugin that adds subdued yet animated moving particle systems to the background of any of your web pages. The particles have a light shade so as not to distract from your pages’ content. The plugin comes with the option to enable the particles to move in correspondence with your cursor.

2. BgSwitcher

Screen Shot 2017-02-16 at 3.43.19 PM

 

This lightweight, easy to use plugin generates a slideshow of images to function as the background of a page. The slideshow flips through the images using smooth animated transitions. To see it in action, check out the demo.

3. Vide

Screen Shot 2017-02-16 at 3.45.27 PM

If you’d like to use a video as the background for your web pages, this plugin is an awesome option for doing so. It couldn’t be easier to use and it’s supported on all desktop browsers (there’s no support for iOS, however, and a cover photo will be displayed when your page is viewed on an iOS device). You can customize volume, playback rate, if you want the video to be on a loop, and much more.

4. Adaptive Backgrounds

Screen Shot 2017-02-16 at 3.48.15 PM

Adaptive Backgrounds is a fun little plugin that chooses the background colors of your web pages or block-level elements based on the dominant colors of the images inside of them. Definitely a cool plugin to add to your projects or to just play around with!

5. Vegas Background Slideshow

Screen Shot 2017-02-16 at 3.55.53 PM

Another background slideshow plugin, this one includes a sort of Ken Burns effect applied to the images, and very nice and smooth fading transitions. Great for showcasing hi-res images.

6. Geometry Angle

Screen Shot 2017-02-16 at 4.00.06 PM

Geometry Angle is a plugin that adds a 3D shading effect to your backgrounds. The effect, while being 3D, is also animated, so it looks as though the shapes and shades are always slowly moving about your page.

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!