I made a little "font-size widget" for my website. Now today I was looking to implement sessionstorage so users don't have to click the button all the time.
The standard font-size is 20. Now, I have no idea why, but sometimes, ONLY when I hit button2 (to have a bigger size) the value becomes literally 20 + 2 => 202. I don't know how or why.
Does anyone have an idea on how to improve performance and solve this code? Or, if you think cookies are a better idea, how would I implement cookies for this piece of code?
var currentSize;
function confSize(){
if (sessionStorage.getItem('sessionSize') == ""){
$("#body").css("font-size", "20px");
}
else {
currentSize = sessionStorage.getItem('sessionSize');
$("#body").css("font-size", currentSize + "px");
console.log(sessionStorage.getItem('sessionSize'))
}
$("#button2").click(function(){
if (currentSize == 20){
currentSize = 22;
}
else {
currentSize = currentSize + 2;
}
sessionStorage.setItem('sessionSize', currentSize);
$("#body").css("font-size", currentSize + "px");
});
$("#button").click(function(){
currentSize -= 2;
sessionStorage.setItem('sessionSize', currentSize);
$("#body").css("font-size", currentSize + "px");
});
}
You need to make sure you are correctly using values as strings and integers as appropriate. If you do an operation like:
currentSize = currentSize + 2
You are going to get different values depending on whether currentSize
is currently a string or an integer. If it is a string, you get the concatenation problem you note.
Now, you actually compound this with the problem that when you insert the integer currentSize
value into sessionStorage
, there is automatically a integer to string conversion made for storage (technically the .toString()
method is called on whatever you are trying to store to determine the string value to be stored). What you retrieve from sessionStorage
will ALWAYS be a string value, such that you would need to cast it back into an integer before trying to do integer math on it.
I would suggest modifying your code to be explicit about strings/integers. That might look like this:
var currentSize;
function confSize(){
var defaultSize = 20;
var sessionStorageStr = sessionStorage.getItem('sessionSize');
if (sessionStorageStr == ""){
currentSize = defaultSize;
}
else {
currentSize = parseInt(sessionStorageStr);
console.log(currentSize);
}
// no need to repeat this code in both sides of the conditional above
$("#body").css("font-size", currentSize + "px");
$("#button2").click(function(){
// I removed your conditional here, as it really did nothing
currentSize += 2;
sessionStorage.setItem('sessionSize', currentSize);
$("#body").css("font-size", currentSize + "px");
});
$("#button").click(function(){
currentSize -= 2;
sessionStorage.setItem('sessionSize', currentSize);
$("#body").css("font-size", currentSize + "px");
});
}