Advanced

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

jQuery.parseJSON vs JSON.parse

JSON.parse() and jQuery.parseJSON(), both are used to parse a JSON string and returns resulting JavaScript value or object described by the string. jQuery.parseJSON() is available only when jQuery library is used where JSON.parse() is JavaScript’s standard built-in JSON object method. So the question is if jQuery library is used, then which one should be used or both gives same performance and result?

Well, the answer is that both are equal. As you know, jQuery’s library is written on top of JavaScript. So  jQuery.parseJSON() makes use of JSON.parse() internally. Here is the code of jQuery.parseJSON() method from jQuery 1.9.1 library. As you can see, it first checks if JSON.parse is supported or not. If supported, then it makes use of JSON.parse only. Otherwise, it tries to evaluate string data with new Function.

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}

if ( data === null ) {
return data;
}

if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {

return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
}

This was done as JSON.parse is natively available on some browsers, and jQuery is browser independent. So if JSON.parse is not available, then it falls back to jQuery implementation.

JSON.parse was not supported in old browsers like IE 7 and Safari 3, but over the period of time, browsers have also evolved. And now most of the browsers support JSON.parse. Therefore, the implementation of jQuery.parseJSON() is also changed after jQuery 2.0 release. Here is the code of new implementation from jQuery 2.2.4 library:

// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function( data ) {
return JSON.parse( data + "" );
};

And the big news is that with jQuery 3.0, jQuery.parseJSON is deprecated. So now to parse JSON objects, use the native JSON.parse method instead.

Using jQuery’s .pushStack() for reusable DOM traversing methods

The .pushStack() method has been in jQuery since before version 1.0, but it hasn’t received a whole lot of attention outside of core developers and plugin authors. While its usefulness may not be immediately apparent, it can come in really handy in some situations, so I’d like to take a quick look at what it does, how it works, and how we can use it.

pushStack Basics

At its most basic level, the .pushStack() method accepts an array of DOM elements and “pushes” it onto a “stack” so that later calls to methods like .end() and .andSelf() behave correctly. (Side note: As of jQuery 1.4.2, you can pass in a jQuery object instead of an array, but that isn’t documented and jQuery itself always uses an array, so that’s what we’ll stick to here.)

Internally, jQuery uses .pushStack() to keep track of the previous jQuery collections as you chain traversing methods such as .parents() and .filter(). This lets us traverse through the DOM, do some stuff, “back up” to previous collections within the same chain using .end(), and then do something else. Here is a somewhat contrived example:

Read the rest of this entry »

Merging jQuery Deferreds and .animate()

Editor’s Note: This article originally appeared on danheberden.com.

jQuery’s .animate() method, and the shorthand methods that use it, are fantastic tools to create animations. Creating animations that link together to achieve a particular effect, and do something specific at the end of the animation, can be a painful, messy task. Luckily, we have .queue() for mashing animations together.

But what happens when you want to bridge the gap between ajax requests and animating? When you want to queue a bunch of animations, get data from the server, and handle it all at once, without a crap-load of nested callbacks? That’s when jQuery.Deferred() puts on its cape, tightens its utility belt, and saves the day.

Read the rest of this entry »

Making a jQuery Plugin Truly Customizable

Most if not all of the jQuery plugins out there have some level of customization. But very few of the plugin authors have mastered the very particular art involved.

Achieving the “optimum level” of customization is a bit of a balancing act… go too far either way and you’ve got an unusable plugin!

Read the rest of this entry »