Search code examples
jqueryhtmllocal-storagemustache

Counter app with local storage


I am working on a counter app that uses mustache.js to create multiple counters and remembers your data using local storage. You simply click the '+' button to add a new counter, and hit the add button to increase the counter.

I am having several issues: - When add, and have multiple counters, they all increase. - When I click the close button, the counters also increase.

Is it also possible to enter a title via the input field and have local storage remember it?

Any help would be greatly appreciated. If you have any solutions, can you explain?

See the fiddle here: http://jsfiddle.net/techydude/MSnuE/

Javascript:

   $(function() {
  var doc = $(document),
      CounterContainer = $("#CounterContainer"),
       //Container for all Counters
      container = $(".counter"),
       //Individual Conter Counters
      counter = $(".valueCount"),
      addBtn = $(".add"),
      valueCount = $(".valueCount").html(),
      addCounter = $("#create-counter"),
      counterTemplate = Mustache.compile($("#counter-template").html());

  if (localStorage.counterSave) {
    CounterContainer.html(localStorage.counterSave);
  }

  function save() {
    localStorage.counterSave = CounterContainer.html();
  }


  addCounter.submit(function(e) {

    // prevent page from refresing
    e.preventDefault();
    var value = 5;
    makeCounter(value);
    save();
  });

  function makeCounter(value) {
    $(counterTemplate({
      txt: value
    })).appendTo(CounterContainer);
  }



  CounterContainer.on("click", addBtn, function(valueCount) {
    var EachContainer = $("div.valueCount"),
        EachContainerValue = $("div.valueCount").html();

    EachContainer.html(++EachContainerValue);

    console.log("test");

    save();
  });

  doc.on("click", "button.removeCounter", function() {
    $(this).parent().remove();
    save();
  });

});​

Solution

  • Lets try to break this into sections. First of all you're incrementing the value of all counters because the selector used to get the counter you're after affects all counters, ergo the behaviour is the correct one. Let me explain:

    When you are doing this: var EachContainer = $("div.valueCount"), the object jQuery returns is all elements matching that selector so if there is more than one counter, all will be affected. To fix this you can use the this keyword to move up the DOM tree from the button you've clicked, and select the only sibling with that selector.

    $(".add").live("click",function(){
            var counter = $(this).siblings(".valueCount");
            counter.html(parseInt(counter.text())+1);
            save();
        });
    

    This approach solves the issue you were likely experiencing by using .click since that one only affects the elements created at that given time and not future ones. With this little change you now have the possibility of creating multiple counters and saving their values. But not the titles, yet

    The first part is to invoke the save method on every modification of the title, although this could be done on other events such as the onChange event, but since that could potentially lead to loosing a title on some circumstances and the title length should be relatively small, you should be fine with just doing:

    $(".title").live("keyup",function(){
       save(); 
    });
    

    The second part is fairly simple and comes from the inability of some browsers to change the DOM when we dynamically modify a form attribute, meaning although the value of your input changes, the DOM doesn't reflect it and therefor when you save the contents on the div containing all your counters, you are not saving the value attribute. To fix this, you end up with:

    $(".title").live("keyup",function(){
        $(this).attr('value',this.value);
        save(); 
    });
    

    Note that I'm not going to modify any of your other code or markup, and I've surrounded my code in a fork of your fiddle and placed it at the top of the Javascript section for easier location. Here's the working fiddle, with the ability of adding new counters, changing the values of those counters and their titles and of course the option of deleting them (which was already working).

    Enjoy!


    Sources: