How to Create Function in jQuery with Examples

Last Updated on August 19, 2022 by Roshan Parihar

In this tutorial, learn how to create function in jQuery. The short answer is to use the code function myfn(){} to define a function within which you can add your code to execute.

You can also use the other methods to create your function using jQuery. Let’s find out with the different examples given below.

Method 1: Using function myfn(){} to Create Function in jQuery

To define your function in jQuery, you have to use the function word after which define the name of the function. The complete code will be function myfn(){} in which you have to replace myfn with your function name.

See the example to learn the method.

Output



The example first defines a function using the method. After that, it uses the click event to call the function and execute the code present inside it. When you click the button given above, it will execute the code inside the function that displays an alert message.

Method 2: Using $.fn.myFn=function(){} to Define

In addition to the above example, you can also use the code $.fn.myFn=function(){} in which myfn is the function. You need to change the name myfn with your function name to create a function using jQuery.

Output



The above example contains the same function name but with a different method to create. However, it works the same as the previous method and gives you the alert message on a button click.

One thing you should notice here is that the function call inside the click event is also different from the previous method.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.