Intermediate

Using jQuery to Get Page Load Time

If you ever find yourself needing to know how long it takes for one of your pages to load, we’ve got the snippet for you. There are many reasons you might want to understand how long a page load takes — doing this might especially appeal to developers who have got their pages loaded with ads, and want to test how much they’re slowing down the site. You can try loading the page yourself, but sometimes to the naked eye it can appear as if the page has loaded, when really scripts are still trying to be fetched and ads have yet to be loaded. Under these circumstances, it’s easier to just test it out using code.

See below for the code snippet:

var start = new Date(); 
jQuery.ready(); 
var end = new Date(); 
var difference = (endTime - startTime) / 1000; 
alert("document.ready time: " + difference + " seconds");

In the code above, we first record the time (using the Date method) when the page is requested and begins to load. This line must go at the top of the code. Then, one the page is loaded (that’s what the jQuery.ready() line is for) we fetch the time again. We find the difference between the two and divide the answer by 1000, because the time is measured in milliseconds and we want our answer to be in seconds for the purpose of this tutorial (but milliseconds is totally fine too if you’d rather your answer be in that format — just remove the division part of the equation!) and set the time to the variable “difference”. From there, we use an alert to let us know the time it took for the page to load by referencing the difference variable. If you don’t want the time difference to appear as an alert, you can log it to the Console or add it to your HTML — whichever works best for you and your project.

How to Increase Conversion Rates with Ouibounce

One surefire way to increase conversion rates on your landing pages is to include some sort of pop-up, be it one that appears as soon as your user visits the page, or an exit pop-up that appears when the user is going to leave the page (usually this type of pop-up is activated when the cursor hits a certain point of the viewport). While no user will tell you that they love pop-ups, there’s no denying that they work to get more people to engage with your site and your content.

An easy way to add pop-ups to your sites is by using the open source, lightweight, and totally free Ouibounce plugin. The plugin gives you total control over your modals, and lets you customize things like a timers, cookie names, cookie expiration time (so how long you want a cookie to last before it expires and a user is exposed to the pop-up again), and more. You can define sensitively, which applies to the exit pop-up option, because sensitivity allows you to choose how far the cursor can move up the the viewport before it triggers the modal to appear. If you don’t want to go the exit pop-up route, but you always don’t want your modal to appear immediately upon page load, there’s also a delay option that allows you to define how much time you would like to pass in between page load and the pop-up appearing.

Screen Shot 2017-03-25 at 10.15.54 AM

 

In terms of design, there are templates and suggestions provided by the plugin’s developer, but the style and content are totally customizable and up to you. Ouibounce gives you complete control of how you want your pop up to look and function within your project. The plugin is easy to install and almost even easier to use, and it will definitely give you great results if you’re looking for a lightweight, simple, and customizable pop-up plugin for any of your sites or pages.

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 the @media rule 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!

Conclusion

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.