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:
jQuery(document).ready(function($) {
    // 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 & lt; $('.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
    setInterval(function() {
        // 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
        var styleElm = 'style="left: ' + randomValue(bArray) + 'px;';
        styleElm = styleElm + 'width: ' + size + 'px; height:' + size + 'px;"';
        $('.bubbles').append('<div class="individual-bubble"' + styleElm + '></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.

Add Pagination to HTML Table Using jQuery

Paging helps present data in a clean and elegant way and it can also improve the page load time. It helps by dividing extensive data into separate pages so that it can easily fit in the UI. In this post, we’ll learn how to add pagination to your HTML table element with the help of jQuery.


The following CSS classes are used to style page numbers. The focus CSS class will style the page number on focus. The pageNumber class will style the position of the page numbers.

.focus {
  background-color: #ff00ff;
  color: #fff;
  cursor: pointer;
  font-weight: bold;
.pageNumber {
  padding: 2px;

jQuery Code

To implement this function, you’ll need to get the count of total records and then divide the total count value with the per page records to get the total number of pages. Finally, add the page numbers to a div and attach a click event to the page numbers to display the next set of records.

The following is the outline of this jQuery solution:

  • First, get the total number of rows with only TD elements and store in a variable totalRows. Do not include the table header row in this section.
  • Declare a variable recordPerPage which defines how many records are to be displayed on a single page. In our example it is set to 5.
  • Count the total number of pages by dividing totalRows and recordPerPage and store it in a variable totalPages.
  • Create a div element which will hold the page numbers. To get page numbers, run a loop from 1 to totalPages. Within the loop, create a SPAN tag to hold the page numbers and append it to the main div element.  Once the loop is finished, add the div element to the HTML table so that page numbers will be displayed just after the HTML table.
  • Add a hover event to pageNumber, to toggle the .focus CSS class.
  • By default, we wish to show records of the first page only. So, hide all the rows of the table and run a loop to show only those rows which satisfy the condition recordPerPage – 1.
  • Finally, attach a click event to the pageNumber span tag to display the result of clicked page number. This is done by showing only those table rows which satisfy the condition of clicked page number * records per page. For the loop, the starting number would be (clicked page number – 1) * records per page and ending number would be (clicked page number + 1) * records per page. As an example, if page number 3 is clicked, then rows from 11-15 should be visible on the screen.

Here is the complete jQuery code:

$(document).ready(function() { 
    var totalRows = $('#tblData').find('tbody tr:has(td)').length; 
    var recordPerPage = 5; 
    var totalPages = Math.ceil(totalRows / recordPerPage); 
    var $pages = $('<div id="pages"></div>'); 
    for (i = 0; i & lt; totalPages; i++) {  
        $('<span>&nbsp;' + (i + 1) + '</span>').appendTo($pages); 
    $('.pageNumber').hover(  function() {
    },   function() {
    } ); 
    $('table').find('tbody tr:has(td)').hide(); 
    var tr = $('table tbody tr:has(td)'); 
    for (var i = 0; i & lt; = recordPerPage - 1; i++) {   
    $('span').click(function(event) {  
        $('#tblData').find('tbody tr:has(td)').hide();  
        var nBegin = ($(this).text() - 1) * recordPerPage;  
        var nEnd = $(this).text() * recordPerPage - 1;  
        for (var i = nBegin; i & lt; = nEnd; i++)   {   

Check out jsFiddle for more pagination examples!


To sum it up, we saw how to add paging to an HTML table element based on configurable options for setting ‘number of records per page’. This simple solution adds the paging with ease, based on your design and requirement. Remember, this information can be easily updated at any time!

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 ( {
   /* 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';  
        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   

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.