How to get the latest css property of a component?
Question
Hi, awesome job with grapesjs!
I already read the docs (especially CssComposer) and also relevant issues but still, I am stuck.
A custom plugin allows me to add css to a component using component.setStyle(). On reload, I need my plugin to initialize with these values.
For example I want to read the margin property of a component. I observed that css gets added inline when using setStyle() and once the data is stored and loaded, the css is defined in classes.
Right now, I am parsing the property value manually with the assumption that the last entry represents the "active" entry. But that approach feels totally wrong! :)
function latestCSSPropertyValue(component, property) {
let css = editor.CodeManager.getCode(component, 'css', {cssc: editor.CssComposer});
let pos1 = css.lastIndexOf(property);
let pos2 = css.indexOf(';', pos1);
return (pos2 > pos1) ? css.substring(pos1, pos2).split(':')[1] : "";
}
I feel like I can achieve this differently with CssComposer but again, I am stuck.
Thanks, Nico
Answers (2)
I observed that css gets added inline when using setStyle() and once the data is stored and loaded, the css is defined in classes.
First of all, be sure to store your templates correctly: Store and load templates in that case, when you set style via component.setStyle(...) on the next page reload you should be able to get that style via component.getStyle(...) without the need to touch the CodeManager/CssComposer
You might also want to take in account setRule/getRule if you need to manipulate CSS rules
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Related Questions and Answers
Continue research with similar issue discussions.
Issue #1720
[QUESTION] How to add the button in custom traits
Hi, I try to add a button to my custom traits for my custom blocks but its not working fine as expected and also need to know how to call t...
Issue #1888
[Question] Add custom html inside canvas
Hi there, I'm using grapes to export a custom json with all the information i need, instead of HTML and CSS. For doing that I'm parsing the...
Issue #1908
[question] Cannot read property 'indexOf' of undefined
I found a previous result here: https://github.com/artf/grapesjs/issues/1772 however I can still not get it to work, using the most basic s...
Issue #1409
Component Drag Event
I want to know how can I get that component from which element is dragged and drop to the other component. I need to add a class if compone...
Paid Plugins That Match This Issue
Curated by issue keywords and label relevance to help you ship faster.
Loading paid plugin recommendations...
Browse Plugin Categories
Jump directly to plugin category pages on the marketplace.