I have an object set up like so:
let xVal = 0;
const myObj = {
infoText: "The value of x is: " + xVal
}
This infoText is referenced later to display somewhat of a tooltip when hovering over an element.
function showTooltip(obj) {
targetEl = document.getElementById('targetId');
targetEl.innerHTML = obj.infoText;
}
The value of xVal can change. The issue I'm running into is that despite whether or not that value has changed, when I hover over my element, it will always display the initial value of xVal. I assume this is because myObj.infoText is established when it's initiated and pulls the initial value of xVal. How can I get myObj.infoText to show the current xVal and keep up with the changes?
EDIT - Here is a better example of my code, I realize I offered a poor sample originally.
let count = 0;
let clickVal = 1;
const myObj = {
cost: 10,
infoText: `This displays the current value of your click <br />
Current click = ` + clickVal
};
function cardContent(obj) {
targetEl = document.getElementById('targetId');
targetEl.innerHTML = obj.infoText;
}
cardContent(myObj); // initialize card content
function handleClick() {
count += clickVal;
}
function upgradeClick() {
count -= myObj.cost;
clickVal += 1;
cardContent(myObj) // attempting to update the text to reflect new value
}
There is a button that invokes handleClick and one that invokes upgradeClick. Using CSS, the following div is hidden and shows when hovering over the upgradeClick button.
<div id='targetId'></div> This is where the infoText shows.
You can use something like a getter
let xVal = 0;
const myObj = {
get infoText() {return "The value of x is: " + xVal;}
}
function showTooltip(obj) {
console.log(obj.infoText);
}
showTooltip(myObj);
xVal = 29;
showTooltip(myObj);
xVal = 794;
showTooltip(myObj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With