Reputation: 28793
I'm using jQuery Storage to save and restore a user's set volume level for a music player. Whenever they drag the volume slider, I save the value...
this.setVolume = function(volume) {
...
$.Storage.set('volume', volume + '');
...
};
Then I use that value as the initial value for the slider the next time the page is loaded...
$("#volumeslider").slider({
...
value: volume,
...
});
The saving and restoring part works fine. The problem is, if you're a brand new user and haven't yet adjusted the volume slider, volume
doesn't have a value.
So I tried using a try
/catch
block to set the volume at 0.6
by default, unless there was a saved value to restore:
var volume = 0.6;
try {
volume = parseFloat($.Storage.get('volume'));
} catch (e) { }
But instead, volume
comes back as NaN
. Then I realized that there's no "error" to catch because NaN
is simply the result of parseFloat
on the empty value in storage.
So: how would I set a default value only for when there's nothing in storage?
Upvotes: 0
Views: 2087
Reputation: 28793
A cleaner solution than my original answer:
var volume = parseFloat($.Storage.get('volume'));
if (!volume) {
volume = 0.6;
$.Storage.set('volume', volume + '');
}
Use a stored value if it exists; if not, set a default value and store that instead.
Upvotes: 0
Reputation: 28793
Solved it using this question as a reference:
if (!isNaN(parseFloat($.Storage.get('volume')))){
var volume = parseFloat($.Storage.get('volume'));
} else {
var volume = 0.6;
}
Upvotes: 1
Reputation: 21911
Why are you storing the value as string to convert it back to a number?
Nevertheless
$("#volumeslider").slider({
value: parseFloat($.Storage.get("volume") || 0.6),
});
Upvotes: 3