Use different CSS rules / styles in JavaScript or jQuery enabled browsers

This is a simple yet very useful and powerful technique. Using different CSS rules in JavaScript or jQuery enabled browsers lets you customize your website style for JS enabled and disabled browsers using only CSS. Thus you separate concerns of styling and business logic into CSS and javascript. This lets you concentrate on your goals and not styling in your javascript code for example.

All you need to do is to add some class or id to body element using javascript/jquery to specify that javascript/jQuery is available. Then define two rules in you CSS files for js enable and disabled browsers.

Here is an example for Javascript enabled browser:

document.getElementsByTagName("body")[0].setAttribute("class", "js");

And in your CSS file:

.someClass{
    display:block;
}
.js .someClass{
    display:none;
}

Why do I need to have a different CSS styles for jQuery/javascript enabled browser you might ask. Consider you have a drop-down menu on your website’s sidebar and you would like to use jQuery/Javascript to make it drop down on mouse hover. You don’t want to hide (display:none) all submenus’ by default. That would make your website not accessible if user has disabled Javascript on his/her browsers.

Similar to previous example, we can use difference CSS style for jQuery enabled browsers.

if(jQuery){
    jQuery("body").addClass("jq");
}

And in your CSS file:

.someClass{
    display:block;
}
.jq .someClass{
    display:none;
}

Check if jQuery plugin is loaded

The previous post checked if jQuery is loaded, now it is time to check if particular jQuery plugin is loaded. Checking if plugin exists or if plugin has been already loaded is useful if you are writing your jQuery code that depends on that plugin.

Here is how to check if some jQuery plugin is loaded or not:

if(jQuery().pluginMethod) {
    //jQuery plugin exists
} else {
    //jQuery plugin DOES NOT exist
}

As you know from previous post on namespacing javascript plugins are created as an additional namespace within jQuery namespace. All you have to do to check if plugin exists is to check if it’s namespace / function is defined.

For example, let’s assume that my plugin depends on jQuery Validation plugin. To check if validation plugin is loaded I would do the following:

if(jQuery().validate) {
    // Validation plugin exists
    // Now I can use $('#someId').validate()
} else {
    // Validation plugin DOES NOT exist
}

Adding and using jQuery on Blogger / Blogspot

Investigating my visitors statistics, I noticed that there were some users who were interested in adding and using jQuery on their Blogger.com (Blogspot.com) accounts. Adding jQuery library to your Blogger/Blogspot blog is not difficult. All you have to do is to add one line of code to your template’s header.

Here is the code to add to your blogger template’s header:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>

NOTE:
You don’t even need to upload jquery.js file on any other hosting Google will host it for your.

Instruction for adding jQuery to Blogger:

  1. Login to your dashboard;
  2. Choose your blog;
  3. From the top menu select “Layout”;
  4. Then select “Edit HTML” sub-menu;
  5. Add the above code just below <head> tag (or alternatively, just above </head> tag)

Check if jQuery.js is loaded

This article discusses how to check if jquery.js file is loaded. Also, presents a way to force load jQuery file before running any dependant JavaScript code.

In order to determine whether jquery.js file is loaded or not, we need to check for existence of jQuery object. Because, when jquery.js file is loaded, it creates a new global jQuery variable. Checking if some class, method, variable or property does already exist is the very basics of any programming language. In our case, the programming environment is JavaScript and the object we are checking for is jQuery() (or $()).

This method is not limited to jQuery only, you can check existence of any other variable or function in your javascript.

Anyway, as we said earlier, jQuery() or $() functions will only be defined if they are already loaded into the current document. So to test if jQuery is loaded or not we can use 2 methods.

Method 1:

if (window.jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}

Method 2:

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded
} else {
    // jQuery is loaded
}

If jquery.js file is not loaded, we can force load it like so:

if (!window.jQuery) {
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  // Path to jquery.js file, eg. Google hosted version
  jq.src = '/path-to-your/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

NOTE:
Here we are checking for jQuery function being defined or not. This is a safe way to check for jQuery library being loaded. In case you are not using any other javascript libraries like prototype.js or mootools.js, then you can also check for $ instead of jQuery.

You can also check if particular jQuery plugin is loaded or not.

Dynamically creating input box/checkbox/radio button... does not work in Internet Explorer (IE)

While working on some project, trying to create a checkbox and radio button dynamically using jQuery I came across a problem. Mozilla Firefox, Opera and Safari were creating and rendering my new checkboxes just fine, but Internet Explorer (IE6, IE7) did not create them. I spend half a day trying to figure out what is wrong with my jQuery or JavaScript code. Some hours later, I remember, I came across a post saying that IE can not create a general DOM input form element and then assign it a type (checkbox, radio, text, password, etc) attribute.

What you need to do when you are creating a new checkbox or radio button set with jQuery is to define the type attribute while creating like so:

$('<input type="checkbox" />');
// Create and then set any other attributes
$('<input type="checkbox" />').attr('id', 'newBox');

Problem:

Can not create a new input form fields using jQuery or newly created checkboxes and radio buttons are not displayed/created.

Solution:

To solve the problem you need to create an input field with type attribute already defined.

Only the last element is bound/inserted/etc. in your javascript code’s “for” loop

There is a common problem when you use javascript for loop to bind an event function or add a class that comes from looping selection’s attributes.

To make clear what I mean consider this example:

var lis = $('ul li');

for (var i = 0; i<lis.length; i++) {
    var id = lis[i].id;
    lis[i].onclick = function () {
        alert(id);
    };
} // All li's get and alert the last li's id

There is no obvious code syntax nor logical problem in this code. But you still will get last li’s id in alert window whichever li you click.

The solution to this problem is to rewrite your code similar to this one:

var lis = $('ul li');

for (var i = 0; i<lis.length; i++) {
    var id = lis[i].id;
    lis[i].onclick = function (the_id) {
        return function () {
            alert(the_id);
        };
    }(id);
}

Here, we are introducing another anonymous function which will be called immediately after it has been declared, because of the trailing () (in our case (id)) with the current id.

This solves the problem of all items in the loop getting the last arrays/elements/etc. attribute value (id/class/etc.).

Convert javascript objects into arrays for better performance

jQuery Howto blog has many posts on your javascript  and jQuery code performance. If you have read the last performance post named “5 easy tips on how to improve code performance with huge data sets in jQuery” then you probably got an idea that it’s better to work with arrays for better javascript performance.

The only problem is that jQuery returns an object not an array when you select elements. Consider you have an object with lots of entries and you have to perform some manipulations that are available in javascript array such as reverse, sort, join, etc. Using built in methods is much faster then those you might write yourself. So the best thing would be converting your objects to arrays and jQuery provides utility method that does exactly this – jQuery.makeArray(obj).

// From jQuery Documentation
var arr = jQuery.makeArray(document.getElementsByTagName("div"));
arr.reverse(); // use an Array method on list of dom elements
$(arr).appendTo(document.body);