I need to delete all children of a div after clicking enter.
There is a div and event listener below.
<div id = "area" contenteditable="true"></div>
document.onreadystatechange = function(){
if(document.readyState == 'complete'){
document.getElementById("area").addEventListener("keypress" , public_mode);
}
function public_mode(){
var key = window.event.keyCode;
if (key == 13) {
sendMessage();
}
}
function sendMessage(){
var area = document.getElementById("area");
while (area.firstChild) {
area.removeChild(area.firstChild);
}
}
As you can see the contenteditable elements is added an element in according with clicking enter - it depends on browser what element will be added.In my case I use chrome and here are inserted div.
So, the result after clicking enter on the area but without removing
<div id = "area" contenteditable = "true">
Sckoriy
<div></div>
</div>
and , with removing
<div id = "area" contenteditable = "true">
<div></div>
<div></div>
</div>
But , the needed result is
<div id = "area" contenteditable = "true">
//Empty
</div>
The code mostly works, however there were two main issues.
keyCode is deprecated. you should be using key which turns the syntax of searching for a key into looking for a string. This means instead of 13 you just check to see if key is Enter.
Secondly you need to pass the event to your public_mode function so that you can read the key that has been pressed when the event occurs. You also need to use preventDefault to prevent it from adding a new line after removing everything from the original contentEditable area when it does detect Enter
document.onreadystatechange = function() {
if (document.readyState == 'complete') {
document.getElementById("area").addEventListener("keypress", public_mode);
}
function public_mode(event) {
var key = event.key;
if (key === "Enter") {
event.preventDefault();
sendMessage();
}
}
function sendMessage() {
var area = document.getElementById("area");
while (area.firstChild) area.removeChild(area.firstChild);
}
}
#area {
min-width: 100vw;
border: 1px solid black;
}
<div id="area" contenteditable="true"></div>
You could just set the innerHTML proprety to an empty string;
area.innerHTML = '';
target the dom by id
var s = document.getElementById("area");
save the number of childrens
var num = s.children.length;
and remove the num of childs of element
for(var i=0;i<num;i++){
s.children[0].remove()
}
and inner for some thext
s.innerHTML = "";
Pass the key event as an argument to your function.
Also, if you do not want the newline entered in your div, you can prevent the event from continuing with event.preventDefault().
document.onreadystatechange = function() {
if (document.readyState == 'complete') {
const area = document.getElementById('area')
area.addEventListener('keypress', public_mode);
area.focus();
}
}
function public_mode(event) {
if (window.event.keyCode == 13) {
sendMessage();
event.preventDefault();
}
}
function sendMessage() {
const area = document.getElementById('area');
while (area.firstChild) {
area.removeChild(area.firstChild);
}
}
<div id="area" contenteditable="true">Press Enter to erase me!</div>
Related
everyone. I got some problems when I wanna accomplish a drop-down box in a HTML website without using select and option elements, instead of using and elements.
The main function is made up by two parts, the first function is when clicked the first elements in the drop-down box, the hidden parts of list shows up and hide clicked again. The second function is when choose the elements in the hidden list, the text of the elements on the list will replace the first element on the drop-down box.
I have accomplished first function using below codes:
// javascript codes
var searchListBtn = document.getElementById("btn_List");
var a_searchListBtn = document.getElementById("btn_List").getElementsByTagName("a");
function show(event) {
let oevent = event || window.event;
if (document.all) {
oevent.cancelBubble = true;
}
else {
oevent.stopPropagation();
}
// click it to show it, click again to hide it and loop
if (searchListBtn.style.display === "none" || searchListBtn.style.display === "") {
searchListBtn.style.display = "block";
}
else {
searchListBtn.style.display = "none";
}
}
document.onclick = function() {
searchListBtn.style.display = "none";
}
searchListBtn.onclick = function (event) {
let oevent = event || window.event;
oevent.stopPropagation();
}
<!-- html codes -->
<html>
<body>
<div>
<div class="ui-search-selected" onclick="show();">A</div>
<div class="ui-search-selected-list" id="btn_List">
B
C
D
</div>
</div>
</body>
</html>
But when I did the second part, my idea was not clear enough to implement that, I searched if I use select>option elements I could use selectedIndex method to find the index of list, but this is a custom drop-down box formed by div>a structure elements.
I tried to console.log(a_searchListBtn) and show an array from the console, and I could use a_searchListBtn[0~3].text to get the value of B/C/D.
I tried to write codes like below:
a_searchListBtn.onclick = function() {
console.log("Clicked.")
}
But nothing in the console, so, is there anyone could apply some help, thx in advance.
Well you're fetching all the a elements using getElementsByTagName("a"). Now you just need to loop through the results and add a click event listener that will take the innerHTML of that a element and put it into the innerHTML of the ui-search-selected div.
You don't need an index. You can access the clicked element's innerHTML using event.target. See it working in this snippet below:
// javascript codes
var searchListBtn = document.getElementById("btn_List");
var uiSearchSelected = document.getElementById("ui-search-selected");
var a_searchListBtn = document.getElementById("btn_List").getElementsByTagName("a");
for (button of a_searchListBtn) {
button.addEventListener("click", replace);
}
function show(event) {
let oevent = event || window.event;
if (document.all) {
oevent.cancelBubble = true;
}
else {
oevent.stopPropagation();
}
// click it to show it, click again to hide it and loop
if (searchListBtn.style.display === "none" || searchListBtn.style.display === "") {
searchListBtn.style.display = "block";
}
else {
searchListBtn.style.display = "none";
}
}
document.onclick = function() {
searchListBtn.style.display = "none";
}
searchListBtn.onclick = function (event) {
let oevent = event || window.event;
oevent.stopPropagation();
}
function replace(event) {
if (!event) return;
uiSearchSelected.innerHTML = event.target.innerHTML
}
<!-- html codes -->
<html>
<body>
<div>
<div id="ui-search-selected" onclick="show();">A</div>
<div class="ui-search-selected-list" id="btn_List">
B
C
D
</div>
</div>
</body>
</html>
I have tried to use this codes to implement this funtion, it works.
// javascript
var par_searchListBtn = document.getElementById("btn_list_parent");
var searchListBtn = document.getElementById("btn_List");
var a_searchListBtn = document.getElementById("btn_List").getElementsByTagName("a");
// console.log(a_searchListBtn.length);
// console.log(a_searchListBtn);
function show(event) {
let oevent = event || window.event;
if (document.all) {
oevent.cancelBubble = true;
}
else {
oevent.stopPropagation();
}
if (searchListBtn.style.display === "none" || searchListBtn.style.display === "") {
searchListBtn.style.display = "block";
}
else {
searchListBtn.style.display = "none";
}
}
document.onclick = function() {
searchListBtn.style.display = "none";
}
searchListBtn.onclick = function (event) {
let oevent = event || window.event;
oevent.stopPropagation();
}
for(var i = 0; i < a_searchListBtn.length; i++){
a_searchListBtn[i].onclick = function () {
par_searchListBtn.innerHTML = this.innerText;
//searchListBtn.style.display = "none";
}
}
<!-- html codes -->
<html>
<body>
<div>
<div class="ui-search-selected" id="btn_list_parent" onclick="show();">A</div>
<div class="ui-search-selected-list" id="btn_List">
B
C
D
</div>
</div>
</body>
</html>
I want to interrupt the Enter key and stop it from injecting the html code into the ContentEditable div. My current code does not work because it does not interrupt the Enter key. However, if I type, press enter, then type again, it deletes the inner html elements. But still, this is not what I want. I want the elements to NOT go into the ContentEditable div to begin with when I press enter rather than having to strip them out.
I am essentially using this as an "input that scales with its content". If there is a better way to do this, please let me know!
import ReactDOM from 'react-dom'
export default class MyInput extends React.Component {
componentWillReceiveProps(nextProps) {
this.setState({value: nextProps.html});
}
shouldComponentUpdate(nextProps){
return nextProps.html !== ReactDOM.findDOMNode(this).innerHTML;
}
componentDidUpdate() {
if ( this.htmlEl && this.props.html !== this.htmlEl.innerHTML ) {
this.htmlEl.innerHTML = this.props.html;
}
}
emitChange(){
var html = ReactDOM.findDOMNode(this).innerHTML;
// regex to remove tags created after pressing enter
value = value.replace(/<div>/g, '');
value = value.replace(/<\/div>/g, '');
value = value.replace(/<br>/g, '');
if (this.props.onChange && html !== this.lastHtml) {
this.props.onChange(html);
}
this.lastHtml = html;
this.forceUpdate();
}
render() {
var html = this.state.value;
return (
<div
dangerouslySetInnerHTML={{__html: html}}
onInput={this.emitChange.bind(this)}
onBlur={this.emitChange.bind(this)}
contentEditable
></div>
)
}
};<kbd>
// function handler inside class declaration
keyPress(event) {
if(event.charCode == 13) {
event.preventDefault()
}
}
// in render function
<div
dangerouslySetInnerHTML={{__html: html}}
onInput={this.emitChange.bind(this)}
onBlur={this.emitChange.bind(this)}
onKeyPress={this.keyPress.bind(this)}
contentEditable
></div>
bind you div with a keyboard event and then:
var keyCode = event.which || event.keyCode;
keyCode === 13 && event.preventDefault();
I am trying to toggle a div so it shows and hides when a user enters text into textarea.
i am using the below code and its not working for me, can anyone please show me why? thanks
html:
<head>
<script>
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val() > 8) {
$('#cname2').toggle("slow");
}
});
});
</script>
</head>
<form>
<input type="text" id="cname" name="cname" class="field">
<div id="cname2"></div>
</form>
css:
#cname2{
width:30px;
height:30px;
position:absolute;
margin-top:-13px;
margin-left:400px;
background-image: url('tick.png');
background-repeat:no-repeat;
background-position:right;
display:none;
}
so apparently my above code doesnt work in IE 9, but i should be able to achieve what i am trying to do by using this code, but can someone please show me where i place my div ID/how i adapt it to work for me?
var activeElement = null;
var activeElementValue = null;
// On focus, start watching the element
document.addEventListener("focusin", function(e) {
var target = e.srcElement;
if (target.nodeName !== "INPUT") return;
// Store a reference to the focused element and its current value
activeElement = target;
activeElementValue = target.value;
// Listen to the propertychange event
activeElement.attachEvent("onpropertychange", handlePropertyChange);
// Override .value to track changes from JavaScript
var valueProp = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype, 'value');
Object.defineProperty(activeElement, {
get: function() { return valueProp.get.call(this); },
set: function(val) {
activeElementValue = val;
valueProp.set.call(this, val);
}
});
});
// And on blur, stop watching
document.addEventListener("focusout", function(e) {
if (!activeElement) return;
// Stop listening to propertychange and restore the original .value prop
activeElement.detachEvent("onpropertychange", handlePropertyChange);
delete activeElement.value;
activeElement = null;
activeElementValue = null;
});
function handlePropertyChange(e) {
if (e.propertyName === "value" &&
activeElementValue !== activeElement.value) {
activeElementValue = activeElement.value;
// Fire textchange event on activeElement
}
};
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val().length > 8) {
$('#cname2').show();
} else {
$('#cname2').hide();
}
});
});
One possible approach (demo):
$(document).ready(function() {
$("#cname").on('input', function() {
$('#cname2')[this.value.length > 8 ? 'hide' : 'show']('slow');
});
});
Here I assumed that in cname2 container there's some warning message, that has to be shown if length of text input is 8 or less characters. Note also that I've used oninput handler, not keyup: as it allows me to process mouse-driven cut-and-paste as well as direct input. The only drawback is that IE8 doesn't support this event (and IE9 support for it is rather buggy, as handler is not fired when character is removed from text input).
Use this Javascript function
var z = document.getElementById('cname');
z.onkeyup = function(){
document.getElementById('cname2').innerHTML = z.value;
}
Your HTML:
<input type='text' name='cname' class='field' id='cname'>
<div class='cname2' id='cname2'></div>
Checkout here: http://jsfiddle.net/iamsajeev/Q9LPv/
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val() > 8) {
$('#cname2').fadeIn("slow");
}
else
{
$('#cname2').fadeOut("slow");
}
});
});
http://jsfiddle.net/5EjP7/2/
I hope that helps
Try the following script:
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val().length > 8) {
$('#cname2').toggle("slow");
}
});
});
I need help with duplicating div when enter is hit while the input element in the div is in focus
so there is a div which has an input element in it. I need to duplicate this div and place it right below the existing div whenever enter is hit while the cursor is in the input element.
Solutions which don't use jquery will be of great help.
Thanks
Here is a high level overview...
Listen for keypress event on the input element, for keyCode of 13.
Use cloneNode() to clone the node.
Use the most appropriate node insertion method, such as appendChild() to insert the cloned element.
try this
Demo
<div id='container'>
<div id='div1'>
<input type='text' onkeyup='clone_element(event)' />
</div>
</div>
<script>
function clone_element(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if(charCode == 13){
var cDiv = document.getElementById("div1");
var clonedDiv = cDiv.cloneNode (true);
clonedDiv.id = "";
var container = document.getElementById ("container");
container.appendChild(clonedDiv);
}
}
</script>
You can use the below function to clone the div. This is likely to be the solution Alex mentioned. I have added the code.
function cloning(divid) {
var container = document.getElementById(divid);
var clone = document.getElementById('div_0').cloneNode(true);
clone.setAttribute('id','div_'+document.getElementById(divid).getElementsByTagName('div').length);
container.appendChild (clone);
}
call the above function when you hit enter.
<script language = "javascript">
function searchKeyPress(e)
{
// look for window.event in case event isn't passed in
if (typeof e == 'undefined' && window.event) { e = window.event; }
if (e.keyCode == 13)
{
alert("Enter received");
cloning('divid');
}
}
</script>
<input type="text" onkeydown="searchKeyPress()">
I have a container on a page that should be prepared for focusing, i.e. when user pressed TAB button, the first active element in the container must be focused.
The simplest way I have thought so far is to find the last active element before the container, focus it and then blur it. Will it work? Is there a simpler way? How to find the last active element before the container (cross-browser)?
I do not want to change tabbed elements order, I just want to define the next element that will be selected.
Please use raw javascript, not frameworks.
The only thing I can think of is looping over the container child nodes and try focusing them until you succeed:
<script type="text/javascript">
document.onkeyup = function (e) {
if (!e)
e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
FocusFirst(document.getElementById("MyContainer"));
}
}
function FocusFirst(element) {
try {
element.focus();
}
catch(ex) {}
if (document.activeElement == element)
return true;
for (var i = 0; i < element.childNodes.length; i++) {
var oChild = element.childNodes[i];
if (FocusFirst(oChild))
return true;
}
return false;
}
</script>
Sample HTML tested with: (IE, Chrome)
<div id="MyContainer">
<div>hello</div>
<div><span><input type="text" /></span></div>
<div><input type="text" /></div>
</div>
This will focus the first input box of the container upon tab click.
Add a listener to the document and change focus onKeyUp. Remove the listener once tab has been pressed:
document.onkeyup = onKeyEvent;
function onKeyEvent (e) {
if (e.keyCode == 9) {
document.onkeyup = null;
document.getElementById ('whatever').focus();
}
}
Here is the solution that I've used finally.
I just create fake empty link in the beginnig of the container and focus it. The link will be removed when it lose focus.
function prefocusElement(node)
{
var fake = document.createElement("a");
fake.setAttribute("href", "#");
node.insertBefore(fake, node.firstChild);
fake.focus();
fake.addEventListener("blur", function(e) { node.removeChild(fake); }, false);
};