Skip to content

Instantly share code, notes, and snippets.

@MariaSzubski
Created October 2, 2017 04:26
Show Gist options
  • Select an option

  • Save MariaSzubski/59d14242ba7a24cffc601315f68b7c8c to your computer and use it in GitHub Desktop.

Select an option

Save MariaSzubski/59d14242ba7a24cffc601315f68b7c8c to your computer and use it in GitHub Desktop.
Use <button> to convert between pixel and rem units. Setting applies site-wide.
/*
Requires html button with at least two unit options.
Unit setting is saved in local storage.
*/
// PX to REM Conversion
if (Modernizr.localstorage) {
// ----------------- On initial load: check local storange and convert units
toggle_pxrem();
// ----------------- On button press: update localStorage, change button state, and convert units
(function pxrem(){
$('button').click(function(e){
$('button').toggleClass('btn-selected');
$('#size-px').hasClass('btn-selected') ?
localStorage.setItem('pxrem', 'px')
: localStorage.setItem('pxrem', 'rem');
convert();
});
})();
// ----------------- Check localStorage and convert units
function toggle_pxrem(){
(localStorage.pxrem == undefined) ? localStorage.setItem('pxrem', 'px') : null;
(localStorage.pxrem == 'rem') ?
($('#size-px').removeClass('btn-selected'),
$('#size-rem').addClass('btn-selected'))
: null;
(localStorage.pxrem == 'px') ?
($('#size-rem').removeClass('btn-selected'),
$('#size-px').addClass('btn-selected'))
: null;
convert();
}
// ----------------- Convert units
function convert(){
// rem -> px
if (localStorage.pxrem == 'px'){
$('.pxrem').each(function(){
let px = $(this).html();
if (px.includes('rem')) {
let px_arr = px.match(/[^rem]+|rem/g);
px_arr[0] = px_arr[0] * 16;
px_arr[1] = 'px';
$(this).html(px_arr.join(''));
};
});
}
// px -> rem
else if (localStorage.pxrem == 'rem'){
$('.pxrem').each(function(){
let rem = $(this).html();
let rem_arr = rem.match(/[^px]+|px/g);
rem_arr[0] = rem_arr[0] / 16;
rem_arr[1] = 'rem';
$(this).html(rem_arr.join(''));
});
};
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment