How to define a function in jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the syntax $.fn.myFunction=function(){}

The following example will show how to define a function in jQuery.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>Define a Function in jQuery</title>
  • <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  • <script type="text/javascript">
  • $(document).ready(function(){
  •     $.fn.myFunction = function(){ 
  •         alert('You have successfully defined the function!'); 
  •     }
  •     $(".call-btn").click(function(){
  •         $.fn.myFunction();
  •     });
  • });
  • </script> 
  • </head>
  • <body>
  •     <button type="button" class="call-btn">Click Me</button>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.