I'm a little confused why doesn't this code work!
The HTML Markup:
<div id="diva"><b>Score</b> some <i>goals</i></div>
<div id="soda"></div>
The JavaScript code:
function GetSelectedText () {
if (window.getSelection) { // all browsers, except IE before version 9
var range = window.getSelection ();
alert (range.toString ());
}
else {
if (document.selection.createRange) { // Internet Explorer
var range = document.selection.createRange ();
alert (range.text);
}
}
}
var butn = document.getElementById("soda");
butn.onclick = function(){
GetSelectedText();
}
One problem that you may well be experiencing is that in some browsers (notably IE), by the time the button's click event fires, the selection has been destroyed. You can fix this by using the mousedown event instead (which still allows the selection to be destroyed, but only after the event has been handled), or by making the button unselectable.
I assume your button is not an actual button input, because this behaviour only happens for regular elements.
Demo: http://jsfiddle.net/L9bvU/1/
function GetSelectedText () {
if (window.getSelection) { // all browsers, except IE before version 9
var range = window.getSelection ();
alert (range.toString ());
}
else {
if (document.selection.createRange) { // Internet Explorer
var range = document.selection.createRange ();
alert (range.text);
}
}
}
span {
background-color: #ccc;
padding: 3px;
border: solid gray 1px;
}
*[unselectable="on"] {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
/*
Introduced in IE 10.
See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
*/
-ms-user-select: none;
user-select: none;
}
<div contenteditable="true">Please select some of this text and press a button below</div>
<span onclick="GetSelectedText()">Click</span>
<span onmousedown="GetSelectedText()">Mousedown</span>
<span unselectable="on" onclick="GetSelectedText()">Click, unselectable</span>
function getSelectedText() {
if (window.getSelection) {
return window.getSelection();
}
if (window.document.getSelection) {
return window.document.getSelection();
}
if (window.document.selection) {
return window.document.selection.createRange().text;
}
return "";
}
<p onmouseup="getSelectedText(); alert(txt)">
Highlight some of this text
with the mouse select press button end release
to fire the event. </p>
This is my way. You just need to select the text end alert text or anything else.
Does anyone know how OnMouse(event) set for the entire document in html, and it does not have to be directly added to html page.
To be on the other side, as we can change the elements in firebug!>-examples
Well there are two problems with the above code.
-You can't be guaranteed that
var butn = document.getElementById("soda");
will work because it may execute before the document is done loading
-When you click on another element that's not a button, the selection is lost. If you change the "soda" div to then it will work:
<div id="diva"><b>Score</b> some <i>goals</i></div>
<div id="soda" onclick="GetSelectedText()">This will NOT work</div>
<input type="button" onclick="GetSelectedText()" value="This will work"/>
However I strongly recommend you look at jQuery as the others here have advised; it will make your like a lot easier!
Related
I want to build my own popup box using div's (not the browser default). So when I display my own popup I want to stop the javascript execution until the user clicks a button on my own popup, same as the default confirmation popup in browsers. Is there a way to do this? If so how? I would like to avoid using jQuery.
You can't (and shouldn't) block JavaScript execution. It would be possible by introducing an endless while loop, but that would seriously degrade performance and also affect the handling of click events.
So, the best and probably only way to do this, is to use a callback that is called when you press a button. This does mean that you can't call this alternative confirm method in a synchronous way, though. Instead you can provide a callback that is executed when one of the buttons is pressed.
I hacked together an example. This is just made up on the fly, and only has some rudimentary styling. If it contains minor flaws, please forgive me.
/**
* The alternative confirmation function
*/
window.myConfirm = function(options) {
// Create the elements
var popup = document.createElement('div');
var box = document.createElement('div');
var ok = document.createElement('button');
var cancel = document.createElement('button');
// Style them
popup.className = 'lightbox';
box.className = 'dialog';
ok.className = 'button buttonOK';
cancel.className = 'button buttonCancel';
// Button texts
ok.innerText = 'OK';
cancel.innerText = 'Cancel';
// Click handlers.
ok.onclick = function(event) {
popup.parentNode.removeChild(popup);
options.onConfirm();
}
cancel.onclick = function(event) {
popup.parentNode.removeChild(popup);
options.onDecline();
};
// Clicking the box does nothing.
box.onclick = function(event){
event.stopPropagation();
};
// Clicking the popup equals cancel.
popup.onclick = cancel.onclick;
// Add all elements to the document.
popup.appendChild(box);
box.innerHTML = "<div><h2>" + options.title + "</h2>" + options.prompt + "</div>";
box.appendChild(ok);
box.appendChild(cancel);
// Finally show the box.
document.body.appendChild(popup);
};
/**
* The call
*/
myConfirm({
title: "Confirm",
prompt: "Are you sure?",
onConfirm: function() {
// The code that is executed when user presses OK.
alert('You confirmed');
},
onDecline: function() {
// Code executed on cancel, or when clicking next to the box.
alert('You declined');
}
});
.lightbox {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
text-align: center;
}
.dialog {
display: inline-block;
margin-top: 50px;
background-color: white;
padding: 50px;
}
.dialog div {
text-align: left;
}
There is no way of stopping the execution, get an input from the user and then continue from some point without using JavaScript popup boxes. You can build one on your own with html components and display it with buttons, provide call backs. You would need to block the window from user access, take the input and then unblock the window. You may use Javascript frameworks like jQuery to get a better styled, enhanced and optimized component. Here is piece of code demonstration:
JavaScript
function myCancelClick() {
hidePrompt();
alert("Cancel");
}
function myOkClick(){
hidePrompt();
alert("Ok");
}
function showPrompt() {
document.getElementById("promptPane").style.display = '';
document.getElementById("displayPane").style.display = 'none';
}
function hidePrompt() {
document.getElementById("promptPane").style.display = 'none';
document.getElementById("displayPane").style.display = '';
}
HTML body
<body>
<div id="displayPane">
<input type="button" onclick="showPrompt()" value="Show Prompt"/>
</div>
<div id="promptPane" style="display: none;">
<div id="myPrompt">what would you like to click?<input type="button" onclick='myCancelClick();' value="Cancel"/><input type="button" onclick='myOkClick();' value="Ok"/>
</div>
</div>
</body>
Fiddle
If you know, how much time you want to stop for; try using setTimeout() function of Javascript to produce a delay
here I have this code.
$(document).ready(function(){
//Variables
var inventory = {storage:'pocket',stuff:0,space:5};
var equip = {
head:'',
chest:'torn shirt',
arms:'',
wrists:'watch',
hands:'',
legs:'torn jeans',
ankles:'',
feet:''
};
var equipNames = [
'torn shirt',
'torn jeans',
'watch',
'boots'
];
var equipPlaces = {
torn_shirt:'chest',
watch:'wrists',
torn_jeans:'legs',
boots:'feet'
}
//Setup
addToInventory('boots',1);
//Intervals
setInterval(function(){
//Text
$('#inventoryTitle').text(inventory.storage+'-'+inventory.stuff+'/'+inventory.space);
$('#equipHead').text(equip.head);
$('#equipChest').text(equip.chest);
$('#equipArms').text(equip.arms);
$('#equipWrists').text(equip.wrists);
$('#equipHands').text(equip.hands);
$('#equipLegs').text(equip.legs);
$('#equipAnkles').text(equip.ankles);
$('#equipFeet').text(equip.feet);
},1);
//Functions
function addToInventory(name,amount){
for(var i=0;i<amount;i++){
if(inventory.stuff>=inventory.space) return;
$('<tr>').text(name).appendTo($('#inventory')).addClass('item');
inventory.stuff++;
}
}
function takeOff(name){
if(equip.head==name) equip.head='';
if(equip.chest==name) equip.chest='';
if(equip.arms==name) equip.arms='';
if(equip.wrists==name) equip.wrists='';
if(equip.hands==name) equip.hands='';
if(equip.legs==name) equip.legs='';
if(equip.ankles==name) equip.ankles='';
if(equip.feet==name) equip.feet='';
}
function isEquip(name){
for(var i=0;i<equipNames.length;i++){
if(name==equipNames[i]) return true;
}
return false;
}
function equip(name){
var name2 = name
name.replace(/ /g,'_');
alert(name);
equip[equipPlaces[name2]]=name;
}
function removeFromInventory(name){
}
//Triggers
$('.equip').click(function(){
var e = $(this).text();
if(e!=''){
if(inventory.stuff<inventory.space){
takeOff(e);
addToInventory(e,1);
}
}
});
$('.item').on('click', function(){
var i = $(this).text();
alert(i);
if(isEquip(i)){
alert(i);
equip(i);
}
});
});
html, body, button {
background-color:black;
color:lime;
font-family:monospace;
text-transform:uppercase;
}
header {text-align:center;}
fieldset {border:1px solid lime;}
td, button {border:1px solid lime;text-align:center;}
html {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>survivor</header>
<fieldset style='float:right;'>
<legend id='inventoryTitle'>storage - stuff / space</legend>
<table id='inventory'></table>
</fieldset>
<fieldset style='float:right;'>
<legend>Equipment</legend>
<table>
<tr><td>Head</td><td id='equipHead' class='equip'></td></tr>
<tr><td>chest</td><td id='equipChest' class='equip'></td></tr>
<tr><td>arms</td><td id='equipArms' class='equip'></td></tr>
<tr><td>wrists</td><td id='equipWrists' class='equip'></td></tr>
<tr><td>hands</td><td id='equipHands' class='equip'></td></tr>
<tr><td>legs</td><td id='equipLegs' class='equip'</td></tr>
<tr><td>ankles</td><td id='equipAnkles' class='equip'></td></tr>
<tr><td>feet</td><td id='equipFeet' class='equip'></td></tr>
</table>
</fieldset>
This is a game I am working on, the current aspect of the game I am working on is the equipment system. It works mostly fine, you can take items off of yourself by clicking them in the equipment fieldset, and they go into your inventory, unless it's full. The problem is trying to put them back on, you should be able to do this by clicking the equipment in your inventory or 'pocket', I have done some testing and I believe the problem is at
$('.item').on('click', function(){
var i = $(this).text();
alert(i);
if(isEquip(i)){
alert(i);
equip(i);
}});
I believe the problem is that JQuery is not recognizing that the items in the inventory have the 'item' class, though if you note in the addToInventory() function I specifically give it the 'item' class, this confuses me. Any help?
Your class="item" elements do not exist at the time you ran the jQuery selector and bound the event handler.
Use a delegated event handler attached to a non-changing ancestor element:
$(document).on('click', '.item', function(){
var i = $(this).text();
alert(i);
if(isEquip(i)){
alert(i);
equip(i);
}
});
document is the default if nothing else is closer.
It works by listening for the event (in this case click) bubbbling up to an ancestor of the element clicked, then applying a jQuery selector at event time. Then applying the function to any matching elements that caused the event. This allows for elements to match even if they were added after the event was registered.
Note: Never use 'body' for delegated mouse events as styling can result in a 0 height, which stops the events bubbling. Use document if nothing else is conveniently closer.
Really simple: how do I most accurately test if a browser has support for a certain CSS selector?
I currently have some CSS code that makes the page a little more interactive by using the :checked selector in CSS, but I want to create a fallback script that does the same thing with JavaScript, but only if the user's browser has no support for the :checked selector.
My question is, how do I most accurately test if the user's browser supports a certain CSS selector?
Here is the code I'd like to use it on:
HTML:
<label class="coolbox">
<input type="checkbox"/>
<span>I want to eat some caek.</span>
</label>
CSS:
.coolbox input {display:none;}
.coolbox span::before {
content: "";
display:inline-block;
width:10px;
height:10px;
margin-right:5px;
border:1px solid black;
}
.coolbox:hover span::before {border:1px solid #555;}
.coolbox:active span::before {border:1px solid #999;}
.coolbox span::before {background-color:#F77;}
.coolbox input:checked + span::before {background-color:#4A4;}
Demo
PS: I'd prefer not to just use conditional comments, because I'd like to follow the standard of detecting features instead of browsers.
You could use querySelector:
function testSelector(selector, node){
var scope = document.createElement("div");
scope.appendChild(node);
try {
return scope.querySelector(selector) !== null;
} catch(e) { return false; }
}
You can test it like this:
var node = document.createElement("input");
node.type = 'checkbox';
node.checked = 'checked';
testSelector("input:checked", node); // === true
See this other question for more info on querySelector.
Workaround for your case:
<input type=checkbox checked=checked>
css:
input{
font-family:'arial';
}
input:checked{
font-family:'sans-serif';
}
checking procedure: js
alert($('input').css('font-family')=='sans-serif'?'supported':'not supported');
From some research I was able to find various websites that can test your browser to see the support.
This website is helpful to find what supports what but does not test your current browser.
CSS Selectors
This website will test your browser and if you don't want to use modernizr you can learn from their script.
CSS Test
This last website seems to do a great job and is very accurate of the support. I also am pretty sure I found the script that is doing this so like
I said you can learn from how other website are doing this.
CSS3Test
Source Code (add view-source: to view source, unable to link according to SO)
Support.js
To figure how they are making this work you will need to understand how their scripts are working. The bottom three seem to be the most critical to the function.
<script src="utopia.js"></script>
<script src="supports.js"></script>
<script src="csstest.js"></script>
<script src="tests.js"></script>
These are just some options that I found and it is up to your needs. Best of luck and hopefully this has been helpful.
A shorter way to do it would be to simply try the query selector, if it produces an error, return false, else true, like this:
function testSelector(selector) {
document.querySelector('*'); //checks if querySelector is implemented and raises an error if not
try {document.querySelector(selector)} catch (e) {return false}
return true;
}
I checked it on IE9 Windows and Chrome Mac (V43.0.2357.130), Win(V39.0.2171.95m), FireFox Win (V38.0.5), and it works fine with testSelector("form:invalid"), which is not implemented by IE9, but by everybody else.
While this is, admittedly, a very late answer to a rather old question it seemed worth adding another answer.
One approach, using JavaScript to test for selector support, is below with explanatory comments in the code:
// some DOM utilities and helpers,
// caching document as I don't enjoy typing that much:
const D = document,
// aliasing document.querySelector() and element.querySelector()
// again, because I don't enjoy typing; here the function takes
// two arguments 'sel' and 'context',
// 'sel' is a String, and is the selector for the element we're
// trying to retrieve;
// 'context' is the element/node we wish to search within; if
// no context is passed we default to document.querySelector()
// otherwise we use Element.querySelector():
get = (sel, context = D) => context.querySelector(sel),
// as above, except it's an alias for querySelectorAll(), and
// here we return an Array of nodes instead of a NodeList in
// order to use Array methods when/if required:
getAll = (sel, context = D) => [...context.querySelectorAll(sel)],
// alias for document.createElement(), which also allows properties
// to be set on the created element:
create = (tag, prop) => document.createElement(tag),
// simple function to allow for more elaborate templates, and
// arguments if required later:
templatedResult = (text) => `<code>${text}</code>`,
// named function to assess whether the browser supports/implements
// a given selector; this takes a reference to the Event Object
// passed automatically from EventTarget.addEventListener():
verifySelectorCompatibility = (evt) => {
// preventing default actions (as one of the events to which
// bind the function is form.submit):
evt.preventDefault();
// gathering variables/data
// here we retrieve the first/only <input> element within
// the document:
const input = get('#testSelector'),
// we retrieve the value from the <input> and trim that
// value of it's leading/trailing white-space:
selector = input.value.trim(),
// we retrieve the element with id=results:
output = get('#results'),
// we use the CSS.supports() function to assess whether
// the browser supports the supplied selector, which
// we pass to the function in a template string
// concatenating the selector within the string
// 'selector(...)' as required by the function:
result = CSS.supports(`selector(${selector})`),
// creating an <li>:
listElement = create('li');
// if the event-type is 'submit' and the user-entered selector
// - once trimmed of leading/trailing white-space - is zero-
// length we return at this point:
if (evt.type === 'submit' && selector.trim().length === 0) {
return false;
}
// here we add the class of 'supported' or 'unsupported' based on
// the 'result' variable being exactly equal to (Boolean) true
// or not:
listElement.classList.add(result === true ? 'supported' : 'unsupported');
// here we set the innerHTML of the <li> element to the template string
// from the defined function (above):
listElement.innerHTML = templatedResult(selector);
// we then use Element.prepend() to insert the new <li>
// as the first child of the 'output' element:
output.prepend(listElement);
},
// here we return the first/only <button> and <form> elements:
button = get('button'),
form = get('form');
// and we then bind the verifySelectorCompatibility() function
// to the 'click' event of the <button> and the 'submit' event
// of the <form>:
button.addEventListener('click', verifySelectorCompatibility);
form.addEventListener('submit', verifySelectorCompatibility);
*,
::before,
::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
form {
margin-block: 1em;
margin-inline: auto;
width: clamp(30rem, 60vw, 1000px);
}
fieldset {
display: grid;
gap: 1em;
grid-auto-rows: min-content;
grid-template-columns: repeat(4, 1fr);
padding-block: 0.25em;
padding-inline: 0.5em;
}
label {
display: flex;
flex-flow: row nowrap;
gap: 1em;
grid-column: 1 / -1;
margin-block: 1em;
margin-inline: 0.5em;
padding: 0.25em;
}
label span {
align-self: center;
}
label span::after {
content: ': ';
}
label input {
flex-grow: 1;
object-fit: cover;
padding: 0.25em;
}
button {
grid-column: -2 / span 2;
}
#results li {
border-block-end-width: 3px;
border-block-end-style: solid;
font-family: monospace;
font-size: 1.5em;
padding-block: 0.25em;
padding-inline: 0.5em;
}
.supported {
border-block-end-color: lime;
}
.supported::marker {
content: '\2713';
}
.unsupported {
border-block-end-color: red;
}
.unsupported::marker {
content: '\2717';
}
<form action="#" method="post">
<fieldset>
<legend>Does your browser support..?</legend>
<label>
<span>Enter a selector to test</span>
<input type="text" id="testSelector">
</label>
<button type="button">Check your browser</button>
</fieldset>
<ul id="results"></ul>
</form>
JS Fiddle demo.
References:
Arrow functions.
CSS.supports().
document.create().
document.querySelector().
document.querySelectorAll().
Element.classList API.
Element.prepend().
Element.querySelector().
Element.querySelectorAll().
Event.preventDefault().
EventTarget.addEventListener().
Template literals.
I have "contenteditable" div element. I want to set a watermark for it so that when user tries to write something in the div the watermark should go disappear.
I tried some watermark jQuery plugins, all work for input, textarea. What is the way to implement this feature for contenteditable div?
If you by "watermark" mean like a placeholder effect, the concept should be fairly simple:
var mark = 'Watermark',
edited = false;
$('[contenteditable]').focus(function() {
if(!edited) {
$(this).empty();
}
}).blur(function() {
if(!$(this).html()) {
$(this).html(mark);
}
}).keyup(function() {
edited = true;
}).text(mark);
Demo: http://jsfiddle.net/jjxvR/1/
Here's my answer to another question:
It uses a combination of jQuery and CSS3. Works exactly like the html5 placeholder attribute!.
Hides itself right away when you input the first letter
Shows itself again when you delete what you input into it
HTML:
<div class="placeholder" contenteditable="true"></div>
CSS3:
.placeholder:after {
content: "Your placeholder"; /* this is where you assign the place holder */
position: absolute;
top: 10px;
color: #a9a9a9;
}
jQuery:
$('.placeholder').on('input', function(){
if ($(this).text().length > 0) {
$(this).removeClass('placeholder');
} else {
$(this).addClass('placeholder');
}
});
DEMO: http://jsfiddle.net/Tomer123/D78X7/
I solved it this way:
div[contenteditable]:empty:before {
content: '-';
}
div[contenteditable]:focus:before {
color: transparent;
}
I have been trying to ask this before, without any luck of explaining/proving a working example where the bug happens. So here is another try:
I’m trying to replicate a placeholder effect on a contenteditable DIV. The core concept is simple:
<div contenteditable><em>Edit me</em></div>
<script>
$('div').focus(function() {
$(this).empty();
});
</script>
This can sometomes work, but if the placeholder contains HTML, or if there some other processing being made, the editable DIV’s text caret is being removed, and the user must re-click the editable DIV to be able to start typing (even if it’s still in focus):
Example: http://jsfiddle.net/hHLXr/6/
I can’t use a focus trigger in the handler, since it will create an event loop. So I need a way to re-set the caret cursor in the editable DIV, or in some other way re-focus.
Here is a CSS only solution augmenting some of the other answers:-
<div contentEditable=true data-ph="My Placeholder String"></div>
<style>
[contentEditable=true]:empty:not(:focus)::before{
content:attr(data-ph)
}
</style>
EDIT: Here is my snippet on codepen -> http://codepen.io/mrmoje/pen/lkLez
EDIT2: Be advised, this method doesn't work 100% for multi-line applications due to residual <br> elements being present in the div after performing a select-all-cut or select-all-delete on all lines. Credits:- #vsync
Backspace seems to work fine (at least on webkit/blink)
I've just published a plugin for this.
It uses a combination of CSS3 and JavaScript to show the placeholder without adding to the content of the div:
HTML:
<div contenteditable='true' data-placeholder='Enter some text'></div>
CSS:
div[data-placeholder]:not(:focus):not([data-div-placeholder-content]):before {
content: attr(data-placeholder);
float: left;
margin-left: 5px;
color: gray;
}
JS:
(function ($) {
$('div[data-placeholder]').on('keydown keypress input', function() {
if (this.textContent) {
this.dataset.divPlaceholderContent = 'true';
}
else {
delete(this.dataset.divPlaceholderContent);
}
});
})(jQuery);
And that's it.
You may need to manually update the selection. In IE, the focus event is too late, so I would suggest using the activate event instead. Here's some code that does the job in all major browsers, including IE <= 8 (which a CSS-only alternative will not):
Live demo: http://jsfiddle.net/hHLXr/12/
Code:
$('div').on('activate', function() {
$(this).empty();
var range, sel;
if ( (sel = document.selection) && document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(this);
range.select();
}
});
$('div').focus(function() {
if (this.hasChildNodes() && document.createRange && window.getSelection) {
$(this).empty();
var range = document.createRange();
range.selectNodeContents(this);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
});
just use css pseudo-classes.
span.spanclass:empty:before {content:"placeholder";}
I found that the best way to do this is to use the placeholder attribute like usual and add a few lines of CSS.
HTML
<div contenteditable placeholder="I am a placeholder"></div>
CSS
[contenteditable][placeholder]:empty:before {
content: attr(placeholder);
color: #bababa;
}
Note: the CSS :empty selector only works if there is literally nothing in-between the opening and closing tag. This includes new lines, tabs, empty space, etc.
Codepen
All you need is this little solution
[contenteditable=true]:empty:before{
content: attr(placeholder);
display: block; /* For Firefox */
}
Demo: http://codepen.io/flesler/pen/AEIFc
Here's my way:
It uses a combination of jQuery and CSS3. Works exactly like the html5 placeholder attribute!.
Hides itself right away when you input the first letter
Shows itself again when you delete what you input into it
HTML:
<div class="placeholder" contenteditable="true"></div>
CSS3:
.placeholder:after {
content: "Your placeholder"; /* this is where you assign the place holder */
position: absolute;
top: 10px;
color: #a9a9a9;
}
jQuery:
$('.placeholder').on('input', function(){
if ($(this).text().length > 0) {
$(this).removeClass('placeholder');
} else {
$(this).addClass('placeholder');
}
});
DEMO: http://jsfiddle.net/Tomer123/D78X7/
Here's the fix that I used.
<div contenteditable><em>Edit me</em></div>
<script>
$('div').focus(function() {
var target = $(this);
window.setTimeout(function() { target.empty(); }, 10);
});
</script>
I developed a jQuery plug-in for this. Take a look https://github.com/phitha/editableDiv
var curText = 'Edit me';
$('div').focusin(function() {
if ($(this).text().toLowerCase() == curText.toLowerCase() || !$(this).text().length) {
$(this).empty();
}
}).focusout(function() {
if ($(this).text().toLowerCase() == curText.toLowerCase() || !$(this).text().length) {
$(this).html('<em>' + curText + '</em>');
}
});
This is not exact solution of your problem ..
in summernote options set
airMode:true
placeholder works in this way.
In .css
.holder:before {
content: attr(placeholder);
color: lightgray;
display: block;
position:absolute;
font-family: "Campton", sans-serif;
}
in js.
clickedOnInput:boolean = false;
charactorCount:number = 0;
let charCount = document.getElementsByClassName('edit-box')[0];
if(charCount){
this.charactorCount = charCount.innerText.length;
}
if(charactorCount > 0 && clickedOnInput){
document.getElementById("MyConteditableElement").classList.add('holder');
}
if(charactorCount == 0 && !clickedOnInput){
document.getElementById("MyConteditableElement").classList.remove('holder');
}
getContent(innerText){
this.clickedOnInput = false;
}
In .html
<div placeholder="Write your message.." id="MyConteditableElement" onclick="clickedOnInput = true;" contenteditable class="form-control edit-box"></div>
this solution worked for me in angular project