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

The HTML

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>
</div>

The CSS

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:
// https://www.html5andbeyond.com/bubbling-text-effect-no-canvas-required/
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 < $('.bubbles').width(); i++) {
 bArray.push(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
 $('.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
 $('.individual-bubble').animate({
 'bottom': '100%',
 'opacity' : '-=0.7'
 }, 3000, function(){
 $(this).remove()
 }
 );

 }, 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(); 
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.

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.

CSS

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 < totalPages; i++) {
    $('<span>&nbsp;' + (i + 1) + '</span>').appendTo($pages);
  }
     $pages.appendTo('#tblData');
  $('.pageNumber').hover(
    function() { $(this).addClass('focus'); },
    function() { $(this).removeClass('focus'); }
  );
  $('table').find('tbody tr:has(td)').hide();
  var tr = $('table tbody tr:has(td)');
  for (var i = 0; i <= recordPerPage - 1; i++) {
      $(tr[i]).show();
  }
  $('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 <= nEnd; i++)
    {
      $(tr[i]).show();
    }
  });
});

Check out jsFiddle for more pagination examples!

Conclusion

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