When working with drag-and-drop and resizing in jQuery, remember that any changes made will be reflected in the inline styles, not in your external stylesheets or <style>
blocks.
You'll need to loop through the elements, but there's no need to loop through each property individually. Simply grab the style
attribute for each element. Make sure each element has an id
set so you can easily find it later when needed.
In this demo, a JSON object is created and saved to localStorage
.
Demo: http://jsfiddle.net/ThinkingStiff/VLXWs/
Here is the script:
function saveState() {
var elements = document.querySelectorAll( 'body *' ),
state = [];
for( var index = 0; index < elements.length; index++ ) {
if( elements[index].id && elements[index].style.length ) {
state.push( { id:elements[index].id, style: elements[index].style.cssText } );
};
};
window.localStorage.setItem( 'state', window.JSON.stringify( state ) );
};
function loadState() {
var state = window.localStorage.getItem( 'state' );
if( state ) {
var styles = window.JSON.parse( state );
for( var index = 0; index < styles.length; index++ ) {
document.getElementById( styles[index].id ).style.cssText = styles[index].style;
};
};
};
document.getElementById( 'one' ).addEventListener( 'click', function() {
this.style.color == 'green' ? this.style.color = 'black' : this.style.color = 'green';
});
document.getElementById( 'two' ).addEventListener( 'click', function() {
this.style.color == 'red' ? this.style.color = 'black' : this.style.color = 'red';
});
document.getElementById( 'three' ).addEventListener( 'click', function() {
this.style.color == 'blue' ? this.style.color = 'black' : this.style.color = 'blue';
});
document.getElementById( 'save' ).addEventListener( 'click', saveState );
loadState();
This is the HTML:
<div id="one">click to toggle</div>
<div id="two">click to toggle</div>
<div id="three">click to toggle</div>
<button id="save">save</button>
<div>toggle colors, save, reload page</div>