Saving changes using Localstorage for currency switcher

Hey,

I have a just added a currency changer to my website, it does work great but I want to add localStorage code to keep changes even when the page ios refreshed, this is the code and also can be seen on my website Morocco Excursions .

(function() { console.clear(); var rates = { 'USD': { 'val': 1.4020951, 'sign': '',
‘name’: ‘US Dollar’
},
‘EUR’: {
‘val’: 1,
‘sign’: ‘€’,
‘name’: ‘Euro’
},
‘MAD’: {
‘val’: 11,
‘sign’: ‘MAD’,
‘name’: ‘Moroccan Dirham’
},
‘CAD’: {
‘val’: 1.6792888,
‘sign’: ‘C$’,
‘name’: ‘Canadian Dollar’
},
‘AUD’: {
‘val’: 1.7581669,
‘sign’: ‘A$’,
‘name’: ‘Australian Dollar’
},
‘GBP’: {
‘val’: 0.96995442,
‘sign’: ‘£’,
‘name’: ‘British Pound’
},
‘BRL’: {
‘val’: 6.5354011,
‘sign’: ‘R$’,
‘name’: ‘Brazilian Real’
},
};
// Create the List of Available Rates
var list = ‘’
var i = 0;
$.each(rates, function(key, value) {

    list += `

`;
i++;
});
// Inject The Rates into their Container Using Data Attributes
('[data-currency-list]').html(list); // Add Event Handler For To change the currency for available rates on click var rateKey; (’[data-currency]’).on(‘click’, function(e) {
e.preventDefault();

    var currentRate = $(this).attr('data-currency');

    if (currentRate == rateKey) {
        return;
    }
    rateKey = currentRate;
    var rateInfo = rates[currentRate];

    $('[data-price]').each(function() {
        var $el = $(this);
        var price = $el.attr('data-price');
        var newVal = price * rateInfo.val;
        /*  Display two decimal places, no rounding
         *  http://stackoverflow.com/questions/4187146/display-two-decimal-places-no-rounding
         */
        var roundedVal = newVal.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
        var el = $el[0];
        // console.log(el);
        el.childNodes[0].nodeValue = roundedVal + ' ' + rateInfo.sign;

    })
    var event = $.Event('currency-change');
    event.rate = rateInfo;
    $(document).trigger(event);

})
var to, to2, to3;
$(document).on('currency-change', function(e) {
    var rate = e.rate;
    var heading = $('<h1 id="heading"></h1>');
    var message = '<span>the currency was changed to : ' + rate.name + '</span><a href="#close" id="close-heading">close</a>';

    heading.html($(message));
    if (!$('#heading').length > 0) {
        $('.price-list').before($(heading));
    }


    if (to) {
        clearTimeout(to);
    }
    if (to2) {
        clearTimeout(to2);
    }
    if (to3) {
        clearTimeout(to3);
    }
    if ($('#heading').hasClass('fade-in')) {
        console.log('IF');
        $('#heading').removeClass('fade-in');
        to = setTimeout(function() {
            $('#heading')
                .html(message)
                .addClass('fade-in');
            console.log('first');
            to2 = setTimeout(function() {
                $('#heading').removeClass('fade-in');
                console.log('second');
            }, 2000)
        }, 300);

    } else {
        console.log('ELSE');
        $('#heading')
            .html(message)
            .addClass('fade-in');
        console.log('first');
        to2 = setTimeout(function() {
            $('#heading').removeClass('fade-in');
            console.log('second');
        }, 2000)

    }
    //  console.log(e.rate);
})
$(document).on('click', '#close-heading', function(e) {
    e.preventDefault();
    $('#heading').removeClass('fade-in');
    if (to) {
        clearTimeout(to);
    }
    if (to2) {
        clearTimeout(to2);
    }
})

})

var x, i, j, l, ll, selElmnt, a, b, c;
/look for any elements with the class “custom-select”:/
x = document.getElementsByClassName(“custom-select”);
l = x.length;
for (i = 0; i < l; i++) {
selElmnt = x[i].getElementsByTagName(“select”)[0];
ll = selElmnt.length;
/for each element, create a new DIV that will act as the selected item:/
a = document.createElement(“DIV”);
a.setAttribute(“class”, “select-selected”);
a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
x[i].appendChild(a);
/for each element, create a new DIV that will contain the option list:/
b = document.createElement(“DIV”);
b.setAttribute(“class”, “select-items select-hide”);
for (j = 1; j < ll; j++) {
/for each option in the original select element,
create a new DIV that will act as an option item:
/
c = document.createElement(“DIV”);
c.innerHTML = selElmnt.options[j].innerHTML;
c.addEventListener(“click”, function(e) {
/when an item is clicked, update the original select box,
and the selected item:
/
var y, i, k, s, h, sl, yl;
s = this.parentNode.parentNode.getElementsByTagName(“select”)[0];
sl = s.length;
h = this.parentNode.previousSibling;
for (i = 0; i < sl; i++) {
if (s.options[i].innerHTML == this.innerHTML) {
s.selectedIndex = i;
h.innerHTML = this.innerHTML;
y = this.parentNode.getElementsByClassName(“same-as-selected”);
yl = y.length;
for (k = 0; k < yl; k++) {
y[k].removeAttribute(“class”);
}
this.setAttribute(“class”, “same-as-selected”);
break;
}
}
h.click();
});
b.appendChild(c);
}
x[i].appendChild(b);
a.addEventListener(“click”, function(e) {
/when the select box is clicked, close any other select boxes,
and open/close the current select box:
/
e.stopPropagation();
closeAllSelect(this);
this.nextSibling.classList.toggle(“select-hide”);
this.classList.toggle(“select-arrow-active”);
});
}

function closeAllSelect(elmnt) {
/a function that will close all select boxes in the document,
except the current select box:
/
var x, y, i, xl, yl, arrNo = ;
x = document.getElementsByClassName(“select-items”);
y = document.getElementsByClassName(“select-selected”);
xl = x.length;
yl = y.length;
for (i = 0; i < yl; i++) {
if (elmnt == y[i]) {
arrNo.push(i)
} else {
y[i].classList.remove(“select-arrow-active”);
}
}
for (i = 0; i < xl; i++) {
if (arrNo.indexOf(i)) {
x[i].classList.add(“select-hide”);
}
}
}
/if the user clicks anywhere outside the select box,
then close all select boxes:
/
document.addEventListener(“click”, closeAllSelect);

Hey there hassanmouhou85201943,
can you make it more clear what you need help on? :slight_smile:

Hi,

Thank you for your reply. I added a currency switcher to my website, you can change to different currencies but once I refresh the webpage I have to select the currency again, it doesn’t get saved.
I want to use localStorage but i new to JS and don’t know how

Hi @hassanmouhou85201943
Nice site! But I didn’t see the calculator on the linked page. On which page is it?
Have you had a look at this: Window.localStorage already?
Or the session storage in case you want to dismiss the data after the browser is closed.
I haven’t used that yet, but it seems to be quite simple. In case you need help with integrating that in your code, you should format your code in this post for better readability:
How to format code

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.