Solved

BR instead of P in contentEditable DIV - Selection Problem

Posted on 2008-10-24
3
3,726 Views
Last Modified: 2008-10-24
I have HTML file which contains a DIV element with contentEditable enabled. I don't want to introduce P elements into the DIV element, but unfortunately a couple of web browsers tend to do this under certain circumstances.

So I came up with a workaround which intercepts when the user hits the return key. When the return key is pressed, a BR element is inserted, and the event is cancelled so that the web browser doesn't do its default process.

This much I have working, and to my surprise it works exactly how I want it to in IE first time. My problem is in the Gecko based browsers like Chrome, Firefox, and Safari. When the return key is pressed in any one of those browsers, the user-input caret is not repositioned after the new BR element.

Firefox is slightly different from Chrome and Safari. The caret is not immediately positioned correctly, but pressing a key on the keyboard appears remedy the problem. Chrome and Safari continue typing before the BR element.

Does anybody know how I can resolve this issue?
<html>

<head>

            <!-- Prototype Framework for JavaScript: http://www.prototypejs.org -->

            <script type="text/javascript" src="prototype.js"></script>

            <script type="text/javascript">

            window.onload = function(event) {

                        document.observe('keydown', doc_keydown.bindAsEventListener(document));

            }

 

            function charCode(event) {

                  return typeof event.which !== 'undefined' ? event.which : event.keyCode;

            }

            function doc_keydown(event) {

                  var range;

                  var code = charCode(event);

                  switch (code) {

                        case 13:      // return

                              if (document.selection) {            // IE

                                    range = document.selection.createRange();

                                    range.pasteHTML("<br />");

                                    range.moveEnd("character", 1);

                                    range.moveStart("character", 1);

                                    range.collapse(false);

                              }

                              else { // FF, Google Chrome

                                    range = window.getSelection().getRangeAt(0);

                                    range.deleteContents();

                                    var newNode = new Element("br");

                                    range.insertNode(newNode);

                                    range.setStartAfter(newNode);            // Doesn't work from here down.

                                    range.setEndAfter(newNode);

                                    range.collapse(false);

                              }

                              break;

                        default:

                              return true;

                  }

                  event.stop();

                  return false;

            }</script>

</head>

<body>

            <div contentEditable="true" style="border: solid 2px black; padding: 6px">

                        Some initial text - Edit Me!

            </div>

</body>

</html>

Open in new window

0
Comment
Question by:numberkruncher
  • 2
3 Comments
 
LVL 44

Accepted Solution

by:
scrathcyboy earned 500 total points
Comment Utility
Don't you need to use the createRange function first before you use getRangeAt -- yes?  no?

https://developer.mozilla.org/En/DOM:range
https://developer.mozilla.org/es/DOM/range.setStartAfter

like this --

range = document.createRange();
referenceNode = document.getElementsByTagName("div").item(0);
range.setStartAfter(referenceNode);

Also check this -- http://search.cpan.org/dist/Mozilla-DOM/lib/Mozilla/DOM/Range.pod

Anyway, this is an extremely important piece of code you are developing.  P tags can be a real <P>ain in the <P>utt at times, and it would be great to have a way to convert them to <BR> as needed.  If you don't get a solution that works, click the red button right of your question, request attention, and ask a MOD to send this out to HTML experts for assistance.
0
 
LVL 13

Author Comment

by:numberkruncher
Comment Utility
Thanks scrathcyboy!

The Mozilla links really helped me to find a solution to this problem.

> Don't you need to use the createRange function first before you use getRangeAt -- yes?  no?

According to the (as always) fantastic QuirksMode website, it is necessary to use createRange before getRangeAt for older versions of the Safari web browser.
(http://www.quirksmode.org/dom/range_intro.html)

I found that in the Gecko browsers, my requirement was actually two separate procedures:
   1) replace original selection with ""
   2) compose a new selection from scratch, or adjust the previously acquired range, followed by rebuilding the selection and adding the new range to it.

I have attached the working version of my HTML for those who are interested.

Here are some other websites which I found particularly useful:

https://developer.mozilla.org/En/DOM/Selection
http://www.wrox.com/WileyCDA/Section/JavaScript-DOM-Ranges-Page-3.id-292303.html


Thanks again for your help!
<html>

<head>

	<script type="text/javascript" src="prototype.js"></script>

	<script type="text/javascript">

		window.onload = function(event) {

			document.observe('keydown', doc_keydown.bindAsEventListener(document));

		}
 

		function charCode(event) {

			return typeof event.which !== 'undefined' ? event.which : event.keyCode;

		}

		function doc_keydown(event) {

			var selection = document.selection, range;

			var code = charCode(event);

			switch (code) {

				case 13:    // return

					if (selection) {	// IE

						range = selection.createRange();

						range.pasteHTML("<br />");

						range.moveEnd("character", 1);

						range.moveStart("character", 1);

						range.collapse(false);

					}

					else { // FF, Google Chrome

						selection = window.getSelection();

						range = selection.getRangeAt(0);

						range.deleteContents();

						var newNode = new Element("br");

						range.insertNode(newNode);
 

						range = document.createRange();

						range.setStartAfter(newNode);

						range.setEndAfter(newNode);

						range.collapse(false);
 

						selection.removeAllRanges();	// The bit I was missing!

						selection.addRange(range);

					}

					break;

				default:

					return true;

			}

			event.stop();

			return false;

		}

	</script>

</head>

<body>

	<div>

		<div style="float: right; margin-top: -4px; margin-right: -4px; width: 16px; height: 16px; background: whitesmoke; border: solid 1px gray"></div>

		<div contentEditable="true" style="border: solid 2px black; padding: 6px">

			Some initial text - Edit Me!

		</div>

	</div>

</body>

</html>

Open in new window

0
 
LVL 44

Expert Comment

by:scrathcyboy
Comment Utility
I have added this question and solution to the knowledgebase.  It is one of the more important ones to come in to EE in a LONG while.  Cheers !!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Several part series to implement Internet Explorer 11 Enterprise Mode
This article offers some helpful and general tips for safe browsing and online shopping. It offers simple and manageable procedures that help to ensure the safety of one's personal information and the security of any devices.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Google currently has a new report that is in beta and coming soon to Webmaster Tool accounts. This Micro Tutorial will highlight new features for Google Webmaster Tools.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now