How to Use jQuery’s Mouse Methods

jQuery has 4 event methods that have to do with cursor movement. The methods are .mouseenter(), .mouseleave(), .mouseup() and .mousedown(). All of these methods can be used to trigger events and execute code based on when and where the user’s cursor moves. In terms of syntax, they’re fairly simple and straightforward to use, but they can also be really versatile and used to achieve some pretty cool functionalities and effects.

In this tutorial, we’re going to go over how to use each of the mouse event methods. Take a look at the code snippets below to for examples of how to use them in the context of your code.

.mouseenter() and .mouseleave()

The .mouseenter() and .mouseleave() methods are two that are often used together. You can probably guess what they do, but here’s a brief explanation. The .mouseenter() method is triggered when the cursor enters the selected element (here, the word “enters” means that the cursor moves over the element), and the .mouseleave() method is triggered when the cursor leaves, or stops moving over, the selected element.

There are many different effects you can achieve with these two methods. To see an example of how you might use them, check out the code below:

$("h1").mouseenter(function(){
     $(this).css("color", "red");
})
$("h1").mouseleave(function(){
     $(this).css("color", "blue");
})

In the code snippet above, the color of the h1 element that the cursor moves over turns red when the cursor is on top of it. When the cursor moves off of it, the color of the h1 element changes to blue.

.mouseup() and .mousedown()

The .mousedown() event is triggered when the mouse button is pressed down over a selected element (essentially, this is very close to the .click() method), and the .mouseup() event occurs when the mouse button is released over a particular element. Basically, it’s a click and release type of deal. Like .mouseenter() and .mouseleave(), these two event methods are often used in conjunction with one another. To see an example of how you would use it, take a look at the code below:

$("p").mousedown(function(){
     $(this).css("color", "orange");
})
$("p").mouseup(function(){
     $(this).css("color", "green");
})

In the code snippet above, the text color of the p element changes to orange when it’s clicked, and green when the click is released.

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.

 

How to Use jQuery’s .queue() Method

jQuery’s .queue() method is one that is actually an effect method. The .queue() method can be used to show the length of the queue for a particular selected element. The queue is the list of functions in line to be executed on a single selected element. So if you’ve got an element with five different functions attached to it, then the queue length would be five. The .queue() method used in conjunction with the .length() method is what you can use to calculate the queue length in your jQuery code.

The syntax for using the .queue() method is as follows:

$(selector).queue(queueName);

A good way to understand how exactly you can use the .queue() method is to see it in a real world context, so check out the example below to see how you would use the method to find the queue length on a p element when a button is clicked:

$("button").click(function(){
     $("span").text(p.queue().length)
})

So to understand what’s going on in the snippet above, it helps to see some HTML:

<button>How many functions are attached to the paragraph below?</button>
<span></span>
<p>I have three functions in my queue.</p>

For the purposes of this tutorial, let’s pretend that isn’t way too much text to be in a button. In the jQuery code snippet above, when the button is clicked, text is dynamically added to the span tag through the .text() method that states the queue length of the p element. It’s actually pretty straightforward. In this case, let’s say the p tag has three functions in its queue, so what was once an empty span tag will say “3″ once the button is clicked.

Sometimes (but rarely) elements have more than one queue attached to them. This is the only case in which you’d need to use the queueName parameter that the queue method takes. In this case, you’d write the name of the queue you’d like to find out the length of as the parameter, but again, this occurs very rarely.

 

12 Awesome jQuery Virtual Keyboard Plugins

A virtual keyboard is a component that allows a user to enter characters without a physical keyboard. It’s an alternative input mechanism for those who cannot use a physical keyboard, or for multi-lingual users who switch frequently between different character sets or alphabets. Virtual keyboards are commonly used as an on-screen input method on smart devices or small devices with no ability/space to attach a physical keyboard.

In this post, you’ll find a compiled list of 12 awesome jQuery virtual keyboard plugins, which allow you to attach an on-screen virtual keyboard. These jQuery plugins support various keyboard layouts, different languages, various theme options for look and feel and option for having a QWERTY keyboard, numeric keyboard or mixed keyboard.  If you are not happy with the default keyboard layout, then you can create your own layout with ease. Enjoy!

1. Keyboard

Keyboard

Keyboard is an on-screen keyboard jQuery plugin embedded within the browser window which will pop up when a specified entry field is focused. The end user can type and then preview the input before accepting or cancelling. It can be set to always remain open, and can also be programmed not to show a preview. The plugin can be programmed to display a QWERTY keyboard, numeric keyboard, alphabetic keyboard, hex value keyboard or iPad style keyboard. For sensitive information, there is also an option to mask the input. This plugin is dependent on the jQuery UI library.

2. Talking Keyboard

Talking Keyboard

Talking keyboard is a jQuery based plugin that enables an interactive and speaking English QWERTY keyboard. It is based upon SkeletonCSS, jQuery, and ResponsiveVoice. ResponsiveVoice is a HTML5-based Text-To-Speech library designed to add voice features to websites and apps across all smartphone, tablet and desktop devices. It supports 51 languages in 168 voices, with no dependencies. The beauty of this plugin is that it speaks when the user types any character.

3. jKeyboard

jKeyboard

jKeyboard is a jQuery plugin for creating an on screen visual keyboard that supports custom layouts for multiple languages. It supports English, Azeri Turkish (a Turkic language) and Russian language. It can be programmed for a QWERTY keyboard or a numeric keyboard.

4. Keypad

Keypad

Keypad is a jQuery plugin that attaches a popup keyboard to a text field for mouse-driven entries or adds an inline keypad in a division or span. The keypad functionality can easily be added to a text field with appropriate default settings. Use it with a password field for more secure text entry. You can also remove the keypad widget if it is no longer required. This plugin supports many languages which helps to implement localization. This plugin also allows users to randomize the key’s position for security purposes.

5. Keyboard Pagination

Keyboard Pagination

Keyboard pagination is a lightweight jQuery plugin which allows you to attach keyboard shortcuts for pagination. Once attached, using the keyboards left and right arrows, you can switch between the previous and the next page. This really helps to make the website more interactive.  It attaches a custom callback function code, detecting which one of the two keyboard arrow keys were selected: left or right. It then selects a corresponding pagination link and simply simulates (triggers) a click event for it. It supports numbered (1,2, 3…) links, previous or next page links and first and last page links.

6. MLKeyboard

MLKeyboard

ML Keyboard is a multi-language jQuery virtual keyboard with features for changing input layouts on the flight. It opens up the virtual keyboard at the bottom of the page, when there is a focus on the attached input field. It currently supports English, Spanish, Italian, Portuguese and Russian languages. It also comes with various configurable options to control the keyboard display, like displaying the keyboard permanently, or controlling the opening and closing speed.

7. jQKeyboard

jQKeyboard

jQKeyboard is a jQuery plugin that allows you to add a responsive virtual keyboard to the input text field. It creates an alphanumeric keyboard and allows you to customize the default layout of the keyboard to your liking.

8. jQuery Keyboard

jQuery Keyboard

jQuery Keyboard is a jQuery plugin for drawing a virtual keyboard. It is dependent on jQuery and Bootstrap. It comes with 3 themes and 5 languages. It has several themes to customize the keyboard.  You can choose the language of the keyboard to draw, if it is defined that the keyboard type will be: ‘Full Keyboard’ or ‘KeyPad’. It has several options of personalization and customization to choose from.

9. jQVirtual Keyboard

jQVirtualKeyboard

jQVirtual Keyboard is a jQuery and jQuery UI based virtual keyboard plugin that creates a draggable keyboard on the screen. Currently it supports English and Bulgarian, but it also provides an option to create your own layout for the keyboard via a custom layout. You can also choose a dark or light overall theme depending on your page design.

10. SoftKey

SoftKey

SoftKey is a jQuery based virtual keyboard plugin that creates an on-screen keyboard. This plugin allows you to define the layout of the keyboard and customize to your liking. You can define the layout as per your choice and set the order for number and alphabet keys.

11. jQBTK

jQBTK

jQBTK (jQuery Bootstrap Touch Keyboard) is a jQuery plugin for creating customizable on-screen virtual keyboards & numpads on mobile touch devices. It only works with touch devices. The plugin listens for touch events and uses the Bootstrap popover component, dynamically adding buttons to form a keyboard and inserting the characters into the HTML input when pressed.

12. NumPad

Numpad

NumPad is a flexible touch-optimized jQuery plugin for creating a numeric keypad for web applications based on jQuery, but it is mainly intended to be used in mobile web applications to quickly input numbers. The numeric keypad can be used to fill inputs, password fields, general div-elements or entire table columns. It works perfectly with most frameworks, including jQuery mobile and Bootstrap.

Conclusion

To conclude, these jQuery virtual keyboard plugins allow you to add an on-screen virtual keyboard to any input field. These plugins support different keyboard layouts, offer many languages and come with a variety of different theme options. Based on your needs, you can either open a QWERTY keyboard or a numpad keyboard. Some of the plugins also allow the user to change the layout/position of the keys as per their need.