Hi,
Reading through the documentation, I can't find anywhere that explains what I'm looking to do.
Currently, Grapes grabs the background image and puts it into the style, but I want to take this image and not add it to a background style, I want to put it into a data-element on the element that is selected.
I've been looking at:
editor.on('component:styleUpdate', function(e, i){});
But inside of this, I can't find the correct attributes I need to target to trigger the change it also doesn't seem to update when new items have been added to the canvas. I could be wrong, but I'm going around in circles.
Hi @awaredigital StyleManager targets both Components and CssRules, so do it like below:
editor.on('component:styleUpdate:background-image', component => {
const sm = editor.StyleManager
const model = sm.getModelToStyle(component)
// the model can be a Component or CssRule
const bg = model.getStyle()['background-image']
const idx = bg.toString().indexOf('url(')
const newBg = bg.substr(idx + 'url'.length, bg.length - 1)
if (newBg != '(none)') {
component.addAttributes && component.addAttributes({'data-element': newBg})
}
})
Cheers!
That is great. How do i stop the data of
model.getStyle()['background-image']
being passed into the CSS? Only the background image.
Thanks
@awaredigital just append the following:
const style = model.getStyle()
delete style['background-image']
delete style['background-repeat']
delete style['background-position']
delete style['background-attachment']
delete style['background-size']
component.setStyle(style)
and in case the styles showed up again when you refreshed the editor, add the below line to the config:
const editor = grapesjs.init({
// ...
clearStyles: true,
});
Cheers!
I've added like so:
editor.on('component:styleUpdate:background-image', component => {
const sm = editor.StyleManager
const model = sm.getModelToStyle(component)
const bg = model.getStyle()['background-image']
const idx = bg.toString().indexOf('url(')
const newBg = bg.substr(idx + 'url'.length, bg.length - 1)
if (newBg != '(none)') {
component.addAttributes && component.addAttributes({'data-image': newBg})
}
const style = model.getStyle();
delete style['background-image'];
component.setStyle(style);
});
But get the following error:
Uncaught TypeError: Cannot read property 'toString' of undefined
Because the background image is being removed.
@awaredigital i have tested the above code and it was working fine.
but for the error, you may check bg before further processing because after we update the component style we may get the callback again which is your case here:
if (bg != null) {
const idx = bg.toString().indexOf('url(')
//...
}
Cheers!