JQuery error: $("#") is not a function


JQuery is gaining popularity day by day and at times we end up using multiple jQuery elements on a single page. With this it brings many issues, if we just go on and copy jQuery elements directly into webpages from the internet. The first and foremost error that we encounter and infact I also faced is the jQuery error message
          $("#") is not a function


* Using jQuery objects
    Adding any jQuery into the code usually includes the following lines of code:

   
    $(document).ready(function(){
        $("#breadcrumbs").xBreadcrumbs();
    });


    '$' sign here signifies the symbol used for initialization of jQuery Object. '$' is an alias to jQuery object - 'jQuery' itself. To this object, we can pass selector, function, string etc. to execute a particular functionality. e.g. in the above code snippet, '$(document).ready(function)' binds a function to the ready event of the document. This simply means that whenever the document is finished loading it will call the specified function.

* Using two jQuery objects together
    Everything is fine till '$' is bound to a single jQuery element. But, if we try to bind it to one more element in the same way, we are bound to have issues. The new initialization will try to bind the '$' element with multiple entities and thus resulting in conflicts with the error message "$ is not a function" on console.

   
    $(document).ready(function(){
        $("#breadcrumbs").xBreadcrumbs();
    });

    $(document).ready(function() {
        $("#tabs").tabs();
    });


    Using the above code will result in "$("#breadcrumbs") is not a function" error message if you are using firebug or any other debugger.

* So, What is the Workaround ?

    Luckily, we have a very easy workaround to circumvent this issue. jQuery provides us with "jQuery.noConflict()" construct which releases jQuery's control of '$' variable. This construct makes sure, that the control for '$' variable goes back to the first entity created and hence ensures that there is no conflict for the usage of '$' variable.
    Also, you would require to use 'jQuery' as the new jQuery object for further invocation of jQuery elements because '$' is no longer available to this newer element invocation. Following is the way we can use both these methods collectively to avoid the before-mentioned errors:

   
    $(document).ready(function(){
        $("#breadcrumbs").xBreadcrumbs();
    });

    jQuery.noConflict();
        jQuery(document).ready(function(){
            jQuery("#tabs").tabs();
    });



If you want to know more then click jQuery.noConflict() for detailed reference.

-Pankaj
Happy Programming

comments powered by Disqus