Search code examples
javascripthtmlreturnlocal-storage

Alphabetizing Content List with LocalStorage


I'm working on an update to one of my apps which allows the user to add multiple new lists and alphabetize them.

I'm using LocalStorage to remember the newly created lists and alphabetized sections.

I couldn't get the content to save with a textarea so I went with a div[contenteditable] instead. Now the newly created "textbox's" that are dynamically added have a random character string used as the selector In which I'm grabbing it using data attributes.

Now when I reload the application the previously added values list are there but my alphabetize button does not alphabetize the list.

Does anyone know how to use LocalStorage in this way to save the values here?

Below is a minified version of the application for the sake of this post. I had to comment out localStorage on the snippet cause otherwise it wouldn't run here on Stack Overflow. I also added it on CodePen as well.

// Creates a random string
function randString() {
  var char = "0123456789abcdefghijklmnopqrstuvwxyz",
      fullchar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
      genHash  = "",
      i;

  for (i = 0; i < 8; i++) {
    var rnum = Math.floor(Math.random() * char.length)
    genHash += char.substring(rnum, rnum + 1)
  }
  return genHash
}

// localStorage Stuff
// Remember list-btns after Delete
// if ( localStorage.getItem("listTree")) {
//   $("[data-action=list-tree]").html(localStorage.getItem("listTree"))
// }
// // Remember alph-btns after Delete
// if ( localStorage.getItem("alphTree")) {
//   $("[data-action=alph-tree]").html(localStorage.getItem("alphTree"))
// }

// Remember lists
function RememberTrees() {
  // Remember list-btns after Delete
  // localStorage.clear()
  // localStorage.setItem("listTree", $("[data-action=list-tree]").html())
  // localStorage.setItem("alphTree", $("[data-action=alph-tree]").html())
}

// Grab currently selected list
var GrabActiveList = function() {
  $(".added-btn-list").on("click", function() {
    // Show/Hide Nav Buttons
    $(".newlist").addClass("hide")
    $(".backbtn").removeClass("hide")

    // Show active editor
    var callThis = $(this).attr("data-call")
    $("[data-call=" + callThis + "]").not("[data-action=" + callThis + "]").removeClass("hide")
    $("[data-action=" + callThis + "]").removeClass("hide")
    $("[data-value=" + callThis + "] *").removeClass("hide")

    // Hide previously added lists
    $(".added-btn-list").addClass("hide")

    // localStorage.clear()
    RememberTrees()

    // Alphabetize List
    $(".alphlist").on("click", function() {
      var selector = $(this).attr("data-action")

      $("[data-value=" + selector + "]").html($("[data-value=" + selector + "]").html().split("<div>").sort(caseInsensitive).join("<div>"))

      function caseInsensitive(a, b) {
        return a.toLowerCase().localeCompare(b.toLowerCase())
      }
      RememberTrees()
    })

    $("[data-value=" + callThis + "]").on("change keyup", function() {
      RememberTrees()
    })

    // Delete List
    $("[data-action=del" + callThis + "]").on("click", function() {
      $("[data-call=" + callThis + "]").remove()
      $(".backbtn").click()
      RememberTrees()
    })
  })
}

GrabActiveList()

// Delete All Lists
function deleteAllLists() {
  alertify.confirm("This action is irreversable.", "Are you sure you wish to clear all your added lists?", function() {
    $("[data-action=alph-tree]").html("")
    $("[data-action=list-tree]").html("")
    $(".backbtn").click()

    // localStorage.clear()
    RememberTrees()
  }, function() {
    // Operation aborted
  })
}

// Create and Manage Lists
$("[data-action=new-list]").on("click", function() {
  alertify.prompt("Title of your new list.", "",
                  function(evt, value) {
    // Random string
    var genHash = randString()

    // New textbox list
    var newTxtList = $("<div>", {
      class: "added-txt-list txtbox hide"
    }).attr("contenteditable", true).attr("data-call", genHash).attr("data-value", genHash).appendTo("[data-action=list-tree]").on("keyup change", function() {
      RememberTrees()
    })

    // New button list
    var newBtnList = $("<button>", {
      text: value,
      class: "added-btn-list"
    }).attr("data-call", genHash).attr("data-action", "btn"+ genHash).appendTo("[data-action=list-tree]")

    // New alphabet list
    var alphList = $("<button>", {
      text: "Alphabetize",
      class: "alphlist hide"
    }).attr("data-call", genHash).attr("data-action", genHash).appendTo("[data-action=alph-tree]")

    // New delete list
    var delList = $("<button>", {
      text: "Delete This",
      class: "added-del-btn hide"
    }).attr("data-call", genHash).attr("data-action", "del"+ genHash).appendTo("[data-action=list-tree]")

    // New delete all button
    var delAll = $("<button>", {
      text: "Delete All",
      class: "added-delall-btn hide"
    }).attr("data-call", genHash).attr("data-action", "delall").appendTo("[data-action=list-tree]").on("click", function() {
      deleteAllLists()
    })

    GrabActiveList()
  }, function() {
    // User clicked cancel
  }).set("basic", true)
  return false
})

// Handles Back Button
$(".backbtn").click(function() {
  $(".newlist").removeClass("hide")
  $(".backbtn, .alphlist").addClass("hide")
  $(".added-btn-list").removeClass("hide")
  $(".added-txt-list").addClass("hide")
  $(".added-del-btn").addClass("hide")
  $(".added-delall-btn").addClass("hide")

  // Remember list-btns after Delete
  RememberTrees()
})

// Remember when all lists are deleted
$("[data-action=delall]").on("click", function() {
  deleteAllLists()
})

// Hide all appended data except the newly added btn-lists
$(".alph-tree *").addClass("hide")
$(".list-tree *").addClass("hide")
$(".added-btn-list").removeClass("hide")
.hide {
  display: none;
}

[contenteditable], .txtbox {
  margin: 20px 0;
  border-radius: 5.6px;
  padding: 15px;
  background: #fff;
  border: 0;
  outline: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://alertifyjs.com/build/alertify.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="http://alertifyjs.com/build/css/themes/default.css" rel="stylesheet"/>
<link href="http://alertifyjs.com/build/css/alertify.css" rel="stylesheet"/>

<div class="grid">
  <div class="grid__col--12">
    <h2 class="backbtn hide" data-action="go-back">
      <i class="fa fa-chevron-left"></i>
    </h2>
    <button class="newlist" data-action="new-list">New List</button>
    <span class="alph-tree" data-action="alph-tree"></span>
    <div class="list-tree" data-action="list-tree"></div>
  </div>
</div>


Solution

  • LocalStorage works fine:

    LocalStorage

    I tested your codepen project, the alphabetize button does not work in both cases: immediately after creation and after reload. So I believe you have a logical issue here which has nothing to do with LocalStorage.

    HTML

    What should alphabetize do? The corresponding div's are always empty.