Issue #2536Opened January 29, 2020by andy-aware3 reactions

[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)

pouyamiralayiJanuary 30, 20201 reactions

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!

andy-awareJanuary 30, 20201 reactions

That is great. How do i stop the data of

model.getStyle()['background-image']

being passed into the CSS? Only the background image.

Thanks

pouyamiralayiJanuary 30, 20201 reactions

@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.

Paid Plugins That Match This Issue

Curated by issue keywords and label relevance to help you ship faster.

View all plugins

Loading paid plugin recommendations...

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.