Grapesjs: [QUESTION]: How to add link on an image?

Created on 15 Jan 2020  路  4Comments  路  Source: artf/grapesjs

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 image?

I tried to use model.replaceWith but the problem is that if I put some styling on the image and then call model.replaceWith, the styles are removed.

Is there a better way to achieve this?

Thanks!

All 4 comments

Ok, I was able to get it working by doing the following:

let model = editor.getSelected();                
let attributes = { href: '#' }

let newLink = {
    type: 'link',
    attributes,
    components: [model.clone()]
}

model.replaceWith(newLink);

I don't know if it's a good way or not, appreciate any feedback.

Hi @simplecommerce !

editor.DomComponents.addType('image-with-link', {
            extend: 'link',
            model: {
                defaults: {
                    style: {
                        display: 'inline-block',
                        padding: '5px',
                        'min-height': '50px',
                        'min-width': '50px'
                    },
                    components: {
                        type: 'image',
                    }
                }
            }
        });

cheers!

Hi @simplecommerce !

editor.DomComponents.addType('image-with-link', {
            extend: 'link',
            model: {
                defaults: {
                    style: {
                        display: 'inline-block',
                        padding: '5px',
                        'min-height': '50px',
                        'min-width': '50px'
                    },
                    components: {
                        type: 'image',
                    }
                }
            }
        });

cheers!

Hi @pouyamiralayi, thanks for the reply.

I didn't mean by creating a new component, what I meant was to simply replace a rendered component model in the canvas (an image) by wrapping it inside a link (a) while keeping the styles.

The example code I pasted does exactly that.

For example:

  1. Add an image on the canvas.
  2. Select the image and add a fixed width, height and a border.
  3. Click on the toolbar icon button to add a link.

Step 3, should wrap the selected image in an (a) tag while keeping the styles of the image.

This is what I was trying to reproduce.

Thanks for the reply though!

Creating custom components it's always a good approach but if your intention was just about creating kind of action (eg. triggered from the toolbar) your example is correct

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kosirm picture kosirm  路  3Comments

krunal039 picture krunal039  路  3Comments

FlashPapa picture FlashPapa  路  3Comments

nojacko picture nojacko  路  3Comments

applibs picture applibs  路  3Comments