I’m trying to implement localStorage into one of my projects, but I’m having a problem because this portion of the code breaks my jQuery ui-layout.
function $(id) {
return document.getElementById(id);
}
In order to make the layout work, I have to add a $:
$(document).ready(function($) {
Being that I don’t know how to write javascript or jquery, I can only implement it, can the code below be written in a way that I can avoid using the “function $(id)” part and the “$”?
Here is the code in its entirety:
// return value - this the prob?
function $(id) {
return document.getElementById(id);
}
// write data to the local storage
function writeLocal() {
var key = $('lsKey').value;
var data = $('html').value;
localStorage.setItem(key, data);
updateItemsList();
}
// remove the item from localStorage
function deleteLocal(keyName) {
localStorage.removeItem(keyName);
updateItemsList();
}
// read the actual data for the key from localStorage
function readLocal(keyName) {
$('lsKey').value = keyName;
$('html').value = localStorage.getItem(keyName);
}
// allow retrieval of localStorage items
function updateItemsList() {
var items = localStorage.length;
var s = '<p>Saved Items</p>';
s+= '<ul>';
for (var i=0; i<items; i++) {
var keyName = localStorage.key(i);
s+= '<li class="lsdLI">' +
'<div style="float:right;">' +
'<input onClick="readLocal(\''+keyName+'\');"/>'+
'<input onClick="deleteLocal(\''+keyName+'\');"/>'+
'</div>'+
'<b>'+keyName+'</b>' +
'</li>';
}
$('lsValues').innerHTML = s + '</ul>';
}
// start by loading up whatever is persistant in localStorage
function load() {
updateItemsList();
}
window.onload = load;
So it sounds like you are using jquery UI and it’s causing a conflict. Easiest thing to do might just be renaming the $ convenience function you are using…
It wouldn’t be hard to convert what you have into jQuery either, but simply grabbing the first item out of each jQuery object.
Beyond those two options, you’d be looking at changing your code a bit more to truly do things the jQuery way. Instead of $(‘lsKey’).value it would be $(‘lsKey’).val(), etc. You’d have to update your code to use all the jQuery methods.