Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
How can I avoid repeating this particular code for page load and for DOM changes?

For context, I'm building a JS calculator whereby the values displayed dynamically change in a 'summary box' as the user changes the values in the input fields (using a <form> element).

I have set default values in the <input> elements of the form, but the calculation functions in the summary box only get called as a keyup function when the values in the input fields are changed.

I have managed to get this to work perfectly, however, on page load the summary box values do not change as this is based on the keyup function (which hasn't occurred yet), so even though there are default values in the inputs, the summary box has nothing to calculate from (as it's waiting for the keyup functions to execute).

Now, I have found a workaround by repeating the DOM blocks to replace values on page load, but the code isn't very DRY. I am sure there must be a way to do this. I have tried to put the code block in an array and/or object but I am unable to successfully extract and execute this.

// THESE ARRAY ITEMS REPRESENT THE INPUT FIELDS IN THE HTML
const innerElementsArr = [investment, buying, selling, invFee];

// APPLYING THE DOM CHANGES TO EACH INPUT ELEMENT ABOVE
innerElementsArr.forEach(item => {
  item.onkeyup = function() {
    invDisplay.innerText = `£${investment.value}`;
    netProfit.innerText = `£${grossProfitLoss()}`;
    invFeeDisplay.innerText = `£${withInvFee()}`;
    netProfitLossDisplay.innerText = `£${netProfitDisplay()}`;
  };
});

// DISPLAY ALL CALCULATIONS ON PAGE LOAD
invDisplay.innerText = `£${investment.value}`;
netProfit.innerText = `£${grossProfitLoss()}`;
invFeeDisplay.innerText = `£${withInvFee()}`;
netProfitLossDisplay.innerText = `£${netProfitDisplay()}`;

As you can see, I am repeating myself and would like to know if there is a much more cleaner way to do this.

Thank you in advance.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Thank you to Ouroborus for the answer - it was such a simple workaround.

I created a function including the DOM block and then called that function as a keyup event and a window.onload event.

const valuesToChange = () => {
  invDisplay.innerText = `£${investment.value}`;
  coinDisplay.innerText = `${coinsOwned()} BTC`;
  netProfit.innerText = `£${grossProfitLoss()}`;
  invFeeDisplay.innerText = `£${withInvFee()}`;
  exitFeeDisplay.innerText = `£${withExitFee()}`;
  netProfitLossDisplay.innerText = `£${netProfitDisplay()}`;
};

// CHANGING THE VALUES IN THE SUMMARY AREA
const innerElementsArr = [investment, buying, selling, invFee, exitFee];
innerElementsArr.forEach(item => {
  item.onkeyup = function() {
    valuesToChange();
  };
});

// DISPLAY ALL CALCULATIONS ON PAGE LOAD
window.onload = function() {
  valuesToChange();
};

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda