All Levels

How to Use jQuery’s .select() Method

jQuery’s .select() method is not a super popular or commonly used jQuery event method, but it can be very useful. A select event occurs when text within a text area or text input field is selected (highlighted) by a user using the cursor. Basically, the only time you would use it is if you want a particular effect to happen or code to change as a direct result of a user selecting text written, either text by themselves or text that exists as the result of it being assigned the value for the elements in question, within a text area or text input field.

What follows is a look at the basic syntax, which is similar to that of many other jQuery event methods:


You can choose to attach a function to the select event, or you can choose to leave the parameter parentheses blank. To see what it might look like with a function attached, check out the code snippet example below.

To better understand how this jQuery event method works, we’re going to show you how you would use it in a realistic context. In the example below, the code demonstrates how the .select() method can be used to trigger an alert message on your page:

   alert("You highlighted some text -- good job!");

So in the example above, when any text from within a text area is selected or highlighted (whether it be text entered by the user or text that was already there), an alert will pop up on the page that says “You highlighted some text — good job!” It’s important to remember that because of the way this code is written, this alert will appear each and every time that text is selected or highlighted within any text area element on the page. If you’d like for that to be different, then be sure to customize the code to suit the needs of your own project.

jQuery Bubbling Text Effect

This tutorial will demonstrate how to use CSS, jQuery, and JavaScript to create a really simple and cool text effect where it appears as though there are bubbles forming behind the text. After forming, the bubble float above the text before they disappear. This tutorial was inspired by a code snippet that originally appeared on CodePen.

Screen Shot 2017-04-15 at 4.08.17 PM


To start creating this effect, first you’ll need some HTML. We’ve included our text in an h1 tag which is wrapped in a div. Check out our code below:

<div class="bubbles">
<h1>Bubble Text!</h1>


Even though jQuery is the most important part of getting the animated bubbles to work for this effect, this snippet would be incomplete without some styling. In the CSS code snippet below, we define things like the background-color, the font-family, and the round shape of the bubbles. Make sure you don’t skip this step, but feel free to customize the code to your liking.

body {
background-color: #3498db;
.bubbles {
display: inline-block;
font-family: arial;
position: relative;
.bubbles h1 {
position: relative;
margin: 1em 0 0;
font-family: 'Lemon/Milk', cursive;
color: #fff;
z-index: 2;
.individual-bubble {
position: absolute;
border-radius: 100%;
bottom: 10px;
background-color: #fff;
z-index: 1;

The jQuery

All that’s left to create this cool effect is the addition of some jQuery code. The jQuery is very straightforward – we need to create two arrays, one blank one that will determine the positioning of the bubbles, and another that is populated and will help determine the size of each bubble. Then, we’ll need to write a function that selects random array elements, and another that generates a new selection every 350 milliseconds. Then we have some code that will append the bubbles to the HTML so that they appear in the viewport, and finally we need a final callback function to remove the bubbles from the viewport, so that a huge collection of bubbles doesn’t accumulate at the top of the page. The original author of the aforementioned CodePen snippet annotated the jQuery code very well, so we’ve left his meticulous notes in the code to help you follow the steps as you read them.

// Created for an Articles on:

 // Define a blank array for the effect positions. This will be populated based on width of the title.
 var bArray = [];
 // Define a size array, this will be used to vary bubble sizes
 var sArray = [4,6,8,10];

 // Push the header width values to bArray
 for (var i = 0; i < $('.bubbles').width(); i++) {

 // Function to select random array element
 // Used within the setInterval a few times
 function randomValue(arr) {
 return arr[Math.floor(Math.random() * arr.length)];

 // setInterval function used to create new bubble every 350 milliseconds

 // Get a random size, defined as variable so it can be used for both width and height
 var size = randomValue(sArray);
 // New bubble appeneded to div with it's size and left position being set inline
 // Left value is set through getting a random value from bArray
 $('.bubbles').append('<div class="individual-bubble" style="left: ' + randomValue(bArray) + 'px; width: ' + size + 'px; height:' + size + 'px;"></div>');

 // Animate each bubble to the top (bottom 100%) and reduce opacity as it moves
 // Callback function used to remove finsihed animations from the page
 'bottom': '100%',
 'opacity' : '-=0.7'
 }, 3000, function(){

 }, 350);


Now you can experiment with this very cool effect — customize the speed, size of the bubbles, colors, etc — and add it to any of your next projects!


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(); 
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 [email protected] 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 ( {
   /* Audio supported */
/* 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 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.

var checkMod = function(){
   if('(min-width: 480px)')){
     return “phone”;
   else if('(min-width: 768px)')){
     return “tablet”;
     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
     // 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,'max-width: 640px') //Valid'max-width: 640') //Invalid'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('only all')) {
 // returns true if MQ are supported, false if not

Or you can use the following test:

Modernizr.addTest("cssmq", function(){
   return !!"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.

    <td>Maria Anders</td>
    <td>Francisco Chang</td>
    <td>Roland Mendel</td>
    <td>Helen Bennett</td>
    <td>Yoshi Tannamuri</td>
    <td>Giovanni Rovelli</td>
    <td>Narendra Sharma</td>
    <td>Alex Smith</td>


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) {
    function() { $(this).addClass('focus'); },
    function() { $(this).removeClass('focus'); }
    $(this).click(function() {
      if ($(this).is('.asc')) {
        $(this).addClass('desc selected');
        sortOrder = -1;
      else {
        $(this).addClass('asc selected');
        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;
           return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;
      $.each(arrData, function(index, 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!


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).