Reputation:
I have a html page and simple jquery codes. I want to add "read/unread" text near a post. When I click unread text it becomes read and click again read text it becomes unread. I want to save my jquery changes. I can change read/unread text but I cant save changes with using localStorage. When I refresh page everytime text becomes "unread". My codes need some restore. These are my codes.Not:I use jinja2 no database no server just local. thanks for time.
<html>
<head>
<title>{{ title }}</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<script>
$(function() {
$('h4').on('click', function(event) {
var $this = $(this);
$(this).text(localStorage.getItem('read'));
if ($this.text()==="unread"){
localStorage.setItem('read', 'read');
}
else if ($this.text()==="read"){
localStorage.setItem('read', 'unread');
}
});
});
</script>
{% for data in collecteddata %}
<div align="center" class="box">{{ data }}</div><h4>unread</h4>
{% endfor %}
</body>
</html>
Upvotes: 1
Views: 544
Reputation: 388446
you need to use setItem() - to set value and getItem() - to read value
$(function() {
var $h4 = $('h4').on('click', function(event) {
var $this = $(this), text = $.trim($this.text());
if (text === "unread"){
localStorage.setItem('read', 'read');
} else if (text === "read"){
localStorage.setItem('read', 'unread');
}
$(this).text(localStorage.getItem('read'));
});
var text = localStorage.getItem('read');
if(text){
$h4.text(text);
}
});
Demo: Fiddle
Upvotes: 0
Reputation: 3491
Local storage work as key:value pair. Here are the basics:- e.g.;
localStorage.setItem("key", "value"); // to store value in, by unique key
var value = localStorage.getItem("key"); // retreive value by key name
Upvotes: 0
Reputation: 40639
Use setItem() like
$(this).text(localStorage.getItem('read'));
if ($this.text()==="unread"){
localStorage.setItem('read','read');
}
else if ($this.text()==="read"){
localStorage.setItem('read','unread');
}
Upvotes: 1