0

I need to modify a pasted image inside a contenteditable div: resize it proportionately, add borders, etc... Perhaps this can be achieved by adding a className that will alter the necessary CSS properties. The problem is that I don't know how to reference the focused, i.e. the active, the clicked-upon image or any element for that matter.

This is the HTML that I am trying to use

<!DOCTYPE html>
<html>

<body>

  <div contenteditable="true">This is a div. It is editable. Try to change this text.</div>

</body>

</html>

7
  • 2
    could you post or add what exactly you have tried and how the code you have looks like?
    – Mixone
    May 27, 2018 at 8:37
  • w3schools.com/tags/… Here is an example of a contenteditable paragraph. It supports not only text editing, but pasting images, etc. I need to get the pasted image and add a css class to it. May 27, 2018 at 8:44
  • 1
    .addEventListener('click'…).
    – deEr.
    May 27, 2018 at 8:45
  • 1
    @ AjAX: when I paste an image, the code generated by the browser is like this: <img src='data:image/png;base64,iVBORwOKGgoAAAANSUhEUgAA...etc.> So the image element has no id, and there is no way ta add event listener without knowing the element reference. May 27, 2018 at 8:54
  • hmm a bit more complicated than I originally thought but there is a solution
    – Mixone
    May 27, 2018 at 8:55

2 Answers 2

0

Using css, html and javascript

Your editable content should be inside a parent div with an id or class name, you can even have different divs for images and such.

Then it is as simple as having css like so:

#editableContentDiv img {
     imgProperty: value;
}

Then you can have javascript like so:

function insertImage(){
    var $img = document.querySelector("#editableContentDiv img");
    $img.setAttribute('class','resize-drag');      
}

Eventually if you have more than one img inside the same div you can use querySelectorAll instead of querySelector and then iterate through the img tags inside same div.

I beleive that should at least give you an idea of where to start with what you want.

Similar example

I found this gist that seems to have similar things to want you want but a bit more complicated.

function resizeMoveListener(event) {
  var target = event.target,
    x = (parseFloat(target.dataset.x) || 0),
    y = (parseFloat(target.dataset.y) || 0);

  // update the element's style
  target.style.width = event.rect.width + 'px';
  target.style.height = event.rect.height + 'px';

  // translate when resizing from top or left edges
  x += event.deltaRect.left;
  y += event.deltaRect.top;
  updateTranslate(target, x, y);
}

function dragMoveListener(event) {
  var target = event.target,
    // keep the dragged position in the data-x/data-y attributes
    x = (parseFloat(target.dataset.x) || 0) + event.dx,
    y = (parseFloat(target.dataset.y) || 0) + event.dy;
  updateTranslate(target, x, y);
}

function updateTranslate(target, x, y) {
  // translate the element
  target.style.webkitTransform =
    target.style.transform =
    'translate(' + x + 'px, ' + y + 'px)';

  // update the position attributes
  target.dataset.x = x;
  target.dataset.y = y;
}


function insertImage() {
  var $img = document.createElement('img');
  $img.setAttribute('src', 'https://vignette.wikia.nocookie.net/googology/images/f/f3/Test.jpeg/revision/latest?cb=20180121032443');
  $img.setAttribute('class', 'resize-drag');
  document.querySelector(".container-wrap").appendChild($img);

  var rect = document.querySelector(".container-wrap").getBoundingClientRect();
  $img.style.left = rect.left;
  $img.style.top = rect.top;
}

function dataTransfer() {

  //cleanup
  var $out = document.querySelector(".out-container-wrap");
  while ($out.hasChildNodes()) {
    $out.removeChild($out.lastChild);
  }

  //get source
  var source = document.querySelector('.container-wrap')

  //get data
  var data = getSource(source);

  //add data to target
  setSource($out, data);

}

/**
 * Get data from source div
 */
function getSource(source) {
  var images = source.querySelectorAll('img');
  var text = source.querySelector('div').textContent;

  //build the js object and return it.
  var data = {};
  data.text = text;

  data.image = [];

  for (var i = 0; i < images.length; i++) {
    var img = {}
    img.url = images[i].src
    img.x = images[i].dataset.x;
    img.y = images[i].dataset.y;
    img.h = images[i].height;
    img.w = images[i].width;

    data.image.push(img)
  }
  return data;
}

function setSource(target, data) {

  //set the images.
  for (var i = 0; i < data.image.length; i++) {

    var d = data.image[i];

    //build a new image
    var $img = document.createElement('img');
    $img.src = d.url;
    $img.setAttribute('class', 'resize-drag');
    $img.width = d.w;
    $img.height = d.h;
    $img.dataset.x = d.x;
    $img.dataset.y = d.y;


    var rect = target.getBoundingClientRect();
    $img.style.left = parseInt(rect.left);
    $img.style.top = parseInt(rect.top);
    //transform: translate(82px, 52px)
    $img.style.webkitTransform = $img.style.transform = 'translate(' + $img.dataset.x + 'px,' + $img.dataset.y + 'px)';
    //$img.style.setProperty('-webkit-transform', 'translate('+$img.dataset.x+'px,'+$img.dataset.y+'px)');
    target.appendChild($img);
  }

  //make a fresh div with text content
  var $outContent = document.createElement('div')
  $outContent.setAttribute('class', 'out-container-content');
  $outContent.setAttribute('contenteditable', 'true');
  $outContent.textContent = data.text;

  target.appendChild($outContent);
}

interact('.resize-drag')
  .draggable({
    onmove: dragMoveListener,
    inertia: true,
    restrict: {
      restriction: "parent",
      endOnly: true,
      elementRect: {
        top: 0,
        left: 0,
        bottom: 1,
        right: 1
      }
    }
  })
  .resizable({
    edges: {
      left: true,
      right: true,
      bottom: true,
      top: true
    },
    onmove: resizeMoveListener
  })
.resize-drag {
  z-index: 200;
  position: absolute;
  border: 2px dashed #ccc;
}

.out-container-content,
.container-content {
  background-color: #fafcaa;
  height: 340px;
}

#btnInsertImage {
  margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="http://code.interactjs.io/interact-1.2.4.min.js"></script>
</head>

<body>
  <button id="btnInsertImage" onclick="insertImage()">Insert Image</button>
  <div class="container-wrap">
    <div class="container-content" contenteditable="true">This is the content of the container. The content is provided along with the image. The image will be moved around and resized as required. The image can move within the boundary of the container.</div>
  </div>
  <button id="btnSubmit" onclick="dataTransfer()">Submit</button>
  <div class="out-container-wrap">
  </div>
</body>

</html>

Source

6
  • Mixone, thank you for your examples! Your suggestion is a workaround, but it applies a new class to all the images inside the div. I need something like querySelector (activeElement...). The second example inserts and moves an image, but does not give me a clue of how to find out which image is selected. May 27, 2018 at 9:26
  • Thats what i meant by having each image have a separate div, you can also use the insert image function to give it a different id each time with something like a counter, the css and tag settings are editable through the javascript
    – Mixone
    May 27, 2018 at 9:30
  • also, you can have "on" "focus" as a listener to have this as the img selected
    – Mixone
    May 27, 2018 at 9:30
  • 1
    @ Mixone: if you could add a working example, that will be great, because, as I am missing something. The image is not inserted, but pasted via the clipboard. May 27, 2018 at 10:00
  • gimme a bit and i will try
    – Mixone
    May 27, 2018 at 10:04
0

This is what I tried and it seems to be working - at least on my system, the snippet I made does not work unfortunately.

function getSelImg(){
var curObj;
window.document.execCommand('CreateLink',false, 'http://imageselectionhack/');
   allLinks =   window.document.getElementsByTagName('A');
   for(i = 0; i < allLinks.length; i++)
    {
      if (allLinks[i].href == 'http://imageselectionhack/')
       {
         curObj = allLinks[i].firstChild;
         window.document.execCommand('Undo'); // undo link
         break;
       }
    }
 
 if ((curObj) && (curObj.tagName=='IMG'))
 {
   //do what you want to...
	 curObj.style.border = "thick solid #0000FF";
 }
}	
<!DOCTYPE html>
<html>

<body>
<input type="button" onclick="getSelImg()" value="set img border">
<div contenteditable="true">This is a div.<br>
It is editable.<br>
Try to paste an image here:<br>
###########################<br>
<br>
<br>
<br>
###########################
</div>

</body>

</html>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.