[Question] Background Image inline
Question
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.
Answers (3)
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 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!
Related Questions and Answers
Continue research with similar issue discussions.
Issue #1877
[FEATURE REQUEST] Custom styles that add/remove custom classes?
Currently, all the style manager values that you change for an element simply update a <style> tag inline in the HTML. Is it possible to ch...
Issue #2651
[QUESTION] Background image via inline style not accessible?
This is very simple, but i can not access the background image set via CSS, within my custom block 'content'. How do i change the backgroun...
Issue #2595
[Question] Having trouble dragging external html with draggable="true"
I want to make an external html element able to be dragged into GrapesJS, like how you can drag in a block and it will add something. I hav...
Issue #2510
[QUESTION]: How to add link on an image?
Hi, quick question. I have an image and I just want to add a link on it. Using the model, what is the easiest way to add a link on the imag...
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.