PHPirate
PHPirate

Reputation: 7572

local-storage, the simple way

I have a working code which changes the text of a button and panel if you click button 1, two or three. See this codepen: http://codepen.io/anon/pen/GgKOba

I now want to use local-storage, in this way: when you first visit the page, the default text is displayed. When you have clicked button X, the button and panel text changes. The id is stored in local-storage. When you reload the page, it sees there's something in the local-storage and uses that to change the button and panel text.

I tried it this way: http://codepen.io/anon/pen/JoPOQv

That codepen contains this html:

<div data-role="panel" id="panel"> 
    <h2>Panel Header</h2>
    <p>default text</p>
</div> <!-- /panel -->

<div class="container">
  <a href="#panel" class="ui-btn ui-btn-inline ui-corner-all ui-shadow" id="panel_button"> <p>default text</p></a>
</div>

<div class="container">
  <a href="#tt_popup" data-role="button" data-rel="popup" class="ui-btn ui-btn-inline ui-corner-all btn" id="btn1" data-transition="flip">Button 1</a>

And this javascript:

// if we have something on local storage 
if(localStorage.getItem('id')) {
$("#panel p").html("This is info about stop <b>" + this.id + "</b>."); //then set this html text to the panel p
      $("#panel_button p").html("Info about stop " + this.id + "."); // and change the button text
}

$(document).on("ready", function () {
    $(".btn").on("click", function () { //if a button with class btn is clicked

      $("#panel p").html("This is info about stop <b>" + this.id + "</b>."); //then set this html text to the panel p
      $("#panel_button p").html("Info about stop " + this.id + "."); // and change the button text
      localStorage.setItem('id', this.id);        //also add the last-clicked id to the local-storage

    });

});

As you can see I used an if-statement I found on google somewhere to check if the local-storage is empty, and if it is not execute some rules.

But as you also can see it doesn't display the default text, neither does it read the local-storage correctly. What do I do wrong?

Upvotes: 0

Views: 176

Answers (1)

balzafin
balzafin

Reputation: 1426

You are referring to wrong id. this.id is not the id you get from the localStorage. Fixed it for you:

// if we have something on local storage
var id = localStorage.getItem('id');
if(id) {
    $("#panel p").html("This is info about stop <b>" + id + "</b>."); //then set this html text to the panel p
    $("#panel_button p").html("Info about stop " + id + "."); // and change the button text
}

Upvotes: 0

Related Questions