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>