Search code examples
javascriptjsonlocal-storagestringify

storing button click in local storage


I'm trying to store button clicks in local storage, so when user clicks the button, the date and time the user clicks it will be stored in local storage. However at the moment the data gets overwritten by new dates when I close the window, opens again and click the button the second time. What I want is for the local storage to store every single button click without overwriting past data. I heard JSON stringify should do the job but its not working.

    function saveData(){
        var date= new Date();
        window.localStorage.setItem("date", JSON.stringify(date));  
        alert("Your data is stored");
    }

Solution

  • You probably want to use an array for that

    function saveData(){
        var data  = localStorage.getItem("date");
    
        var dates = data ? JSON.parse(data) : [];
    
        dates.push( Date.now() );
    
        localStorage.setItem("date", JSON.stringify(dates));  
    
        alert("Your data is stored");
    }