Run the code once to load the page, then each time the button is clicked

I need the function to run once when the page loads, and then again whenever the button is clicked. If I take out the code to run it when the page loads, it works every time the button is clicked, otherwise it only works once on the page load and the button will never be pressed.

$(function()
{
    // code to be run
});

$(document).ready(function()
{
    $("#button").click(function()
    {
        // code to be run
    });
});
+3
source share
2 answers
function run(){
    //code to run
}
$(document).ready(function()
{
    $("#button").click(function()
    {
        run()
    });
    run()
});
+8
source

Define a function:

$(function() {
    var your_code = function() {
        // code to be run
    };
    $("#button").click(your_code);
    your_code();
});

Working example .

+2
source

Source: https://habr.com/ru/post/1785260/


All Articles