All Levels

20 Impressive jQuery Plugins to Replace the HTML Select Box

The traditional HTML select element is not very powerful out of the box, it lacks in more substantive features. Today, the web demands controls with multiple features for a user-friendly experience and the traditional HTML select box just can’t compete. Features like multi-select, grouping, hierarchical lists, and custom HTML markup make light work of projects and tasks, and the HTML Box lacks these features.
Writing your own implementation for these features will require a lot of effort, and testing browser compatibility can be a nightmare. Luckily, jQuery offers lots of plugins to save you from that hassle. This post has a compiled list of 20 impressive jQuery plugins to replace the traditional HTML select box with a sleek, stylish and feature-rich select box. These jQuery plugins offer various features like changing default styles, adding search functionality, grouping the items, creating hierarchies, keyboard navigation, multiple item selection and many other features.

1. Pretty Dropdowns

Pretty Dropdowns

https://github.com/thdoan/pretty-dropdowns

Pretty Dropdowns is a simple, lightweight jQuery plugin that converts <select> drop-down menus into “pretty” menus that you can skin using CSS. It features:

  • Two arrow styles and sizes to choose from (or add your own style)
  • Easily add icons, thumbnails, and other custom HTML to the menu items
  • Support for multiple-select lists
  • Support for option groups
  • Tooltips (title) carried over at select, option, and optgroup levels
  • Full keyboard navigation (you can even go directly to a menu item by typing its text!)
  • Auto-linked to label (menu will get focus when you click on the label)
  • Accessibility (it plays nicely with screen readers)
  • Sensibility (when you open the menu it does its best to keep the menu items within the viewport)
  • Complete control over the look and feel of the drop-down menu by modifying prettydropdowns.css

2. SelectPick

SelectPick

http://project.zyy1217.com/selectpick/

SelectPick is a fast, simple, customizable, and lightweight jQuery plugin to customize the HTML drop-down box with custom styling. The beauty of this plugin is that it can be applied to any type of HTML, not necessarily just HTML select box. Features include:

  • Possibility to bind to multiple types of HTML elements
  • Customizable data sources
  • Support for Ajax asynchronous access to data
  • Providing options and labelling disable functions
  • Dynamically setting selected items
  • User style customization

3. InputPicker

InputPicker

https://github.com/ukalpa/inputpicker

InputPicker is a jQuery input plugin that converts an input text field into a filterable, multi-column dropdown select box. When initiated this plugin appends a div element below the input box and styles it with the help of default CSS classes. It supports both local data (data array) and removing data sources (JSON) via AJAX requests. The plugin also gives flexibility to developers to change the width and height.

4. Select2

Select2

https://select2.github.io/

Select2 is a jQuery replacement for traditional select boxes. Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options. It features:

  • Over 40 languages and RTL support.
  • Fully skinnable CSS built with Sass and an optional theme for the Bootstrap 3.
  • Full extensibility to work exactly how you want it to
  • Dynamic item creation
  • Support for both modern and legacy browsers

5. Sweet Dropdown

Sweet Dropdown

http://sweet-dropdown.adepto.as/

Sweet Dropdown is a simple jQuery plugin which creates flexible and animated dropdowns in any direction with any kind of content. It also supports adding icons to select items as well as the option to apply dark or light themes for styling. This plugin works in all major browsers.

6. Awesome Select

Awesome Select

https://github.com/prevwong/awesome-select

Awesome Select is a beautiful and customizable jQuery plugin for transforming the boring select tag into something beautiful and minimal, with animations inspired from Material Design. You are free to change the way the dropdown looks based on your own taste. This plugin also supports immersive mode, which allows you to render the dropdown in a modal window covering the complete screen. The animations are based on CSS3 transform and transition properties.

7. jQuery Dropdown

jQuery Dropdown

https://github.com/daneWilliams/jquery.dropdown

jQuery Dropdown is a flexible and cross-device jQuery plugin for replacing HTML selects and multi-level menus with animated select dropdowns. This plugin allows you to create simple, multiple select, nested, grouped and custom HTML content dropdowns. The plugin allows you to override default settings for animation, keyboard navigation, multiple item selection and other default settings.

8. Combo Select

Combo Select

https://github.com/PebbleRoad/combo-select

Combo Select is a jQuery plugin that converts a select box into a searchable and keyboard-friendly interface. The plugin creates a div element and styles it using the default CSS. It also attaches the keydown event to capture key strokes for filtering the select. The other advantage of this plugin is that it falls back to native select on mobile and iPad devices. It features:

  • Search and filter, select items
  • Mobile- and tablet-friendliness (fall-backs to native select)
  • Keyboard accessibility
  • Ease of style
  • Data attribute support
  • Support for both numeric and string data types in select
  • Support for implicit style attributes

9. Fuzzy Dropdown

fuzzy Dropdown

https://github.com/zeusdeux/fuzzy-dropdown

Fuzzy-dropdown is a jQuery plugin that converts a select box into a fuzzy searchable dropdown. Fuzzy string matching is a technique for finding strings that match a pattern approximately rather than exactly. Fuzzy-dropdown delegates interactions to the underlying select box. Also, the dropdown is fully navigable via arrow keys. Fuzzy-dropdown by itself does no styling. All the styling is controlled via CSS. This gives you complete freedom to style your dropdown however you want.

10. DDList

DDList

http://code.cwwonline.be/serviceddlistjquery

DDlist is a lightweight jQuery plugin that allows you to create a stylish dropdown list supporting list options with text, images, and additional description strings. This plugin hides the select element and the list is ‘reconstructed’ by means of a jQuery-generated <ul> list inside a <div> container. The select element options can also be defined via a JSON array object. The plugin comes with a CSS file that contains various classes to present the internal elements and their styles, giving you the option to modify the existing style to match with your website design.

11. ddSlick

ddSlick

http://designwithpc.com/Plugins/ddSlick

Ever wanted a dropdown with images? Well, you now have a plugin for that! ddSlick is a free and lightweight jQuery plugin that allows you to create a custom dropdown with images and descriptions.

  • Adds images and descriptions to otherwise bland drop downs
  • Allows JSON to populate the drop down options
  • Converts your HTML select element to ddSlick
  • Uses Minimum CSS and no external stylesheets to download
  • Supports call-back functions on selection

12. Dropdown Checkboxes

Dropdown Checkboxes

https://github.com/creativecirclemedia/dropdown-checkboxes

Dropdown checkboxes is a simple jQuery plugin that turns a bootstrap dropdown component into a compact multi-select dropdown list with checkboxes. This plugin creates a hidden input element. When the values are checked and saved, the plugin creates a JSON array of all checked values and assigns the same to the hidden input box. This plugin also allows you to pre-check the checkboxes on page load. When the selected checkbox’s text values goes beyond a certain length, then the plugin truncates the string value for better UI arrangement.

13. Hierarchy Select

Hierarchy Select

https://github.com/NeoFusion/hierarchy-select

Hierarchy Select is a lightweight jQuery plugin which converts the Bootstrap dropdown into a filterable dropdown list. This plugin works well for simple dropdowns and also for hierarchical dropdown, both with the option to search. You need to define an input element just above the select element. The plugin makes use of this input element to create search functionality for the select box. It attaches a keyup event to the input box and responds to keyboard interaction. For searching the text, it makes use of the indexOf() function which returns the position of the first occurrence of a specified value in a string.

14. Selectric

Selectric

http://selectric.js.org/

Selectric is a fast, simple, and light jQuery plugin designed to help in stylizing and manipulating traditional HTML selects elements. It also allows you to select multiple elements and add icons to select list items. It features:

  • Keyboard navigation (Up/Down/Left/Right/Word search)
  • Easy customization
  • Permanently visible options box
  • Independence from external libraries (besides jQuery)
  • Word search compatibility with western Latin characters set
  • 10 built-in themes
  • The ability to dynamically add items to select the element
  • Support for various callbacks for customizable handling
  • Options to populate the data via Ajax
  • Support for custom HTML markup

15. Sumo Select

Sumo Select

http://hemantnegi.github.io/jquery.sumoselect/

Sumo Select is a beautiful and cross-device jQuery plugin that progressively enhances an HTML Select Box into a Single/Multiple option dropdown list. The dropdown list can be fully customizable using simple CSS. It can adapt itself according to any device, keeping the User Experience unbroken. It features:

  • Single and Multi-select options
  • Search support
  • Optgroup support
  • Localization support
  • Full customization by simple css
  • Support for almost all devices
  • Intelligent rendering according to device
  • Rendering native Single/Multiple pop-ups on Android, iOS, Windows and other devices
  • Custom postback data format
  • Selected, Disabled, Select All, keyboard navigation and Placeholder support
  • A redesigned UI (No external icons are used now and the color scheme can be controlled by CSS)
  • Easy extendability to allow developers to create new widgets

16. Fast Select

FastSelect

http://dbrekalo.github.io/fastselect/

Fastselect is a lightweight plugin for enhanced select elements based on jQuery. It enables responsive, fast, and sensible UI upgrades of selected elements with features like option searching and remote dataset loading. It weighs less than 5KB (minified and gzipped). It provides features like searching, filtering, tagging, single-select, multi-select, autocomplete, and dynamic AJAX content.

17. Selectize

Selectize

http://selectize.github.io/selectize.js/

selectize.js is a lightweight plugin for creating a solid and user-friendly select list with clean and powerful APIs. It’s useful for tagging, contact lists, country selectors, and so on. It clocks in at around ~7kb (gzipped). It features:

  • Skinnability – Comes with LESS stylesheets and shims for Bootstrap 2 and Bootstrap 3.
  • Clean API, code, and extensibility
  • Smart Ranking / Multi-Property Searching & Sorting – Options are efficiently scored and sorted on-the-fly
  • Caret between Items – Use the left and right arrow keys to move between items
  • Select and delete multiple items at once
  • RTL supported – Great for international environments
  • Item Creation – Allow users to create items on the fly
  • Remote Data Loading

18. Light Weight Select

LightWeightSelect

https://github.com/keyo321/jQueryLightWeightMultiSelect

This is a super lightweight jQuery plugin that converts a multi-select drop menu into a simple two panel selection interface. The UI is completely controlled via CSS, so you can change the look and feel according to your needs. The plugin size is 4kb after minification, 2kb for the CSS and 2kb for the double arrow icon.

19. BetterSelecter

BetterSelecter

https://github.com/BenMMcLean/BetterSelecter

BetterSelecter is a simple, clean and easy to use jQuery plugin for converting the standard HTML select box into a stylish and sleek searchable select box. The styling is controlled via CSS classes which gives you flexibility to change the design per your requirements. This plugin appends a div element with a span inside to create a searchable select box and display the selected value.

20. SelectMe

SelectMe

https://github.com/bschueller/jquery.selectMe

selectMe is a jQuery-based select replacement plugin that replaces the large select element into a neat and searchable solution. It can also add a checkbox or radio button to the items for a better way of selecting the item. It supports:

  • Search for specific elements
  • Selecting or unselecting all elements which are currently shown
  • Show only selected elements
  • Optgroups
  • Navigating through elements with arrow keys (up + down)
  • Selecting elements via space key
  • Jumping directly to the search field when pressing a key while navigating in the dropdown

Conclusion

These lightweight and customizable jQuery plugins allow you to turn the normal HTML select elements into stylish and sleek select elements. These plugins offer various powerful features like searching, grouping, custom HTML markup, keyboard navigation, remote data loading, RTL support, multiple item selection, and other small but handy features. The other advantage is that all the plugins use simple CSS classes to style the select elements. This gives flexibility to the developers to override or change the default plugin style to your own style implementation.

Handling JSON with jQuery

JSON (JavaScript Object Notation) is a way to store information in an organized manner. It is the preferred data-interchange format as its shorter, lightweight, human-readable and requires no tags like XML. This allows faster processing and transmission, and also the serializing and deserializing becomes much faster when compared to XML. JSON returned via REST APIs is used in different ways on the client side. You can populate data in HTML elements, display the JSON on the UI after formatting and convert it to CSV for exporting. This post provides jQuery solutions for formatting the JSON, converting it to CSV format, and showing the JSON data in an HTML table. Let’s begin!

Format JSON in jQuery

Unformatted JSON is not human-readable and most of the time the JSON returned by REST APIs are not formatted, hence can’t be displayed directly on the UI. There are different ways to format it. Either using your own implementation or third-party plugins. Formatting the JSON using jQuery can be done easily and requires only 2 function calls.

  1. JSON.parse() – To parse a JSON string and convert it to a JavaScript object.
  2. JSON.stringify() – Convert a JavaScript object into a string. You can also apply indentation by passing an optional value.

The following jQuery code formats a JSON string:

var jData = '[{"fname":"Mark", "lname":"Wood", "company":"Apple"},' +
'{"fname":"Steve", "lname":"Jones", "company":"Amazon"},' + 
'{"fname":"Bill", "lname":"Peterson", "company":"HP"},' +
'{"fname":"Peter", "lname":"Jacobs", "company":"Dell"}]';

var tmpData = JSON.parse(jData);
var formattedJson = JSON.stringify(tmpData, null, '\t');

Here, the formattedJson variable will have the formatted JSON string, indented using tab. To display formatted JSON on UI, use the <pre> tag only. If you want to display inside a div, you would need to first append the <pre> tag in the div element. Like:

$('#dvText').append($('<pre>').text(formattedJson));

You can check out the demo here.

Convert JSON to CSV

If you want to convert JSON data to CSV for export purpose, the following jQuery code will help you. The following jQuery code defines a function called ConvertToCSV which takes JSON string, converts to CSV and returns it. Since it’s not compulsory to have comma as a delimiter for CSV, the delimiter is passed from outside which helps in changing the delimiter in the future without changing the actual function. The function first converts the JSON data into an array and then loops through the array to create a delimited string.

var jData = '[{"fname":"Mark", "lname":"Wood", "company":"Apple"},' +
  '{"fname":"Steve", "lname":"Jones", "company":"Amazon"},' +
  '{"fname":"Bill", "lname":"Peterson", "company":"HP"},' +
  '{"fname":"Peter", "lname":"Jacobs", "company":"Dell"}]';

var seperator = ',';
var sCSV = ConvertToCSV(jData, seperator);

function ConvertToCSV(jData, delimiter) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var sReturnVal = '';
  for (var i = 0; i < arrJSON.length; i++) {
    var sLine = '';
    for (var index in arrJSON[i]) {
      if (sLine != '') sLine += delimiter;
      sLine += arrJSON[i][index];
    }
    sReturnVal += sLine + '\r\n';
  }
  return sReturnVal;
}

You can check out the demo here.
The above function just creates a delimited string, it doesn’t allow you to save it as a .csv file. If you wish to export/download the JSON data into a CSV file with column headings and an optional report title, the following jQuery code provides a solution for the same. The modified function now expects 3 more parameters: report title, flag to display header, and a file name. While calling the function, please consider following things:

  • If you don’t wish to have a report title, pass an empty string.
  • In case you don’t need a column header, pass ShowHeader as false.
  • Pass the file name without the .csv extension.

The function does the following things:

  • First, parses the JSON data in an object, if not already.
  • If report title is not empty, appends the title to the variable.
  • If ShowHeader is true, then loop through the array’s 0th element to get the header columns and then appends them in the variable.
  • Then loop the array to get the data and creates a delimiter separated string.
  • Once the loop is completed, check the variable for any errors. An empty value means the JSON data is not correct. In such a case, it logs the error and exits the function.
  • If everything is correct, then initialize file format. The file format is CSV in this case.
  • Then it creates a temporary anchor tag and appends it to the HTML body with hidden visibility. Assigns the href and download attribute values and calls the anchor click function. Finally, removes it again from the body as it’s no longer needed.
function ConvertToCSV(jData, title, ShowHeader, fileName, delimiter) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var strCSV = '';
  //Set title first.
  if (title.length > 0)
    strCSV += title + '\r\n\n';
  if (ShowHeader) {
    var headerRow = "";
    for (var index in arrJSON[0]) {
      if (headerRow != '') headerRow += delimiter;
      headerRow += index;
    }
    strCSV += headerRow + '\r\n';
  }
  for (var i = 0; i < arrJSON.length; i++) {
    var sLine = '';
    for (var index in arrJSON[i]) {
      if (sLine != '') sLine += delimiter;
      sLine += arrJSON[i][index];
    }
    strCSV += sLine + '\r\n';
  }
  if (strCSV == '') {
    console.log('Error while converting due to invalid data');
    return;
  }
  var uri = 'data:text/csv;charset=utf-8,' + escape(strCSV);
  var link = document.createElement("a");
  link.href = uri;
  link.style = "visibility:hidden";
  link.download = fileName + ".csv";
  $('body').append(link);
  link.click();
  $('body').remove(link);
}

Call this function on any event to convert the JSON data into a downloadable CSV file like:

ConvertToCSV(jData, "Employee Data", true, "EmployeeReport", seperator);

You can check out the code in action here.

Convert JSON to HTML Table

The following jQuery code will create a table element, populates the table data from JSON data and appends the table element to the HTML body. The function uses jQuery syntax for different table elements like header row and table row. Inside the JSON array loop, it appends the data in appropriate objects, and finally it is added to the HTML body.

function ConvertToTable(jData) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var $table = $('');
  var $headerTr = $('');

  for (var index in arrJSON[0]) {
    $headerTr.append($(' ').html(index));
  }
  $table.append($headerTr);
  for (var i = 0; i < arrJSON.length; i++) {
   var $tableTr = $('');
    for (var index in arrJSON[i]) {
      $tableTr.append($(' ').html(arrJSON[i][index]));
    }
    $table.append($tableTr);
  }
  $('body').append($table);
}

Here the table formatting needs to be handled via CSS. You can also incorporate the same in this code with slight modifications.
You can check out the code in action here.

Conclusion

This post provides simple solutions for handling JSON on the client side in different ways. The jQuery implementation helps in formatting the unstructured JSON, converting the JSON data into a CSV string or downloadable CSV file with customization and displaying the JSON data in an HTML table. These jQuery codes are not dependent on any third-party plugins, which helps you to modify them as per your need without any hassle.

JavaScript-Equivalent jQuery Code for Simple Tasks

Introduction

There are developers who love jQuery and there are some who hate jQuery. The benefits of using jQuery now are debatable, but there was a time when solving the cross-browser issue was a nightmare and using JavaScript was painful. If you had been through that phase, you might understand the importance of jQuery. jQuery was born to overcome the biggest issues of JavaScript. Over the years, JavaScript has also evolved but we should be thankful for the fact that modern browsers are also becoming more and more standard-compliant. jQuery is still a powerful library and it can still reduce your efforts for client-side programming.

The aim of this post is not to discourage your use of JavaScript, but rather to give you an insight into how jQuery can help to solve simple tasks compared to JavaScript. jQuery can help in reducing the lines of code and your efforts, lessen cross-browser compatibility issues, result in faster development, and it makes AJAX calls and animations dead simple. To start with, we’ll take a look at the most basic requirements like selecting elements on the page by their ID, class, and tag name and then we will look at some complex examples. Let’s dive in!

Selecting an Element by ID

JavaScript code

document.querySelector('#elmID'); // Modern Way - IE8 and above 
document.getElementById('elmID'); // Older Way 

jQuery code

$('#elmID');

As you can already see, we’ve used less code to select the element in jQuery.

Selecting an Element by Tag

Consider a use case to select all the paragraph elements on the page:

JavaScript code

document.getElementsByTagName('p'); 

jQuery code

$('p');

Again, shorter code in jQuery!

Selecting Elements by Class Name

To select all elements having dummy CSS class:

JavaScript code

document.getElementsByClassName('dummy'); // Older Way 
document.querySelectorAll('.dummy'); // Modern Way - IE8 and above

jQuery code

$('.dummy');

We can see a continuing trend of fewer and shorter lines of code in jQuery.

Change Body Background Color on Load

JavaScript code

function changeBackground(color) {
    document.body.style.background = color;
}
<body onload = "changeBackground('green');" >

jQuery code

$ ('body').css('background-color', 'green');

A single line of code accomplishes what takes four lines of code to accomplish in JavaScript.

Adding a CSS Class to Element

JavaScript code

if (el.classList)
  el.classList.add(className);
else
  el.className += ' ' + className;

jQuery code

$(el).addClass(className);

That’s three fewer lines!

Making an Ajax Call

JavaScript code

function loadValues() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById(“demo”).innerHTML = this.responseText;
        }
    };
    xhttp.open(“GET”, “/api/values”, true);
    xhttp.send();
}

jQuery code

function loadValues() {
    $.ajax({
        url: "/api/values",
        type: "GET",
        dataType: "json",
        success: function(data) {
            $('#demo').html(data);
        },
        error: function(response) {
            alert(response.responseText);
        }
    });
}

The jQuery version looks much cleaner and more readable, it also offers a better method for error handling.

Making a Simple Fade-Out Animation

JavaScript code

function fadeOut(element) {
    var op = 1; // initial opacity
    var timer = setInterval(function() {
        if (op < = 0.1) {
            clearInterval(timer);
            element.style.display = ‘none’;
        }
        element.style.opacity = op;
        element.style.filter = ‘alpha(opacity = ’+op * 100 + “)”;
        op -= op * 0.5;
    }, 500);
}
var element = document.getElementById(‘elm’);
fadeout(element);

jQuery code

$("#elm").fadeOut();

There is no need to judge here who is better: jQuery is the clear winner.

Conclusion

We’ve just seen how jQuery can make life much simpler for easy tasks. Some functionality can be achieved by just one line of code in jQuery that requires 15-20 lines of JavaScript to achieve the same result. jQuery is an awesome library and it’s still very popular among developers. You should consider it as an alternative for fast development and without worrying about cross-browser issues. However, you should also be careful as it's large file to load! 

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") & 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
    }
}