Reputation: 1166
How can I change this code so it detects whether a line inside contenteditable div is empty of has text?
$('#area').on("keyup change", function() {
if( this.value.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
&& this.value.substr(this.selectionStart).match(/^(?:\s+|$)/)) {
console.log("empty");
} else {
console.log("has stuff");
}
});
works the way it should with textarea. I tried to replace VALUE with innerHTML - alas! with no luck.
UPDATE: what I am looking for is to find out if A SEPARATE LINE is empty. For example - try to add several lines and then delete any line using backspace. Deleting one symbol by one - when there are no more symbols on the line - script should return "empty". Example:
Upvotes: 0
Views: 549
Reputation: 11859
with your code(added mouseover
to get div status on mouseover) using innerHTML:
$('#area').on("keyup change mouseover", function() {
if( this.innerHTML.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
&& this.innerHTML.substr(this.selectionStart).match(/^(?:\s+|$)/)){
console.log("empty");
} else {
console.log("has stuff");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div name="" id="area" style="width:100px;height:100px;border:1px solid black;" contenteditable=true></div>
With mouseover
and get the data using innerHTML.
$('#area').mouseover( function() {
if( this.innerHTML.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
&& this.innerHTML.substr(this.selectionStart).match(/^(?:\s+|$)/)) {
console.log("empty");
} else {
console.log("has stuff");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div name="" id="area" style="width:100px;height:100px;border:1px solid black;" contenteditable=true></div>
Upvotes: 2
Reputation: 1105
You need to change the .value to .textContent.
$('#area').on("keyup change", function() {
if( this.textContent.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
&& this.textContent.substr(this.selectionStart).match(/^(?:\s+|$)/)){
console.log("empty");
} else {
console.log("has stuff");
}
});
and change the textarea to div if I understood you correctly.
<div name="" id="area" cols="30" rows="10" contenteditable=true></div>
Upvotes: 2