In this post, we will learn how to define a function in jQuery. In jQuery for defining a function is little bit different. So how we can define a function, we will learn in this post.

How to Define A Function In jQuery ?

Define A Function In jQuery

To define a function in jQuery, we use this syntax  $fn.myFunction=function() {}  . Don't forget to use jQuery CDN before writing jQuery code.

In this given example we use jQuery function for alert when click on the button.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How To Define A Function In jQuery ?</title>
</head>
<body>

<button type="button" id="alertBtn">Click Me!</button>

<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<script>
$(document).ready(function(){
$.fn.myFunction = function(){
alert('Function Works!');
}

// Call the function when click on the button
$("#alertBtn").click(function(){
$.fn.myFunction();
});
});
</script>
</body>
</html> code-box



Summary

In this post we learned how to define a function in jQuery. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

Post a Comment

Previous Post Next Post