Brispo
Brispo

Reputation: 55

Is there a way to trigger a jquery function if document.ready OR if an element is clicked?

I have a function that fires an ajax call when the page is initially loaded, but I want to be able to fire that same ajax call if my user clicks a 'refresh' button on the page. Currently I accomplish this by having two completely separate (but identical) functions. One fires on $(document).ready( and the other fires on $(document).on('click'

Any way to consolidate these so it's just one function that gets fires on either document.ready OR document.on'click'?

Upvotes: 0

Views: 102

Answers (2)

Angel Politis
Angel Politis

Reputation: 11313

Simply define it and pass it as an argument.

function func () {}

$(document).ready(func); // or $(func)

$(document).on("click", ".your-btn", func);

Upvotes: 3

N'Bayramberdiyev
N'Bayramberdiyev

Reputation: 3620

You can also define a variable and assign your function to it as an expression. Then, call it immediately and use wherever you want.

$(document).ready(function() {
    let foo;

    (foo = function() {
        console.log('Foo');
    })();

    $(document).on('click', '<selector>', foo); // $('<selector>').click(foo);
});

Upvotes: 0

Related Questions