Search code examples
javascriptjquerywysiwygcontenteditable

contenteditable no detection image


please help me..

I have contenteditable issues, especially on image detection

I use this code :

function getnode() {
  var node, selection;
  if (window.getSelection) {
    selection = getSelection();
    node = selection.anchorNode;
  }
  if (!node && document.selection) {
    selection = document.selection;
    var range = selection.getRangeAt ?
      selection.getRangeAt(0) :
      selection.createRange();
    node = range.commonAncestorContainer ?
      range.commonAncestorContainer :
      range.parentElement ? range
      .parentElement() : range.item(0);
  }
  if (node) {
    return (node.nodeName == "#text" ? node.parentNode : node);
  }
}

jquery :

$(function() {
  $("#editor").bind('click', function(e) {
    var $node = $(getnode());

    if ($node.is('a')) {
      alert("Yes I am link");
    }

    if ($node.is('b')) {
      alert("Yes I am bold");
    }

    if ($node.is('img')) {
      alert("IMAGE READY");
    } else {
      $("#editor").focus();
    }
  });
});

FIDDLE DEMO : Please help me, to find the way

Thank you in advance


Solution

  • I think the easiest way to fix your problem would be to not use your own getnode function, but allow the element to come from the click eventhandler by means of the target property.

    Changing your code to this works perfectly, at least, for the scenarios I have tried

    $("#editor").bind('click', function (e) {
        var $node =  $( e.target );
        if ($node.is('a')) {
            alert("Yes I am link");
        }
        if ($node.is('b')) {
            alert("Yes I am bold");
        }
        if ($node.is('img')) {alert("IMAGE READY");
        } else {
            $("#editor").focus();
        }
    });