Benjadock
Benjadock

Reputation: 45

Is there a way to run JavaScript snippet after inserting an image in CKEditor?

I have a very interesting situation that I hope someone can help me with. I currently have a custom email campaign system set up for a client that is coded using cold fusion (but this isn't relevant) anyway, What they see in the campaign design bit is a CKEditor for every section (if they decide they want more than one section.) Here's my problem, the clients sometimes don't specify widths on their images, and sometimes they use images with widths 5k+. So I have in the email template:

    <style type="text/css">
        img {
            max-width: 100% !important;
            height: auto !important;
        }
    </style>

Which works great... except for Gmail, one of the most popular email clients.

What I dreamed up: somewhere in CKEditor, it would be really nice if after an image was inserted into the rich text editor, this snippet would be executed:

document.getElementsByTagName("img")[0].setAttribute("max-width", "800px");
document.getElementsByTagName("img")[0].setAttribute("height", "auto");

or

img.style.maxWidth = "800px";
img.style.height = "auto";

Is that possible? or am I just spinning my wheels? Thanks for your time and patience!

Upvotes: 0

Views: 55

Answers (1)

AlfonsoML
AlfonsoML

Reputation: 12740

You're proposing just to patch the problem because the image will be oversized and should be scaled correctly before it's sent out, but if you want to do it that way you can write an output filter for CKEditor.
Something along this: (untested)

var dataProcessor = editor.dataProcessor,
    htmlFilter = dataProcessor && dataProcessor.htmlFilter;

// htmlFilter : conversion from internal data to html output.
htmlFilter.addRules( {
    elements :
    {
        'img' : function( element ) {

            element.attributes.style = 'max-width: 800px; height: auto';

            return element;
        }
    }
});

Obviously the correct solution is to scale down the image to max: 800px when you save it on your system or even before it's uploaded.

Upvotes: 1

Related Questions