Day 15 of #javascript30 is about localStorage and event delegation.
LocalStorage
The Window.localStorage a simple key-value store that lives in the browser. It is pr. site and has a nice and simple interface. Keep in mind that both the key and the value should be a string, so often times the value is made into json if it is an object.
The methods on the Storage object can be found here, but I'll just list the most important ones:
That's it! Nice and simple way to talk to a key-value store. Oh, there is also Storage.clear()
for clearing the whole storehouse.
Event Delegation
Is basically putting an event listener on a parent element to avoid having to attach listeners when new items are added dynamically. When you want to have listeners on something that doesn't exist yet or maybe just instead of attaching 1000 listeners you can put the listener on the parent element. When the parent element is clicked for instance, you then look at the event to see if an item you want to listen for was the target.
function myEventHandler(e) {
if (!e.target.matches('input')) {
// Not what we are listening for, so return.
return;
}
// An input element was clicked. Do what needs to be done.
}
preventDefault() confusion
This has had me confused. There is an Event.preventDefault in vanilla JS and then jQuery has event.preventDefault() with the exact same name. Just something to keep in mind to avoid confusion.