How to Use JavaScript to Detect Browser

Wouldn’t it be nice if all of our code looked the same and worked the same no matter what browser our users are viewing our projects or web pages on? That’s the dream, right? Unfortunately, cross browser compatibility isn’t something that a site can achieve without adding some extra code.

There a few ways that you can use code to compensate for different browsers. You can us CSS selector browser hacks, which is a good option, especially if any changes you need to accommodate for are mostly cosmetic and can be fixed with CSS. For more dynamic browser selections, JavaScript is actually a valid way to go.

Below, you’ll find a code snippet that you can use to check for Internet Explorer, Chrome, Firefox, Safari, and Opera. The function checks for these browsers, and will execute any code you insert within the if/else if statements for each browser if the code is run on any of the browsers in question. Use the code to dynamically add classes to your HTML based on the browser, to send alerts to the user based on the browser, to trigger events based on the browser.

The code snippet is lightweight and straightforward, so even the most beginner coders should be able to add it to their projects. Play around with it and see if you can’t achieve that elusive cross-browser compatibility!

function BrowserDetection() {
    //Check if browser is IE
    if (navigator.userAgent.search("MSIE") & gt; = 0) {
        // insert conditional IE code here
    }
    //Check if browser is Chrome
    else if (navigator.userAgent.search("Chrome") & gt; = 0) {
        // insert conditional Chrome code here
    }
    //Check if browser is Firefox 
    else if (navigator.userAgent.search("Firefox") & gt; = 0) {
        // insert conditional Firefox Code here
    }
    //Check if browser is Safari
    else if (navigator.userAgent.search("Safari") & gt; = 0 & amp; & amp; navigator.userAgent.search("Chrome") & lt; 0) {
        // insert conditional Safari code here
    }
    //Check if browser is Opera
    else if (navigator.userAgent.search("Opera") & gt; = 0) {
        // insert conditional Opera code here
    }
}

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) & lt; 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.