Snippets

Define a Function in jQuery

Posted by I. B. Gd Pramana A. Putra, 06 Aug 22, last updated 06 Aug 22

We can define a function in jQuery by using the $.fn and followed by the function name, as an example:

$.fn.ourFunction = function(){ 
    // code here
}

To call our defined jQuery function:

$.fn.ourFunction();

Full code example how we can define a function and call it 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-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $.fn.ourFunction = function(){ 
        alert('You just called your defined function!'); 
    }
    $(".test-function").click(function(){
        $.fn.ourFunction();
    });
});
</script> 
</head>
<body>
    <button type="button" class="test-function">Test Function</button>
</body>
</html>

I love sharing code snippets as most of the time, a quick code example is what we're looking for instead of long-written articles. If you think my code snippets are helpful and save you a lot of time, please consider buying me a cup of coffee :)

Support me via · paypal · buymeacoffee · ko-fi · trakteer
Contributed Snippets
Answer & Responses
    No comments yet

Wanna write a response?

You have to login before write a comment to this post.