0

How do I make this code into a cookie to remember a user's selected text size?

function resizeText(multiplier) {
  if (document.body.style.fontSize == '') {
      document.body.style.fontSize = '1.0em';
  }
  document.body.style.fontSize = parseFloat(document.body.style.fontSize) + (multiplier * 0.2) + 'em';
}
$("plustext").addEvent("click", function() {resizeText(1);});
$("minustext").addEvent("click", function() {resizeText(-1);});

If you cannot tell by my question... I am a newbie to cookies and to JavaScript. By the way, I do not want to rewrite my whole code that I posted here as it works perfectly... I just want to add cookies to it.

Aurora0001
  • 13,139
  • 5
  • 50
  • 53
vampnerdlord
  • 129
  • 1
  • 3
  • 11
  • Look at this answer. https://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie – nixkuroi Aug 21 '17 at 19:40

1 Answers1

0

You need to use the Web Storage API. As this seems like a plugin you're building, I would wrap the Storage API methods and use a prefix to prevent interference with other scripts that may be running on the page (as I have done in the example below).

I've taken the liberty of expanding your example a bit to better demonstrate usage, and I've removed all of that jQuery nonsense.

Here's a demo showing it in action

const textResizePlugin = scope => {
    if(!(scope instanceof Node)) {
        throw new Error('Invalid scope supplied');
    }

    const style = scope.style;
    const prefix = 'textResizePlugin_';

    if(scope.classList.contains(`${prefix}active`)) {
        throw new Error('Already initialized');
    } else {
        scope.classList.add(`${prefix}active`);
    }

    const storage = {
        get: (key) => window.localStorage.getItem(prefix + key),
        set: (key, val) => window.localStorage.setItem(prefix + key, val)
    };

    const setSize = size => {
        storage.set('fontSize', size);
        style.fontSize = size;
    };

    setSize(storage.get('fontSize'));

    const resize = m => setSize(
        (style.fontSize||"1.0em").replace(/[\d.]+/, num => +num + m * 0.2)
    );

    const html = `
        <div id="${prefix}bar">
            <button id="${prefix}less">-</button>
            <button id="${prefix}more">+</button>
        </div>
        <style type="text/css">
            #${prefix}bar {
                background: rgba(200,200,200,0.3);
                position: fixed;
                font-size: 0px !important;
                top: 0;
                width: 100%;
                padding: 5px;
                text-align: right;
                box-sizing: border-box;
            }
        </style>
    `;

    scope.insertAdjacentHTML('afterbegin', html);
    const [less, more] = scope.querySelectorAll(`#${prefix}less, #${prefix}more`);

    less.addEventListener('click', () => resize(-1));
    more.addEventListener('click', () => resize(1));
};

textResizePlugin(document.body);