Code: 1
Conversor Kilo -> Pound com toggle calc
by Lucas Fontes Gaspareto
HTML
<div>
<!-- Label + Input referente ao valor base da conversão -->
<label id="lblValor" for="iptValor">Kilos</label>
<input type="number" id="iptValor">
<!-- Neste botão será adiciona um evento de click -->
<button id="trocar">Trocar</button>
<!-- Label + Input referente ao resultado da conversão -->
<label id="lblResultado" for="iptResultado">Pounds</label>
<input type="number" id="iptResultado">
<!-- Neste botão será adiciona um evento de click -->
<button id="calcular">Calcular</button>
</div>
JavaScript
var conversor = {
// Valores do Objeto conversor
valor : document.getElementById('iptValor'),
resultado : document.getElementById('iptResultado'),
labelValor : document.getElementById('lblValor'),
labelResultado : document.getElementById('lblResultado'),
unidade : 2.2046,
operacao : 'Kilos',
// Valores Funções do Objeto conversor
Kilos : function() {
return this.valor.value * this.unidade;
},
Pounds : function() {
return this.valor.value / this.unidade;
},
trocar : function() {
this.labelResultado.innerText = this.operacao;
this.operacao = this.operacao === 'Kilos' ? 'Pounds' : 'Kilos';
this.labelValor.innerText = this.operacao;
this.calcular(this.valor.value);
},
// Função para conversão.
calcular : function() {
if(this.valor.value != '')
this.resultado.value = conversor[this.operacao]().toFixed(4); // .toFixed(4) fixa 4 casas decimais.
}
}
// Adiciona o evento click ao botão trocar
document.getElementById('trocar').addEventListener('click', function() {
conversor.trocar(); // Chama a função que troca a conversão
}, false);
// Adiciona o evento click ao botão calcular
document.getElementById('calcular').addEventListener('click', function() {
conversor.calcular(); // Chama a função que calcula a conversão
}, false);