button is triggered without me clicking - jquery

Asked

Viewed 29 times

-3

    let aplicarCor = function(elemento, cor){
        elemento = ("#" + elemento);
        $(elemento).css("background-color", cor);
    };

    $("#laranja").on("click", (aplicarCor("funcoesComEventos", "orange")));
    $("#verde").on("click", (aplicarCor("funcoesComEventos", "green")));
    $("#gray").on("click", (aplicarCor("funcoesComEventos", "gray")));

1 answer

4

The method on jquery expects a function of callback as second parameter, but you are not passing a function, you are calling the function and passing its return.

You can fix this by declaring a callback function, which invokes its function aplicarCor.

let aplicarCor = function(elemento, cor){
    elemento = ("#" + elemento);
    $(elemento).css("background-color", cor);
};

$("#laranja").on("click", () => aplicarCor("funcoesComEventos", "orange"));
$("#verde").on("click", () => aplicarCor("funcoesComEventos", "green"));
$("#gray").on("click", () => aplicarCor("funcoesComEventos", "gray"));

Note that this abstraction is only necessary because you are invoking the function aplicarCor with different parameters on each call, if the function aplicarCor did not receive any parameter, you could write simply

$("#laranja").on("click", aplicarCor);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.