How to declare a function that has calls with quantities of different parameters?

Asked

Viewed 50 times

0

I have a function that is called every time the input element is in focus, only the calls are made with a number of different parameters.

How to declare the same function with passing variable parameters ?

input1.addEventListener("focus", function (){
    inputPlaceFocus(input1, ph1);
});
input2.addEventListener("focus", function (){
    inputPlaceFocus(input2, ph2, olho);
});

function inputPlaceFocus(input, ph, eye){
    if (input.value.length == 0){
        ph.style.transform = "translate(-6px, -20px) scale(.8)";
        ph.style.color = "deepskyblue";
        eye.style.visibility = "visible";
    }
};
var input1 = document.getElementById("mail");
var input2 = document.getElementById("pass");
var ph1 = document.querySelector("#ph1");
var ph2 = document.querySelector("#ph2");
var olho = document.querySelector(".fas");

3 answers

1


The job declaration stays the same, which you have to worry about is if that element exists;

function inputPlaceFocus(input, ph, eye){
    if (input.value.length == 0) {
        ph.style.transform = "translate(-6px, -20px) scale(.8)";
        ph.style.color = "deepskyblue";
        if (eye) // < aqui, se o parametro nao for passado, a linha seguinte será ignorada
          eye.style.visibility = "visible";
    }
};

1

In the function declaration instead of setting the number of parameters in a form static what you can do is use Rest Parameters, so you leave the amount of dynamic parameters, no matter the amount passed:

function inputPlaceFocus(...params) {
  return arguments.length
}

console.log(inputPlaceFocus(1,2,3))
console.log(inputPlaceFocus(1,2,3,4,5))
console.log(inputPlaceFocus(1,2))

0

A more elegant solution

input1.addEventListener("focus", function (){
    inputPlaceFocus(input1, ph1);
});
input2.addEventListener("focus", function (){
    inputPlaceFocus(input2, ph2, olho);
});
// Defina o valor padrão, caso não seja passado por parâmetro
function inputPlaceFocus(input, ph, eye = undefined){
    if (input.value.length == 0){
        ph.style.transform = "translate(-6px, -20px) scale(.8)";
        ph.style.color = "deepskyblue";
        // faça um ternário, caso eye venha, ele atribui o "visible", caso não, undefined
        eye.style.visibility = eye ? "visible" : undefined;
    }
};

Browser other questions tagged

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