I am a beginner in Javascript. I am building a webpage which has 4 elements, an input field, a saving button and a delete button, and a list. When a users types in the input field and hit the saving button, what he just put in will be displayed in the list. Every time he refreshes the page, past inputs will still be available in the list. I am having trouble with this particular line of code:
rendering_list(JSON.parse(localStorage.getItem("Note")))
Namely, when I put this function call at the end of the document, the page works just fine. However, when I put it where it is in the codes below, the whole page does not work. Could you tell me what the problem is here? Thank you
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="leadChromeExtension.css">
</head>
<body>
<input type="text">
<div>
<button id="lead_saving">Save lead</button>
<button id="lead_deleting">Delete lead</button>
</div>
<ul></ul>
<script src="leadChromeExtension.js"></script>
</body>
</html>
CSS
*{
margin: 0;
box-sizing: border-box;
}
body{
min-height: 100vh;
padding-top: 10px;
padding-left: 10px;
}
input{
width: 300px;
margin-bottom: 10px;
}
Javascript
let lead_list=[]
let input_field = document.querySelector("input")
let saving = document.getElementById("lead_saving")
let deleting = document.getElementById("lead_deleting")
let ul_el = document.querySelector("ul")
rendering_list(JSON.parse(localStorage.getItem("Note")))
function clearing_Storage(){
localStorage.clear()
}
deleting.addEventListener("click",clearing_Storage)
function rendering_list(list){
let HTML_text = ""
for (i=0; i < list.length; i=i+1){
HTML_text = HTML_text +
`<li>
<a href = ${list[i]}> ${list[i]}</a>
</li>`
ul_el.innerHTML = HTML_text
}
}
saving.addEventListener("click",function(){
HTML_text = ""
lead_list.push(input_field.value)
input_field.value=""
localStorage.setItem("Note",JSON.stringify(lead_list))
rendering_list(lead_list)
})
type here
I have tried moving the problematic code line around. It works, except for I would like to know the underlying issue here.