'Click event not updating global variable
I have a website with 2 pages. In the first page (landing page), I have this clickable element:
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12" id="arrest-data" onclick="changeDisp()>
<div class="box-part text-center"> <i class="fa-solid fa-3x fa-handcuffs" aria-hidden="true"></i>
<div class="title">
<h3>Arrest Data</h3>
</div>
<div class="text"> <span>Crime data and other crime statistics</span> </div> <a href="#" class="get-data">GET DATA</a>
</div>
I want to change the value of a global variable when that clickable element is clicked:
var disp = 0;
function changeDisp(){
disp = 120
console.log(disp)
}
So this works and it prints 120
.
The problem is that the value of disp doesn't change globally.For example, on the second page, there's another dropdown menu:
<div class="container">
<div class="row dropdowns">
<div class="col-4">
<select id="categoryDropdown">
<option value="All">All Topics</option>
<option value="Category: Arrest Data">Arrest Data</option>
<option value="Category: Use of Force">Use of Force</option>
<option value="Category: Human Trafficking">Human Trafficking</option>
<option value="Category: Treatment and Diversion">Treatment and Diversion</option>
<option value="Category: Drug and Overdose Data">Drug and Overdose Data</option>
</select>
</div>
And when I test to see if the global variable is now 120 with this function:
$('.container').on("change", 'select', function() {
console.log(disp)
});
It still prints 0!
What am I doing wrong here? I want the value to change globally with the on-click event, and it doesn't seem to be doing that.
Solution 1:[1]
If you want to read and use values between separate pages you could use something like localStorage to store your values and then read from it when needed.
Ref: Window.localStorage
See the implementation below:
// Setter function
function setDisp(value) {
if (!isNaN(value)) {
localStorage.setItem('disp', Number(value));
}
}
// Getter function
function getDisp(defaultValue = 0) {
let localStorageValue = localStorage.getItem('disp');
return !!localStorageValue
? Number(localStorageValue)
: defaultValue;
}
let dispBeforeChange = getDisp();
console.log(`dispBeforeChange = ${dispBeforeChange}`);
// Changing the value of 'disp' to 120
setDisp(120)
let dispAfterChange = getDisp();
console.log(`dispAfterChange = ${dispAfterChange}`);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |