0

A beginner question:

I'd like to create an app where I obtain an imaginary number from user and plot it to complex plane. Since I'm hoping to add other things later, I keep the code in separate files, connected in HTML file.

In first file, I get the real and the complex part from the user:

$(document).ready(function() {
$("#button-number").click(function() {
    var realPart = prompt("Please, enter the real Part of the number:")
    var imagPart = prompt("Please, enter the imaginary Part of the number:")
});})

which I use in the second file:

$(document).ready(function() {
var c = document.getElementById("ComplexPlane");
var number = c.getContext("2d");
number.beginPath();
number.arc(500+50*realPart,300-50*imagPart,10,0,2*Math.PI);
number.stroke();
number.fill();})

However, this doesn't work. It works if I define the variables manually outside the function. I'm not entirely sure how are all the operations timed, since my variables aren't defined when the document loads. I'd love to know how to solve this issue.

Ardweaden
  • 857
  • 9
  • 23
  • 2
    Possible duplicate of [What is the scope of variables in JavaScript?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Turnip Jul 06 '16 at 11:14
  • Try using a module loading system. – gcampbell Jul 06 '16 at 11:15
  • Possible duplicate of [Javascript Accessing Variables Defined in External .js files](http://stackoverflow.com/questions/10864732/javascript-accessing-variables-defined-in-external-js-files) – Arnav Borborah Jul 06 '16 at 11:30

2 Answers2

0

This works as expected.

Instead using global variable scope you could use localStorage

http://www.w3schools.com/html/html5_webstorage.asp

you can store the real an imaginary part numbers in localStorage in your first file. And you can access them in your second file.

0

I this what your trying to do?

$("#button-number").click(function() {
  var realPart = prompt("Please, enter the real Part of the number:")
  var imagPart = prompt("Please, enter the imaginary Part of the number:")
  if (realPart != null && imagPart != null) {
    var c = document.getElementById("ComplexPlane");
    var number = c.getContext("2d");
    number.beginPath();
    number.arc(parseInt(realPart),parseInt(imagPart),10,0,2*Math.PI);
    number.stroke();
  } 
});

https://jsfiddle.net/LeroyRon/93jvtrae/ Or part of what your doing...
realPart and imagPart could be set in a global scope or storage.

Leroy Thompson
  • 470
  • 3
  • 13