Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

81
Vistas
Combine multiple similar JavaScript functions into one

I'm creating an extension that requires copying to clipboard, but I don't want to have 18 different functions that do (pretty much) the exact same thing.

This is the function that I wrote:

function copyS1_1() {
    var letter_to_copy = document.getElementById('textarea-S1-1');
    letter_to_copy.select();
    navigator.clipboard.writeText(letter_to_copy.value);
}
function copyS1_2() {
    var letter_to_copy = document.getElementById('textarea-S1-2');
    letter_to_copy.select();
    navigator.clipboard.writeText(letter_to_copy.value);
}

Each function is called 'copyS#_#' for 'Section' then the number in that section. I don't want to have 18 of these, so I'm looking for a way to simplify it down to 3 functions (one for each Section, there's 3.)

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can do this with template literals and function arguments.

function copyFuncForAny(num1, num2) {
    var letter_to_copy = document.getElementById(`textarea-S${num1}-${num2}`);
    letter_to_copy.select();
    navigator.clipboard.writeText(letter_to_copy.value);
}

copyFuncForAny(1, 1);
copyFuncForAny(1, 2);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could add a parameter:

function copyS1(id) {
    var letter_to_copy = document.getElementById('textarea-S1-' + id);
    letter_to_copy.select();
    navigator.clipboard.writeText(letter_to_copy.value);
}

Use like this:

copyS1(1)
copyS1(2)
...
about 4 years ago · Juan Pablo Isaza Denunciar

0

its simple just your own function like this

function copyText(id) {
    var letter_to_copy = document.getElementById(id);
    letter_to_copy.select();
    navigator.clipboard.writeText(letter_to_copy.value);
}

use it as many time as you want.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda