How to make the same event work several times in different elements?

Asked

Viewed 81 times

4

I created a formula in which when clicking on a field its bottom edge changes color, and I used an onblur() so that the color returns to normal when clicking outside. However, I wanted this function to function individually in each input. Let each one change color when selected without having to write the same function several times for each id. How can I do this?

<form>

 <input type="number" placeholder="idade" id="a" onclick="azul()" onblur="nada()">

<input type="text" placeholder="nome" id="b" onclick="azul()" onblur="nada()">

(...)

</form>

<script>

function azul(){
    var a = document.getElementById("a");
    a.style.borderBottomColor = "#4976d0";
}

    function nada(){
         var a = document.getElementById("a");
         a.style.borderBottomColor = "transparent";    
    }

</script>
  • Create a Generic function by passing 2 parameters, one that is id and the other the color you want

2 answers

3

You can select all inputs from your form this way

let inputs = document.querySelectorAll("input");

Just note that if you with this line all the inputs of the page will be selected, then if you have more inputs on the page you can assign some class to the ones you want to select and modify the top row leaving it so

let inputs = document.querySelectorAll("input.suaclasse");

After selecting the inputs just do a foreach by adding the events like this

inputs.forEach(input => {

   input.addEventListener("click", () => {
       azul(input);
   });

   input.addEventListener("blur", () => {
       nada(input);
   });

});

Don’t forget to modify your functions leaving them like this

function azul(input) {
    input.style.borderBottomColor = "#4976d0";
}

function nada(input) {
   input.style.borderBottomColor = "transparent";
}

1

Just to leave it here as a reference, you can do what you want without using javascript, at least for the example you have in the question. Repair gives the style when you click (ie when you win phocus) and then removes the style when you click out (on Blur that is when you lose focus). Through CSS you can apply style to the focused element using the pseudo selector phocus.

Take the example:

input:focus {
  border-bottom-color: red; /*vermelho quando está focado*/
}

input {
  border-bottom-color: transparent;
}
<form>
  <input type="number" placeholder="idade" id="a">
  <input type="text" placeholder="nome" id="b">
  (...)
</form>

In this example I put the bottom edge in red to notice more. And to conclude, if you can do with CSS what you were doing with JS then it’s preferable to do it with CSS.

Browser other questions tagged

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