Berstos
Berstos

Reputation: 179

Add "rel"-attribute to img tag in TinyMCE 5 editor

I search a solution to add automatically a "rel-attribute" to every image which is added in the TinyMCE 5 editor. So the html tag should look like:

<img class="imageborder" src="https://xy.jpg" rel="lightbox" width="500" height="333" />

I've tried it like that, but it doesn't get added. This is the JSFiddle.

tinyMCE.init({
    selector: '#myTextarea',
    plugins: 'code image autolink link lists charmap print preview textcolor',
    toolbar: 'code image link | undo redo | insert | ',
    menubar: false,
    min_height: 300,
    image_class_list: [
        { title: 'imageborder', value: 'imageborder' },
    ],
    image_rel_list: [
        { title: 'lightbox', value: 'lightbox' },
    ],
    setup: function (ed) {
        ed.on("keyup", function () {
            $('#preview').html(tinymce.activeEditor.getContent());
        });
    }
});

Upvotes: 1

Views: 660

Answers (2)

User863
User863

Reputation: 20039

You can get the img element on NodeChange event.

Doc: https://www.tiny.cloud/docs-4x/advanced/events/#nodechange

Jsfiddle: https://jsfiddle.net/aswinkumar863/L48jdqzs/

tinyMCE.init({
  ...
  setup: function(ed) {
    ed.on("keyup", function() {
      $('#preview').html(tinymce.activeEditor.getContent());
    });
    ed.on('NodeChange', function(e) {
      e.element.parentNode.querySelectorAll('img:not([rel=lightbox])').forEach(img => {
        img.setAttribute('rel', 'lightbox');
      });    
    });
  }
});

Upvotes: 2

Kim Vinberg
Kim Vinberg

Reputation: 36

You could add the rel to the link instead of the image like this:

    tinyMCE.init({
    selector: '#myTextarea',
    plugins: 'code image autolink link lists charmap print preview textcolor',
    toolbar: 'code image link | undo redo | insert | ',
    menubar: false,
    min_height: 300,
    image_class_list: [
        { title: 'imageborder', value: 'imageborder' },
    ],
    rel_list: [
             {title: 'lightbox', value: 'lightbox'},
            {title: 'Other rel', value: 'otherrel'}
        ],
    setup: function (ed) {
        ed.on("keyup", function () {
            $('#preview').html(tinymce.activeEditor.getContent());
        });
    }
});

It´s in the documentation here: https://www.tiny.cloud/docs/plugins/opensource/link/#exampleusingrel_list

Then use the a rel as the lightbox link, instead of the image.

Upvotes: 0

Related Questions