Solve - $(...).on is not a function jQuery Error

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Erik Mclean

Solve - $(...).on is not a function #

The "$(...).on if not a function" jQuery error occurs for 2 main reasons:

  1. Loading an old version of the jQuery library that doesn't support the on function.
  2. Loading a library that overrides the value of the dollar sign $ variable.

Here is a working example that shows how the on function is used in jQuery.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <!-- โœ… load jQuery โœ… --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous" ></script> </head> <body> <button id="btn">Click</button> <script src="index.js"></script> </body> </html>

We loaded a recent version of the jQuery library and defined a button, on which we'll add an event listener.

Here's the code for the index.js file.

index.js
$(document).ready(function () { $('#btn').on('click', function () { console.log('Button clicked'); }); });

If you load the page and click on the button, you will see the console.log output printed to the console.

The .on() function requires jQuery version 1.7 or newer.

If you are loading a script that overrides the value of the dollar sign variable, you can use the jQuery global instead.

index.js
jQuery(document).ready(function () { jQuery('#btn').on('click', function () { console.log('Button clicked'); }); });
This issue might occur if you load a script that overrides the value of the global dollar sign variable after you have loaded the jQuery script.

Loading multiple scripts that override the same global variable can be quite confusing, because the script that is ran last wins.

Conclusion #

To solve the "$(...).on if not a function" jQuery error, make sure to load a recent version of the jQuery library and check if you are including any scripts that are overriding the value for the global dollar sign $ variable after you load the jQuery script.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee