Trying to accomplish:
The website is an online Bible; I'd like to allow users to do the following....
Allow user to highlight (add yellow background to text) a verse by clicking on it. They can toggle the highlight on and off by clicking on it.
Save the verse to local storage, so that when they come back to the page at a later time, the verses will remain highlighted.
Relevant code
Twig is the template engine I'm using. Each bible verse is generated with the following:
<span id="{{ result.verse }}" onclick="javascript:saveVerse('{{ result.verse }}'); highlighter('{{ result.verse }}')">
<sup class="verse">{{ result.verse }}</sup>
<span>{{ result.text }}</span>
</span>
Here is an example of the generated HTML
<span id="1" onclick="javascript:saveVerse('1'); highlighter('1')" class="">
<sup class="verse">1</sup>
<span id="verseText-1"> And the ark of the LORD was in the country of the Philistines seven months.</span>
</span>
What I've tried
#1 was simple enough. I have that working properly. When user clicks on the verse, it sends the <span>
id to the highlighter()
function, which just uses toggleClass()
to add/remove some css. That issue is resolved.
#2 is where I'm stuck. The code I currently have is below:
function saveVerse( verse )
{
// Save to local storage
let data = JSON.parse( localStorage.getItem("savedVerses") );
var saveVerse = [{
book: "{{ book }}",
chapter: {{ chapter }},
verse: verse
}];
$(data).push({saveVerse});
localStorage.setItem("savedVerses", JSON.stringify( data ));
}
What I would like to do is store the data to local storage with the key name "savedVerses", and that key should keep track of the books, chapters and corresponding verses. For example, the :
savedVerses[0]:
"book": 'Genesis',
"chapter": 6,
"verse": 21
savedVerses[1]:
"book": 'Matthew',
"chapter": 2,
"verse": 14
savedVerses[2]:
"book": 'Exodus',
"chapter": 8,
"verse": 10
and so on...
What actually happens is that when I look in the dev console, all I see is this:
{"book":"1 Samuel","chapter":6,"verse":"3"}
It appears to be saving the first verse clicked, but does not append any addition data to it.
Can anyone tell where I'm going wrong? Thank you in advance!
$(data)
👈 why are you wrapping this in a jQuery object?data
is not an array. Doesn't mean "wrap it in jQuery".localStorage
. You'll want to clear that before trying my answer below