I’m creating a variable called current to store what button was just clicked. Then I want to use that info in another JS File when loading up a new HTML page. However, current still remains as "my_null". I’m assuming it’s still my_null because when file2 creates the new page, the problem_type_title displays "my_null"
I expected current to change to the value that I passed in based on which button was clicked. I ordered the JS Files correctly in my HTML files when using . I know the variable is being passed through files as problem_type is "my_null" and not undefined. However, it shouldn’t be "my_null" and should be "Geometry" for example.
Here is file 1
const geo = document.getElementById('geo');
const algebra = document.getElementById('alegbra');
const centroid = document.getElementById('centroid');
const angle_bisector = document.getElementById('angle_bisector');
const two_pole = document.getElementById('two_pole');
const herons = document.getElementById('herons');
const x_intercept = document.getElementById('x_intercept');
const inverse_functions = document.getElementById('inverse_functions');
const challenge = document.getElementById('challenge');
var current = 'my_null';
geo.addEventListener('click', () => {update_curr('Geometry')});
alegbra.addEventListener('click', () => {update_curr('Alegbra')});
centroid.addEventListener('click', () => {update_curr('Centroid')});
angle_bisector.addEventListener('click', () => {update_curr('Angle Bisector')});
two_pole.addEventListener('click', () => {update_curr('Two Pole')});
herons.addEventListener('click', () => {update_curr("Heron's Formula")});
x_intercept.addEventListener('click', () => {update_curr('X-intercept')});
inverse_functions.addEventListener('click', () => {update_curr('Inverse Functions')});
challenge.addEventListener('click', () => {update_curr('Challenge Problems')});
function update_curr(clicked) {
current = clicked;
}
Here is file 2
// Deleted code before this function for readability
async function update(url){
// Setting value of current as a variable in this function
let problem_type = current;
let id = await set_problem(url);
url = url + "challenges/" + id;
console.log(url);
console.log("id = " + id)
fetch(url).then(res => res.json())
.then(function(problem) {
console.log(problem);
img = problem.img;
answer = problem.answer;
div_main = document.createElement('div');
div_main.innerHTML = `
<div class='trainer_area' id='trainer_area'>
<div class='problem_type_title'>
// Accessing the variable
${problem_type}
</div>
// More code that doesn't matter
2
Answers
I don't really know why the problem was occurring but I used localStorage and onclick() instead of addEventListener() and I got the information to pass between files. The root of my error was likely something wrong with addEventListener as I saw my console giving me error related to that.
File 1:
File 2:
You can define a getter function to get the latest value of the
current
variable.Try this :
file1
file2