jQuery
jQuery Create Function Example
Have you ever come across a situation where you need to create function in jQuery but did not know how to do it? In this article, I am going to share a very simple and easy way to create function / define custom function using jQuery with an example.
How to use jQuery to Create Custom Function / Define Custom Function
It’s very easy to create and call custom function using jQuery, once you get the hang of it. So we are going to look at how to use jQuery to call custom javascript function by means of an example.
Example: Define a custom function using jQuery
<html>
<head>
<title>Create Function | Define Custom Function using jQuery</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>
<body>
<div id="my_div" class="my_class">This is some content.</div>
<input type="submit" name="call_function" id="call_function" value="Call jQuery Function" />
<script type="text/javascript">
$(document).ready(function() {
$('#call_function').click(function(){
//Call my custom jQuery function when the button is clicked
$.fn.my_function();
});
//This is my custom function that I defined in jQuery
$.fn.my_function = function() {
alert('This alert is a result of creating function / defining custom function in jQuery.');
}
});
</script>
</body>
</html>Once you run the above code, simply click on the “Call jQuery Function” button to show the alert. This alert is inside our custom function that we defined.
Simple, isn’t it?
Do you know of any other ways to create custom function using jQuery? Feel free to suggest by commenting below.
Ty, i love it!
May 31, 2013 at 1:41 am
nice example
ravi
May 24, 2014 at 7:04 pm