0

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?

daGUY
  • 27,055
  • 29
  • 75
  • 119

3 Answers3

3

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),
});
Andreas
  • 21,535
  • 7
  • 47
  • 56
  • According to the documentation, "Names and values should be strings. Some browsers may accept non-string values, but not all do." – daGUY Jul 23 '12 at 18:43
  • @daGUY I must admit that I haven't read the documentation... Never mind me asking :) – Andreas Jul 23 '12 at 18:50
1

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;
}
Community
  • 1
  • 1
daGUY
  • 27,055
  • 29
  • 75
  • 119
0

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.

daGUY
  • 27,055
  • 29
  • 75
  • 119