Watermark for contenteditable div element - javascript

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;
}

Related

Adding an event listener on load for floating label

On page reloads I have floating labels overlapping the input text if the form has been filled out before. To avoid this problem I want to alter the input text's style if there is data in the form.
Here is my code:
https://codepen.io/holly-williford/pen/pONYYM
document.getElementsByClassName("floating").addEventListener("load", hideLabel);
function hideLabel() {
if(!$('input').val() ) {
$('floating').addClass('warning');
} else {
}
}
<label class="floating">Test</label>
<input></input>
warning {
color: red;
}
There are many things from the codepen example that need changes.
HTML
<label class="floating">Test</label>
<input> <!-- You should have a proper html tag -->
CSS
.warning { //Notice the '.'
color: red;
}
JS
window.onload = hideLabel;
function hideLabel() {
if(!$('input').val() ) {
$('.floating').addClass('warning'); // Notice the '.'
} else {
}
}
These modifications should help you get started.
But, you have mentioned jQuery and you don't seem to make the most of it.

Adding 'placeholder' text to an element using JS

-
There are a few posts on this already (like this one) but they're not really adaptable to this situation.
I have a shortcode that dynamically generates text content based on a custom field in my CRM, this is used to display a users serial number for their software, shown below:
The direct parent container for the serial number is #copyTarget2.
When the container is empty it is still rendered on the page but with no content, shown here:
I need to populate the empty container with 'placeholder' text, but not the kind that you can type over, just so that there is text visible that just reads - 'No active serial number.'
Lastly, when the field is populated, the placeholder text needs to be hidden, it doesn't really matter how it's hidden so long as it's not visible and doesn't affect the text generated by the shortcode.
I also tried to adapt this JS Fiddle: http://jsfiddle.net/davidThomas/LAfN2/
From:
$('input:text').each(
function(i,el) {
if (!el.value || el.value == '') {
el.placeholder = 'placeholdertext';
/* or:
el.placeholder = $('label[for=' + el.id + ']').text();
*/
}
});
To:
jQuery('#copyTarget2').each(
function(i,el) {
if (!el.value || el.value == '') {
el.placeholder = 'No valid serial number.';
/* or:
el.placeholder = $('label[for=' + el.id + ']').text();
*/
}
});
CSS and HTML are like second languages to me but I'm new to JS so I can modify code a little but I can't write it (yet), I'm wondering what the best JS solution would be to achieve this and why?
Using :empty and :before with attribute to set the placeholder when it is empty.
[data-placeholder]:empty:before {
color: #AAA;
content: attr(data-placeholder);
}
<span data-placeholder="My placeholder"></span>
<br/>
<span data-placeholder="My placeholder">I have text</span>
I think you need a effect like placeholder in the span element not the input tag .Try with some css .see the below snippet .And add the attribute using attr() of jquery function
see the CSS content
jQuery('#copyTarget2').each(
function(i, el) {
if (!$(el).text() || $(el).text().trim() == '') {
$(el).attr('placeholder', 'No valid serial number.')
/* or:
el.placeholder = $('label[for=' + el.id + ']').text();
*/
}
});
span:empty:before {
font-size: 12;
color: #9E9E9E;
line-height: 40px;
text-indent: 20px;
content: attr(placeholder);
display: block;
border: 1px solid grey;
}
span{
position:absolute;/*or fix as your wish with respect to parent element*/
width:200px;/*or fix as your wish with respect to parent element*/
height:50px;/*or fix as your wish with respect to parent element*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="copyTarget2"></span>

Get a word under cursor and output a corresponding translation using JavaScript

I want to implement a kana-helper into my website: When the user hovers over a kana (japanese character) it shall output the right translation.
I have found this: How to get a word under cursor using JavaScript?
jsfiddle
html:
<p>Each word will be wrapped in a span.</p>
<p>A second paragraph here.</p>
Word: <span id="word"></span>
js:
// wrap words in spans
$('p').each(function() {
var $this = $(this);
$this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
});
// bind to each span
$('p span').hover(
function() { $('#word').text($(this).css('background-color','#ffff66').text()); },
function() { $('#word').text(''); $(this).css('background-color',''); }
);
but i am a very beginner in JavaScript and i am not able to rewrite it to my needs.
I do not need to automatically set spans, I will do it manually.
For example I have this:
<span id="sho">しょ</span><span id="ha">は</span><span id="n">ん</span>
When the mouse hovers over one of these characters I want to display a translation of it at a fixed position on the page:
しょ = "sho"
は = "ha" or particle "wa"
ん = "n"
(one at a time)
You can just use the ::before pseudo-selector to do it. No JavaScript required.
.kana {
position: relative;
}
.kana:hover {
color: blue;
}
.kana:hover::before {
position: absolute;
content: attr(romaji);
top: 1em;
color: blue;
}
<span class="kana" romaji="sho">しょ</span><span class="kana" romaji="ha">は</span><span class="kana" romaji="n">ん</span>
I've taken the liberty to use a data-*-attribute as there should not be more than one element with the same id on a page.
// bind to each span
$('#raw span').hover(
function() { $('#translation').text($(this).css('background-color','#ffff66').data('translation')); },
function() { $('#translation').text(''); $(this).css('background-color',''); }
);
#translation {
font-weight: 700;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="raw">
<span data-translation="sho">しょ</span><span data-translation="ha">は</span><span data-translation="n">ん</span>
</div>
Translation: <span id="translation"></span>

jquery/javascript - how to "undo" a click event using if statement?

The below code takes into account different tags and turns the background red if the tag is clicked on. I want to code it so that if it is clicked on again, it changes back from red and 'deletes' the background, or at least set it to null. I have tried an if statement to no avail. I know that I can just make another click event that changes the background to white, but this is for experimental purposes and i was wondering if this CAN be done with if statements. thanks to ya.
<script>
$(document).ready(function() {
$("p, h1").click(function() {
$(this).css("background-color", "red");
if ($(this).css("background-color", "red")) {
$(this).css("background-color", "null");
}
});
});
</script>
First you need to use the getter version of .css() like
if($(this).css("background-color") == "red"){
but it still won't work because, the css getter will return a rgb format value and will return non consistent values across browsers.
So the solution is to use a css based solution using toggleClass()
.red {
background-color: red;
}
then
$(document).ready(function() {
$("p, h1").click(function() {
$(this).toggleClass("red");
});
});
Demo: Fiddle
$('p, h1').click(function() {
var $this = $(this);
var altColor = $this.data('altColor');
$this.css('background-color', altColor ? '' : 'red');
$this.data('altColor', ! altColor);
});
This answers your question, but you should really be using a CSS class for this.
This is easily done using CSS, and is a bit more straight forward. If you create a CSS class for the click, then you can just toggle it on/off each time the item is clicked:
CSS
p, h1 {
background-color: none;
}
p.red, p.h1 {
background-color: red;
}
JavaScript:
$('p, h1').click(function() {
$(this).toggleClass('red');
});

Placeholder in contenteditable - focus event issue

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

Categories

Resources