Intermediate

How to Use jQuery to Dynamically Open Links in New Tabs

Even if you’re a new or beginning developer, you probably know that you can easily make links open in new tabs by using the target attribute with your anchor tags. To make a link open in a new tab, all it takes is to make your HTML look like this:

<a href="/link/" target="_blank"></a>

The target=”_blank” attribute is all you need to make your links open in new tabs. But what if your anchor tags weren’t written this way, and you still want your links to open in new tabs? You can go back through your HTML and hand code it yourself, but if you’ve got a lot of anchor tags this could take you a really long time. Luckily, jQuery is here to save the day.

With jQuery,  you can use some really straightforward snippets to dynamically open all external links in new tabs without having to go through every line of your HTML with a fine-toothed comb. To see the snippet for yourself, check out the code below:

$('a[@rel$='external']').click(function(){
     this.target = "_blank";
});

That’s it. All it takes are two lines of  jQuery to make sure that all of your external links open in new tabs. The function is triggered by the .click() event method, so the function won’t run unless any of the external links are clicked on, so it’s a pretty lightweight solution. You can see that the snippet above uses the ‘a[@rel$='external']‘ selector. This can be used to select all of the external links, and apply the target=”_blank” attribute to it. But, if you find yourself wanting to select all of the anchor tags on your page, you can remove the rel code and simply use ‘a’ as the selector. You can also use a similar concept to select all links of one class or ID type by placing the class or ID name in the selector.

 

Using jQuery to Count Child Elements

If you ever find yourself needing to know how many child elements an HTML element has, you’re in luck, because there’s a jQuery function for that.

There are actually a few different ways you can go about doing this. The first is really simple and straightforward, and will count all the children elements of an element, regardless of what type of element it is or its class or id names. To do this, we just need to use the .children() method and chain it with the .length() method, and apply it to the element in question whose children total we’d like to know. So, for example, if we’d like to know how many children a div element with the id of #main has, we can use the following snippet:

$("#main").children().length;

Okay, that’s easy enough. But what if you’re trying to find something more specific, like the number of children of an element that are <p> tags, or <h1> tags, then the code is a little bit more complicated.

You might know that you can use jQuery selectors a lot like CSS selectors (and if you don’t know, try reading this handy guide to brush up on your jQuery skills). So in CSS, if you want to select the direct child of an element, you do so by using the > symbol after the parent but before the child element. For example, in CSS, if you want to select the p elements that are children of any div element with the #main ID, you’d use the following code:

div#main > p{
   //insert code here
}

In jQuery, it’s actually almost the same principle. To select the specific children elements of an element, your selector would look almost exactly the same as it would in CSS (except, of course, for the jQuery syntax). From there, you just need to apply the .length() method to your selector to count all of the children. So if you’re trying to count all of the p element children of the #main div, your jQuery code can look like this:

$("main > p").length;

There you go, that’s all it takes.

Drag and Drop HTML Table Rows Using jQuery

HTML tables are the preferred UI option for displaying data. Sorting, paging and searching/filtering are must-have functionalities for any HTML table with extensive data. These functions make HTML tables more user-friendly and efficient for the end user. In some cases one may require drag and drop functionalities for HTML table rows. Unfortunately, implementing drag and drop for table rows is not available out of the box with jQuery. To implement this, we need to use a jQuery plugin called TableDnD. In this post, we’ll learn how to implement drag and drop HTML rows using jQuery plugin TableDnD.

HTML Markup

To get started, create a standard HTML table on the page. For this demo, our table has 3 columns: Name, Age and Country, along with some random data.

<table id="tblData">
<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 table and its rows. The myDragClass CSS class styles the row that needs to be dragged and dropped. This style will be applied for the duration of the drag and then removed when the row is dropped.

table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
th {background-color: #dddddd;}
.even {background-color: #ecf6fc;}
.odd {background-color: #ddeedd; }
.myDragClass {
  background-color: yellow;
  font-size: 16pt;
}

jQuery Code

As mentioned in the beginning of the post, the TableDnd plugin will be used for implementing this feature. This plugin allows the user to reorder the rows within a table. The great thing about this plugin is that it doesn’t take into account cell count within a row or the row containing form elements. Using this plugin, you can also mark rows as non-draggable and/or non-droppable so that other rows can’t be dropped onto them. Now, let’s look at using this plugin.

The plugin is only dependent on the jQuery library, so download the jQuery library and TableDnd plugin library.  Then include the reference of jQuery and this plugins library. To implement the basic functionality, call tableDnd() function on the table element. Like this:

$(document).ready(function() {
  $("#tblData").find("tr:even").addClass("even");
  $("#tblData").find("tr:odd").addClass("odd");
  $("#tblData").tableDnD();
});

The above code will apply different row styles for odd and even rows, and will also implement drag and drop functionality for the rows. You can check out the demo at the following link.

The above code does the basic job of dragging and dropping the rows. To make it look more attractive, we can also highlight specific rows. Remember, we defined a CSS class named myDragClass. This plugin provides an option to set a CSS class to row during dragging. Use the onDragClass option to set the CSS class. Like this:

$("#tblData").tableDnD({
   onDragClass: "myDragClass"
});

This style will be applied for the duration of the drag and then removed when the row is dropped. You can check out the demo at the following link. Looks great, don’t you think?

However, there is a small UI problem that you may have noticed in both the demos. To make tables look more attractive, we used different background colors for even and odd rows, but when the row is dragged and dropped the color styling is negatively affected. The styles that were previously applied to the rows are moved with the data. Take a look at the image below to understand the problem.

To fix this formatting issue, we need to implement a onDrop event. This event is called when the row is dropped. We can pass a function that will be called when the row is dropped. The function takes 2 parameters: the table and the row that was dropped. So inside the function, we can re-arrange the styling order. Like,

$(document).ready(function() {
  $("#tblData").find("tr:even").addClass("even");
  $("#tblData").find("tr:odd").addClass("odd");
  $("#tblData").tableDnD({
    onDragClass: "myDragClass",
    onDrop: function(table, row) {
      $("#tblData").find("tr").removeClass("even odd");
      $("#tblData").find("tr:even").addClass("even");
      $("#tblData").find("tr:odd").addClass("odd");
    }
  });
});

The above code first removes the CSS classes from the table rows and then reassigns the color styles. One thing to note here is that for the onDrop event to get called you must have IDs assigned to all your table rows. So when generating the HTML table dynamically, make sure you assign the ID attribute to table rows. In case of a static HTML table (like in this case), either you can manually assign an ID to every table row (which can be painful) or you can take advantage of jQuery to assign it via code. Like this:

var iCnt = 1;
  $("#tblData tr").each(function() {
     var id = "tr" + parseInt(iCnt);
     $(this).attr("id", id);
     iCnt++;
  });

The above code loops through table rows and adds ID attribute to each row. So now, everything looks good. Check out the demo at the following link!

If you wish to restrict certain rows to be non-draggable, then you can add a “nodrag” class to that table row and the plugin will take care of the rest. Like this:

<tr class=”nodrag”>

Similarly, if you want to make rows non-droppable so other rows can’t be dropped onto them, add “nodrop” class to that table row and let the plugin do its magic. Like this:

<tr class=”nodrop”>

For the demo, row no. 3 is marked as nodrag and row no. 8 is marked as nodrop. You can also give a different style to them to let user know that these rows have special restrictions. For this demo, non-draggable rows are highlighted with a light blue background while the non-droppable rows are highlighted with a red background.

.nodrag {
  background-color: lightblue;
}
.nodrop {
  background-color: red;
}

You can check out the demo at the following link!

This plugin offers other events and styles to play around with, and also works with hierarchical tables. Please visit the official website to learn more about this plugin.

Conclusion

To sum it up, we’ve just learned how to drag and drop HTML table rows using the TableDnD jQuery plugin. Along with drag and drop implementation, this jQuery plugin offers options to style the way rows are dragged and dropped. Using this plugin, you can also mark individual rows as non-draggable and non-droppable.

How to Verify User Age with jQuery Code

If you’ve ever visited a site that’s selling a product that has certain age restrictions (for example, a site selling or representing an alcohol brand might prompt you to verify that you’re over 21 before you’re allowed access to the site), you might have come into contact with an age verification form. It turns out, that this type of form is a fairly easy one to validate, because all you need to do is prove whether it’s true or false that someone is older than the desired age cut off for access to your site.

The jQuery snippet you can use to validate this type of form is as follows:

$("#age-verify").submit(function(){
 var day = $("#day").val();
 var month = $("#month").val();
 var year = $("#year").val();
 var age = 21;
 var mydate = new Date();
 mydate.setFullYear(year, month-1, day);
var currdate = new Date();
 currdate.setFullYear(currdate.getFullYear() - age);
 if ((currdate - mydate) < 0){
 alert("Sorry, only persons over the age of " + age + " may enter this site");
 return false;
 }
 return true;
});

The code above assumes that the only relevant information you’re collecting from your age verification form (here it has the id #age-verify – - be sure to change it to match the id of your own form) is the day, month, and year of your users birth. The age variable sets the minimum age of users allowed access to your site. For the purposes of this example, we’ve made the minimum age 21.

Using some simple arithmetic and an if else statement, the snippet above determines whether a person is over 21 by checking if the current date subtracted by the age variable is greater than zero. If it is, then they are allowed access to the site, and if it isn’t, they’re presented with a “Sorry, you’re not old enough” message. Of course, there’s nothing about this form that wouldn’t stop an under age user from simply lying about the year of their birth, but the same is true with implementations of this type of form across the board, including with big, international brands.

 

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.