Home > Web Front-end > JS Tutorial > body text

How to Place the Caret at the End of Text in a `contenteditable` Pre Element Consistently Across Browsers?

Patricia Arquette
Release: 2024-11-23 02:31:10
Original
799 people have browsed it
<p>How to Place the Caret at the End of Text in a `contenteditable` Pre Element Consistently Across Browsers?

Setting Caret at the End of Text Cross-Browser

<p>In HTML,
contenteditable
elements allow users to edit text directly within the element. However, there can be cross-browser inconsistencies in how line breaks are handled.

Cross-Browser Line Break Differences

<p>The output of
contenteditable
elements varies across browsers: Chrome places a
<div>
within the line break, Firefox inserts a
<br />
, and Internet Explorer adds a
<p>
.

Setting Caret at End of Text

<p>To consistently position the caret at the end of the text in all browsers, use the following JavaScript function:

function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            &amp;&amp; typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}
Copy after login

Example Usage

<p>To utilize this function, attach an event listener to a button that, when clicked, calls the function to place the caret at the end of the text:

$(document).ready(function()
{
    $('#insert_caret').click(function()
    {
        placeCaretAtEnd($('#content'));
    }
});
Copy after login

The above is the detailed content of How to Place the Caret at the End of Text in a `contenteditable` Pre Element Consistently Across Browsers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template