localStorage() and Target

Page section: playground

This is based on a vid by iEatWebsite on Youtube

What it does

This does two things. Firstly the input field adds to the paragraph below on every keystroke.

Secondly the save button saves the content of that paragraph to localStorage

Save something to localStorage

How it works

First variables are created for the input, the paragraph, and the button.

const input = document.querySelector('.inputField');
const output = document.querySelector('.output');
const saveBtn = document.getElementById('save');

Next an event listener is added to the <input> element listening for input.

input.addEventListener('input', e => {
    output.innerHTML = e.target.value;
})

e.target.value

Using an arrow function, firstly a new parameter I’ve named e is created for the event.

The target of the event is the element where the event originated, which in this case is the <input> element.

What we want is not the element itself but it’s value so e.target.value means the event’s element value.

This e.target.value can then be used anywhere, in the case the textContent of the paragraph with a class of output.

const input = document.querySelector('.inputField');
const output = document.querySelector('.output');
const saveBtn = document.getElementById('save');

input.addEventListener('input', e => output.innerHTML = e.target.value);

The arrow function here has had the curly braces removed which are unnecessary with a only single parameter e.

Saving to localStorage

To do this we first create a simple function:

const saveToLocalStorage = () => {
    localStorage.setItem('inputText', output.textContent )
};

The setItem() method takes two parameters. The first is the key and the second is what we want to store. The key, inputText is being declared for the first time here and could be any name we want at this point.

The output.textContent is the content of the paragraph we named output above and textContent is what is inside it.

All we need now is a click event on the button to fire this function.

saveBtn.addEventListener('click', saveToLocalStorage);

Retrieving our variable from localStorage

The key we saved our string under is called inputText. To get this we use:

localStorage.getItem('inputText');

The current localStorage value for inputText is:

Table of Contents