Functions used in jQuery code are normal JavaScript functions. You can define a function once, pass values into it, call it from a jQuery event handler, and return a result for other code to use.
function showMessage(message) {
$("#d1").text(message);
}
In this example, message is a parameter. Each time you call the function, you can supply a different value.
Define the function and call it from the jQuery ready handler when you want it to run as soon as the page DOM is available.
$(function () {
function showMessage(message) {
$("#d1").text(message);
}
showMessage("Welcome to Plus2net");
});
Demo: execute a function on page load →
Keep the HTML free of inline JavaScript and attach the event handler with jQuery.
<button type="button" id="b1">Show message</button>
<div id="d1"></div>
$(function () {
function showMessage(message) {
$("#d1").text(message);
}
$("#b1").on("click", function () {
showMessage("Hi");
});
});
Demo: execute a function on button click →
Separating reusable work into a named function keeps the event handler short and lets other parts of the page call the same logic.
function showMessage(message) {
$("#d1").text(message);
}
$("#b1").on("click", function () {
showMessage("Hi");
});
Demo: call a user-defined function →
A function can return a value instead of updating the page directly. The calling code can then decide where to use the result.
function createMessage(name) {
return name + ", I am Plus2net";
}
$("#b1").on("click", function () {
const message = createMessage("Hi");
$("#d1").text(message);
});
Demo: return a value from a function →
.text() for plain text. Use .html() only when you intentionally need to insert HTML.← jQuery basic structure · Next: jQuery events →
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.