Functions Used with jQuery

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.

Basic Function Syntax Top ↑

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.

Run a Function After the DOM Is Ready Top ↑

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 →

Call a Function from a Click Event Top ↑

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 →

Call One Function from Another Handler Top ↑

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 →

Return a Value from a Function Top ↑

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 →

Function Tips for jQuery Code Top ↑

  • Use named functions when the same task is needed in more than one place.
  • Use parameters instead of creating several nearly identical functions.
  • Return a value when the function should calculate or prepare data rather than directly change the page.
  • Use .text() for plain text. Use .html() only when you intentionally need to insert HTML.

← jQuery basic structure · Next: jQuery events →






plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer