1

I would like to know how do I use the variables only once before the functions so I can use the variables without having to declare them again in each function?

window.onload = function() {
    document.getElementById("soma").onclick = soma;
    document.getElementById("subtracao").onclick = subtracao;
    document.getElementById("multiplicacao").onclick = multiplicacao;
    document.getElementById("divicao").onclick = divicao;

    function soma() {
        var n1 = parseFloat(document.getElementById("n1").value);
        var n2 = parseFloat(document.getElementById("n2").value);
        document.getElementById("resultado").value = (n1 + n2);
    }

    function subtracao() {
        var n1 = parseFloat(document.getElementById("n1").value);
        var n2 = parseFloat(document.getElementById("n2").value);
        document.getElementById("resultado").value = (n1 - n2);
    }

    function multiplicacao() {
        var n1 = parseFloat(document.getElementById("n1").value);
        var n2 = parseFloat(document.getElementById("n2").value);
        document.getElementById("resultado").value = (n1 * n2);
    }

    function divicao() {
        var n1 = parseFloat(document.getElementById("n1").value);
        var n2 = parseFloat(document.getElementById("n2").value);
        document.getElementById("resultado").value = (n1 / n2);
    }
}
P.S.
  • 15,970
  • 14
  • 62
  • 86
  • You should learn to use [DOMContentLoaded](https://developer.mozilla.org/docs/Web/Events/DOMContentLoaded) in place of `window.onload = ` — and [addEventListener](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) in place of `.onclick = ` – Stephen P Sep 27 '17 at 22:49

3 Answers3

1

You can declare the variable at the top of window.onload function, like this:

window.onload = function() {
  var yourVariable;
}

and you will be able to use this variable inside any of your functions (soma, subtracao, multiplicacao and divicao).

Here is an example:

window.onload = function() {
  var yourVariable = "Value";
  
  function testFunc() {
    console.log(yourVariable);
  }
  
  testFunc();
}

Here you can find more info about scope, global and local variables: https://www.w3schools.com/js/js_scope.asp

And here: https://stackoverflow.com/a/500459/6053654

P.S.
  • 15,970
  • 14
  • 62
  • 86
1

Define your n1 and n2 variables outside onclick functions:

window.onload = function() {
  document.getElementById("soma").onclick = soma;
  document.getElementById("subtracao").onclick = subtracao;
  document.getElementById("multiplicacao").onclick = multiplicacao;
  document.getElementById("divicao").onclick = divicao;

  var n1 = parseFloat(document.getElementById("n1").value);
  var n2 = parseFloat(document.getElementById("n2").value);

  function soma() {
    document.getElementById("resultado").value = (n1 + n2);
  }

  function subtracao() {
     document.getElementById("resultado").value = (n1 - n2);
  }

  function multiplicacao() {
    document.getElementById("resultado").value = (n1 * n2);
  }

  function divicao() {
    document.getElementById("resultado").value = (n1 / n2);
  }
}

Now you should provide n1 and n2 listeners for changes:

document.getElementById("n1").onchange = n1Change;
document.getElementById("n2").onchange = n2Change;

function n1Change() {
  n1 = parseFloat(document.getElementById("n1").value);
}

function n2Change() {
  n2 = parseFloat(document.getElementById("n2").value);
}
Ammar
  • 770
  • 4
  • 11
0

To make variables available to all functions, declare them in the enclosing scope of the functions - that is, in this case, declare them at the top of the page-ready (loaded) event handler.

This full demonstration include the advice I mentioned in my comment on the question; it uses the DOMContentLoaded event rather than onload, and it adds event listeners, where .onload = ... and onclick = ... blindly assigns event handlers, possibly replacing an existing event handler.

This is a fully complete .html file which you can save and load into your browser:

<!DOCTYPE html>
<html>
<head>
    <title>SO 46457061</title>
    <script>
    document.addEventListener('DOMContentLoaded', function(event) {

        // Get the two number and one answer elements once and store them,
        // saving us from having to traverse the DOM every time.
        // Declaring these here makes them available to all code within
        // this anonymous event-listener function.
        var n1el = document.getElementById('n1');
        var n2el = document.getElementById('n2');
        var resultEl = document.getElementById('result');

        // Attach a click-event handler to each of the buttons,
        // providing an anonymous function as the handler.
        document.getElementById('soma')
                .addEventListener('click', function(e) {
                    e.preventDefault();
                    // Log just to demonstrate
                    console.log('n1 = ' + n1.value);
                    console.log('n2 = ' + n2.value);
                    // Compute
                    resultEl.innerText = '' +
                        (parseFloat(n1.value) +
                         parseFloat(n2.value));
                });

        document.getElementById('subtracao')
                .addEventListener('click', function(e) {
                    // Stop what normally happens on a button-click, and...
                    e.preventDefault();
                    // ...instead set the text of the answer to the computed value
                    // This performs the operation on the numbers, as numbers,
                    // but adds a string at the start to force the result to be
                    // a String. This is not strictly necessary, since assigning
                    // it to .innerText also converts to a String.
                    resultEl.innerText = '' +
                        (parseFloat(n1.value) -
                         parseFloat(n2.value));
                });

        document.getElementById('multiplicacao')
                .addEventListener('click', function(e) {
                    e.preventDefault();
                    resultEl.innerText = '' +
                        (parseFloat(n1.value) *
                         parseFloat(n2.value));
                });

        document.getElementById('divicao')
                .addEventListener('click', function(e) {
                    e.preventDefault();
                    resultEl.innerText = '' +
                        (parseFloat(n1.value) /
                         parseFloat(n2.value));
                });

    });
    </script>
    <style>
    button {
        height: 1.5em;
        width: 1.5em;
        font-size: 20px;
        margin-bottom: 5px;
    }
    section {
        display: inline-block;
    }
    </style>
</head>
<body>

    <section id="numbers">
        <label for="n1">First Number</label> <input type="text" id="n1" name="n1">  <br>
        <label for="n2">Second Number</label> <input type="text" id="n2" name="n2"> <br>
        <span class="result">Result: <span id="result">_</span></span>
    </section>

    <section id="operators">
        <button id="soma">&#x2b;</button>
        <button id="subtracao">&minus;</button>     <br>
        <button id="multiplicacao">&times;</button>
        <button id="divicao">&divide;</button>
    </section>

</body>
</html>

Same thing, basically, but as a stack-snippet so you can see it in action right here.

document.addEventListener('DOMContentLoaded', function(event) {

    // Get the two number and one answer elements once and store them,
    // saving us from having to traverse the DOM every time.
    // Declaring these here makes them available to all code within
    // this anonymous function.
    var n1el = document.getElementById('n1');
    var n2el = document.getElementById('n2');
    var resultEl = document.getElementById('result');

    // Attach a click-event handler to each of the buttons,
    // providing an anonymous function as the handler.
    document.getElementById('soma')
            .addEventListener('click', function(e) {
                e.preventDefault();
                resultEl.innerText =
                    parseFloat(n1.value) +
                    parseFloat(n2.value);
            });

    document.getElementById('subtracao')
            .addEventListener('click', function(e) {
                e.preventDefault();
                resultEl.innerText =
                    parseFloat(n1.value) -
                    parseFloat(n2.value);
            });

    document.getElementById('multiplicacao')
            .addEventListener('click', function(e) {
                e.preventDefault();
                resultEl.innerText =
                    parseFloat(n1.value) *
                    parseFloat(n2.value);
            });

    document.getElementById('divicao')
            .addEventListener('click', function(e) {
                e.preventDefault();
                resultEl.innerText =
                    parseFloat(n1.value) /
                    parseFloat(n2.value);
            });

});
button {
    height: 1.5em;
    width: 1.5em;
    font-size: 20px;
    margin-bottom: 5px;
}
section {
    display: inline-block;
}
<section id="numbers">
    <label for="n1">First Number</label> <input type="text" id="n1" name="n1">  <br>
    <label for="n2">Second Number</label> <input type="text" id="n2" name="n2"> <br>
    <span class="result">Result: <span id="result">_</span></span>
</section>

<section id="operators">
    <button id="soma">&#x2b;</button>
    <button id="subtracao">&minus;</button>     <br>
    <button id="multiplicacao">&times;</button>
    <button id="divicao">&divide;</button>
</section>
Stephen P
  • 14,422
  • 2
  • 43
  • 67