I'm trying to learn about "localstorage", and so far I've managed to apply it to a select. But I'm having trouble getting it to show the "div" with Content One or Contet Two after page load. Localstorage saves the selected option, but the "showDivOne" and "showDivTwo" functions do not work, only after clicking the same option again. Is there any way to make these two div's appear without having to click again on some option?
var init = function (){
//an ugly warning to users without localStorage support
if(!window.localStorage){
$('body').prepend('Sorry, you browser does not support local storage');
return false;
}
var sel = $('select'),
but = $('button');
var clearSelected = function(){
sel.find(':selected').prop('selected', false);
}
if(localStorage.getItem('pref')){
var pref = localStorage.getItem('pref');
clearSelected();
//set the selected state to true on the option localStorage remembers
sel.find('#' + pref).prop('selected', true);
}
var setPreference = function(){
//remember the ID of the option the user selected
localStorage.setItem('pref', sel.find(':selected').attr('id'));
};
var reset = function(){
clearSelected();
localStorage.setItem('pref', undefined);
}
sel.on('change', setPreference);
but.on('click', reset);
};
$(document).ready(init);
function showDivOne(divId, element){
document.getElementById(divId).style.display = element.value == 0 ? 'block' : 'none';
}
function showDivTwo(divId, element){
document.getElementById(divId).style.display = element.value == 1 ? 'block' : 'none';
}
select, button {
margin-top: .5em;
}
#one_div{
display: none;
}
#two_div {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select onchange="showDivOne('one_div', this); showDivTwo('two_div', this);">
<option selected>Select an option</option>
<option id="opt1" value="0">1</option>
<option id="opt2" value="1">2</option>
</select>
<button>Reset preference</button>
<div id="one_div">Content One</div>
<div id="two_div">Content Two</div>