Search code examples
javascriptjquerypluginstablesorter

JQuery Plugin File Loading But Is Not Working


I am attempting to load the tablesorter JQuery plugin, I am using JQuery version 2.1.1 and the latest version of tablesorter. I load them in the following order :

<script src="javascript/jquery-2.1.1.min.js"></script>
<script src="javascript/jquery.tablesorter.min.js"></script>

I have tried forks of tablesorter and none of them work. I tested that I had the right plugin file location by putting

alert("Plugin File");

at the top of the file and this works when the page loads.

None of the plugins functionality is working and I tested it using this code :

$(document).ready(function(e){
  if(jQuery.fn.tablesorter){
    alert("pluginloaded");
   }
     jQuery.tablesorter();
   }
}

The alert does not work and firebug reports that tablesorter is not a function.


Solution

  • I think this issue is a combination of problems.

    1. The document ready function doesn't have a closing parenthesis, which is causing a javascript error making the function not run at all:

      $(document).ready(function(e){
          if (jQuery.fn.tablesorter) {
              alert("pluginloaded");
          }
          jQuery.tablesorter();
      });
      
    2. The second issue is that tablesorter is not being called properly. The line jQuery.tablesorter(); is trying to call the tablesorter function, but that is just an object that contains all of the tablesorter plugin functions.

      To actually call the plugin, you need to use a jQuery selector followed by the tablesorter function (this is why jQuery.fn.tablesorter works - it's jQuery's alias to the prototype property)

      $(function (e) {
          if (jQuery.fn.tablesorter) {
              alert("pluginloaded");
          }
          // jQuery.tablesorter(); // not the way to call the plugin
          $('table').tablesorter();
      });
      

    Here is a demo to show it working.