Using jQuery to Delete All Inline HTML Styling

Inline HTML styling (when the style attributes for a particular element are written within the HTML tag) is not something that’s considered a best practice when it comes to HTML and CSS, and it’s becoming less and less common. You don’t often come across inline styling unless a site’s code hasn’t been touched since the 90s or early 2000s, but it’s certainly not unheard of. If you find yourself trying to do a redesign of an older site that contains inline styling within the HTML, you’ll almost absolutely find that overriding the inline styling can be a huge pain.

Rather than go through every HTML file to remove inline styling, all of your inline styling woes can be eradicated using a very simple jQuery code snippet, which will completely get rid of all of the style attributes that can be found within your HTML tags. To see how it works, take a look at the code snippet below:

$("*[style]").attr("style""");

The code snippet above uses jQuery to select every single style attribute (using the * selector in combination with the [style] attribute) and, using the .attr method, removes all of the values from the inline style elements by replacing the text with nothing (thanks to those empty quotation marks).

This is a super simple solution to getting rid of inline styling that can save you tons and tons of time and aggravation. If you’re working on a smaller site with less instances of style attributes within the HTML tags, then it might be wiser to just go through and remove them manually, but if you’ve got a big size with inline styling on every single page, then this is a great, super straightforward, and rather lightweight solution that will easily and quickly remove every single instance of inline style attributes so that the site in question can be updated to look its very best.

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.

 

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") >= 0) {
 // insert conditional IE code here
 }
 //Check if browser is Chrome
 else if (navigator.userAgent.search("Chrome") >= 0) {
 // insert conditional Chrome code here
 }
 //Check if browser is Firefox 
 else if (navigator.userAgent.search("Firefox") >= 0) {
 // insert conditional Firefox Code here
 }
 //Check if browser is Safari
 else if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
 // insert conditional Safari code here
 }
 //Check if browser is Opera
 else if (navigator.userAgent.search("Opera") >= 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.