What is the best method for capturing the current CSS settings?

For my web project, I am implementing jQuery drag and drop features as well as resizing elements. However, it's frustrating because every time I close the browser or refresh the page, all my progress is lost. To avoid this issue, I want to save the entire environment and reload it rather than keeping track of individual changes.

I am attempting to use jQuery to store the complete CSS environment in a JavaScript variable without having to manually loop through each element and property.

My initial thought was to simplify the process with code like:

var cssEnvironment = document.css();

Then, when the window is closed or reopened, I could reverse the action using:

document.css() = cssEnvironment;

This way, everything would be restored automatically. Is there a method to achieve similar functionality?

Answer №1

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manipulating the content of a specific row's table cells with a text box in jQuery Datatables

I am working with a jQuery datatable that consists of only one column. Every time a row is selected, a panel opens with a text box that automatically populates with the name of the selected td. I am trying to figure out how to edit the name of the selected ...

What is the best way to utilize a JavaScript for loop to translate ASCII code into a word?

I am attempting to solve this code in order to determine the name associated with the array below: let numbers=[42,67,74,62,6A,1F,58,64,60,66,64,71]; for(let i=0;i<numbers.length;i++) { numbers[i] = numbers[i]+1; } Any guesses on what the resultin ...

What is the best way to dynamically update styleUrls or style properties in Angular?

One of my goals is to give users the ability to customize colors and certain styles within my Angular application. I am thinking about creating a structure like this: Structure: component-one   folder-with-css-files     style-for-component-1-fo ...

Creating watercolor effects using JavaScript

Coffee has been the only thing on my mind lately. I've been contemplating how to replicate the essence of coffee in JavaScript. Imagine being able to fill a shape on the screen as if it were infused with the rich aroma of coffee. Is there a JavaScript ...

Image breaks out of container on mobile devices using Bootstrap 4

When I view my website on different phones, the image in my div jumps down and out of its container. It seems to be okay on some devices, but not on the Samsung Galaxy Note 9 for example. Despite trying various solutions to prevent this issue, such as usin ...

Alter data in MongoDB based on specific circumstances

Currently, I am utilizing node.js and mongoose for a project. The task at hand involves updating database information only if the required field either does not exist in the database or its value is less than 'x'. Specifically, this pertains to ...

Python string manipulation to create a list from text

I've got a bunch of JSON objects that are all smashed together in a single string. jsonString = "[{'key1':'value1','key2':'value2'}, {'key1':'value1','key2':'value2',&ap ...

Increasing the padding at the top of the logo when scrolling down the page

When scrolling down the page, there seems to be extra padding above the logo that is throwing off the alignment with the rest of the site. I've been trying different solutions to correct this issue: //$('.navbar-brand').css({ 'padding- ...

Performing operations on an array: What method do you favor and why? Is there a more efficient approach?

What is the most effective method for checking if an element exists in an array? Are there alternative ways to perform a boolean check? type ObjType = { name: string } let privileges: ObjType[] = [{ name: "ROLE_USER" }, { name: "ROLE_ ...

Exhibition of Expertise: NodeJS and Express Module Bypasses SQLite3 Database Inquiry

Currently, I am trying to establish a connection between a function in a separate JS file and my index file. However, during the execution of the function, it seems to skip over a certain part of the code, going back to the app.post method in the index.js ...

ZK: maintaining session connectivity

When I need to redirect to a tel:**** link in ZK and then redirect the user to another page after the call, I encounter a problem. Every time I click on the link, ZK interprets it as leaving the browser, which results in my client session ending automatica ...

Floating dropdown within a scrolling box

How can I ensure that the absolute positioned dropdown remains on top of the scrollable container and moves along with its relative parent when scrolling? Currently, the dropdown is displayed within the scrollable area. The desired layout is illustrated i ...

Fixing the Timeout Error in Node.js & Mongoose: A Step-by-Step Guide

After developing an API, I encountered the following issue: const express = require("express"); const router = express.Router(); const {getAttendanceSheet,getDailyAttendance} = require("../../services/attendanceService"); router.get(& ...

Issue with CSS Transform Causing Rendering Errors in Both Chrome and Firefox

While a pixel here or there can be overlooked, in this case, precision is essential for the perfect rendering of this simple menu. The spacing between menu items must be impeccably equal to avoid any merging or disjointed appearance. Currently, the sep ...

Explore the capabilities of Vue.js by creating multiple JavaScript classes within your application

<div class="container" :class="{ qwerty: !open }" :class="lower? 'left' : 'right'"> Hey there, I've noticed that Vue seems to only allow me to add one class with conditions, as shown in the exam ...

The border layout in ExtJS 4.2 is causing errors when running the layout

I am encountering an issue with an html page where I am trying to render a panel with layout set to 'border'. The panel is rendered to a div using the renderBody config. However, when I run the page, I am receiving an error message stating ' ...

The pop-up dialog on Facebook is limited to the width of the like button, cutting off any excess information

Feel free to check out my blog here. When attempting to click the "LIKE" button, the pop-up appears at the correct height, but the width is limited to the size of the button. Below is the CSS code I am using: .blog_social_media { float: right; b ...

Want to analyze the response time of jQuery AJAX and initiate specific actions based on the results

$.ajax({ url: "http://ajaxhttpheaders.appspot.com", dataType: 'jsonp', success: function(headers) { language = headers['Accept-Language']; alert(language); }, //it& ...

What is causing the error message "Uncaught TypeError: Cannot read property 'helpers' of undefined" to occur in my straight-forward Meteor application?

As I follow along with the tutorial here, I encounter an issue after replacing the default markup/code with the provided HTML and JavaScript. The error message "Uncaught TypeError: Cannot read property 'helpers' of undefined" appears. Below is t ...

Converting the PHP encoded Postgresql query result into a stringified array

I have a SQL query that transforms the result into JSON format. SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features FROM ( SELECT 'Feature' As type, ST_AsGeoJSON(geom)::json As geometry, ro ...