|
| 1 | + |
| 2 | +if (!localStorage.getItem('counter')){ |
| 3 | + localStorage.setItem('counter',0); |
| 4 | +} |
| 5 | +// now we will use localstorage instead of variable let counter = 0; |
| 6 | +function count() { |
| 7 | +counter = localStorage.getItem('counter'); |
| 8 | +counter++; |
| 9 | +document.querySelector('h1').innerHTML = counter; |
| 10 | +localStorage.setItem('counter',counter); //save the lst value of counter |
| 11 | +//if (counter % 10 === 0) |
| 12 | +//{ |
| 13 | + // alert ( f{"count is now {counter}" ) this is how we would do this in python |
| 14 | + // alert(`Count is now ${counter}`) //template literal, ${ } means plug in a variable here |
| 15 | +//} |
| 16 | +} |
| 17 | + |
| 18 | +// document.querySelector('button').onclick = count; |
| 19 | +// I am not actually calling the function if i call it i would do count(), but I am setting litterally equal to the function itself |
| 20 | + |
| 21 | +// It is not going to work bcs js code looking for button but body of the page hasnt finished loading yet. |
| 22 | +//I can add an event listener to the document itself |
| 23 | + |
| 24 | +document.addEventListener('DOMContentLoaded',function(){ |
| 25 | + //so now when refresh the page, it'll go back to value that remembered not 0, bcs h1 was 0 in html code. |
| 26 | +document.querySelector('h1').innerHTML =localStorage.getItem('counter'); |
| 27 | +document.querySelector('button').onclick = count; |
| 28 | + |
| 29 | +// run this function every 1000 miliseconds |
| 30 | +//setInterval(count,1000); |
| 31 | +}); |
| 32 | +/* It says, wait until the all the content in the page is loaded, then run this function, so now we will able to find the button |
| 33 | +So now I am able to seperate all of my js code from the html, you can move js to seperate file |
| 34 | +To do this: in the head <script src='counter.js'></cript> */ |
| 35 | + |
| 36 | +/* Now our code doesnt store any information. There is a way to remembering information for later use, Now js allows us to do smth called |
| 37 | +local storage. Its a way for us to store info inside of the users web browser |
| 38 | +
|
| 39 | +Local storage is gonna give access to two key functions that we will use to manipulate this local storage: |
| 40 | +1) localstorage.getItem(key) |
| 41 | +2) localstorage.setItem(key,value) |
| 42 | +*/ |
0 commit comments