Set caret position right after the inserted element in a contentEditable div

The following function will do it. DOM Level 2 Range objects make this easy in most browsers. In IE, you need to insert a marker element after the node you’re inserting, move the selection to it and then remove it. Live example: http://jsfiddle.net/timdown/4N4ZD/ Code: function insertNodeAtCaret(node) { if (typeof window.getSelection != “undefined”) { var sel … Read more

trigger an event when contenteditable is changed

Just store the contents to a variable and check if it is different after blur() event. If it is different, store the new contents. var contents = $(‘.changeable’).html(); $(‘.changeable’).blur(function() { if (contents!=$(this).html()){ alert(‘Handler for .change() called.’); contents = $(this).html(); } }); example: http://jsfiddle.net/niklasvh/a4QNB/

How to select all text in contenteditable div?

I used some code from this thread to come up with my answer. It’s 100% jQuery as you asked for as well. Hope you like it 🙂 jQuery.fn.selectText = function(){ var doc = document; var element = this[0]; console.log(this, element); if (doc.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if (window.getSelection) { var … Read more

How to use [(ngModel)] on div’s contenteditable in angular2?

NgModel expects the bound element to have a value property, which divs don’t have. That’s why you get the No value accessor error. You can set up your own equivalent property and event databinding using the textContent property (instead of value) and the input event: import { Component } from “angular2/core”; @Component({ selector: “my-app”, template: … Read more

Get caret index in contenteditable div including tags

Have you tried this? Get a range’s start and end offset’s relative to its parent container Direct link to the jsfiddle: https://jsfiddle.net/TjXEG/1/ Function code: function getCaretCharacterOffsetWithin(element) { var caretOffset = 0; if (typeof window.getSelection != “undefined”) { var range = window.getSelection().getRangeAt(0); var preCaretRange = range.cloneRange(); preCaretRange.selectNodeContents(element); preCaretRange.setEnd(range.endContainer, range.endOffset); caretOffset = preCaretRange.toString().length; } else if (typeof … Read more

replace innerHTML in contenteditable div

The problem is that Rangy’s save/restore selection module works by inserting invisible marker elements into the DOM where the selection boundaries are and then your code strips out all HTML tags, including Rangy’s marker elements (as the error message suggests). You have two options: Move to a DOM traversal solution for colouring the numbers rather … Read more