@@ -26,9 +26,55 @@ <h2>LOCAL TAPAS</h2>
2626 </ div >
2727
2828< script >
29+ const itemInput = document . querySelector ( '[name="item"]' ) ;
2930 const addItems = document . querySelector ( '.add-items' ) ;
3031 const itemsList = document . querySelector ( '.plates' ) ;
3132 const items = [ ] ;
33+ const storage = localStorage ;
34+ restoreOptions ( ) ;
35+
36+ function restoreOptions ( ) {
37+ const storageItems = ( storage . items ) ? JSON . parse ( storage . items ) : [ ] ;
38+ items . push ( ...storageItems ) ;
39+ renderList ( ) ;
40+ }
41+
42+ function renderList ( ) {
43+ itemsList . innerHTML = items . map ( ( item , i ) => {
44+ const checked = ( item . done ) ? "checked" : "" ;
45+ return `
46+ <li>
47+ <input type="checkbox" data-index="${ i } " id="item${ i } " ${ checked } >
48+ <label for="item${ i } ">${ item . text } </label>
49+ </li>
50+ ` ;
51+ } ) . join ( "" ) ;
52+ }
53+
54+ function addItemHandler ( e ) {
55+ e . preventDefault ( ) ;
56+ const itemText = itemInput . value ;
57+ items . push ( {
58+ text : itemText ,
59+ done : false
60+ } ) ;
61+ storage . setItem ( 'items' , JSON . stringify ( items ) ) ;
62+ renderList ( ) ;
63+ itemInput . value = "" ;
64+ }
65+
66+ function changeStateHandler ( e ) {
67+ if ( e . target . tagName . toLowerCase ( ) === 'input' ) {
68+ const theItemIndex = e . target . dataset . index ;
69+ console . log ( theItemIndex ) ;
70+ const state = ! items [ theItemIndex ] . done ;
71+ items [ theItemIndex ] . done = state ;
72+ storage . setItem ( 'items' , JSON . stringify ( items ) ) ;
73+ }
74+ }
75+
76+ addItems . addEventListener ( 'submit' , addItemHandler ) ;
77+ itemsList . addEventListener ( 'click' , changeStateHandler ) ;
3278
3379</ script >
3480
0 commit comments