I have a small project I run using Live Server on VSCode. In this project I enter an email and password into fields. When I press save I want to store the values into localStorage, and clear the localStorage when I press clear.
But it seems that the addEventListener() runs automatically.
How do I get it to where the functions only run when I press the Save and Clear buttons?
Javascript
var email = document.getElementById('email');
var password = document.getElementById('password');
function save(email, password){
try{
localStorage.setItem("email", JSON.stringify(email) )
localStorage.setItem("password", JSON.stringify(password) )
}
catch (err){
console.log(err)
}
console.log(localStorage.getItem("email"));
console.log(localStorage.getItem("password"));
}
function cancel(){
localStorage.clear()
console.log("Cancel Clicked")
}
document.getElementById("savebutton").addEventListener('click', save(email, password));
document.getElementById("cancelbutton").addEventListener('click',cancel());
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Local Storage App</title>
</head>
<body>
<div>
<h2>Local Storage Practice Example</h2>
<div id="inputs">
<div id="inputflex">
<label>Email</label>
<input type="email" id="email" />
</div>
<div id="inputflex">
<label>Password</label>
<input type="password" id="password" />
</div>
</div>
<div>
<button id="savebutton">Save</button>
<button id="cancelbutton">Clear</button>
</div>
</div>
<script src="/main.js"></script>
</body>
</html>
Image of project.
The bottom shows the logs. It runs each time I start the project or refresh. I want the code to run only when I click save or clear buttons.