Allow moving only <img> s inside contentEditable <div>
I am struggling to achieve the desired behavior with a div marked as contentEditable . I want to allow the user to move img within the div and maintain its built-in, but not to let them resize or otherwise change this img value. Otherwise, they can change the text in the div .
The default behavior of the browser can be seen below, while img can be moved and resized using the drag and drop handle:
<html> <head> <title></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> </head> <body> <div id="edit" contenteditable="true"> Here is some text, and also an <img src="http://img841.imageshack.us/img841/1747/imagead.png" /> image </div> </body> </html> I played with various client scenarios to try to achieve the desired functionality, but every attempt I try to make seems to run into difficulties. What I can achieve is the final blocking with:
<script type="text/javascript"> $(document).ready(function() { $('img', '#edit').each(function (i, item) { item.contentEditable = false; $(item).bind('mousedown', function (e) { e.preventDefault(); }); if ($.browser.msie) { item.oncontrolselect = function () { return false; } } }); }); </script> but although this prevents duplicate elements (a problem that I had in Firefox) and resizing using drag and drop controls (in IE), it's impossible to move img at all.
UPDATE: Thank you guys, the closest I have so far:
<script type="text/javascript"> $(document).ready(function() { $('img', '#edit').each(function (i, item) { attachEvents(item); }); if ($.browser.mozilla) { document.execCommand("enableObjectResizing", false, false); } }); function attachEvents(item) { if ($.browser.msie) { item.attachEvent('onresizestart', function (e) { e.returnValue = false; }, false); item.attachEvent('ondragend', function (e) { // cannot get IE to rebind moved item (toElement or similar is not available until IE9 when using addEventListener) attachEvents(e.srcElement); }, false); } if ($.browser.opera) { // doesn't seem to work at all in Opera 11 } } </script> but the two remaining problems are the complete lack of support in Opera (with which I can live) and the problem of recovering ondragend events in IE.
Can anyone else help?