I have a <label> with an ::after pseudo-element attached to it, to which I would like to bind a click event.
<label for="my-input">
<input id="my-input" />
</label>
Since pseudo-elements are not part of the DOM, I obviously can't do that, so I have bound the click event to the <label> instead.
But... we all know what a <label> does, right? Yes, it re-focuses the cursor on the <input>.
So, well done if you've already guessed what happens - the event fires twice.
Why? Because it fires once when the user clicks on the <label> and then the browser auto-clicks on the <input> (to re-position the cursor) and that ends up firing the event a second time.
I'd be intrigued to know if there is any creative way around this.
Normally, you'd stop the event firing during the bubbling phase by changing the useCapture boolean flag at the end of .addEventListener() from false to true - but in this case that's not going to stop the event (bound to the <label>) from firing a second time, when the browser auto-clicks on the <input>.
Working Example:
var myInput = document.querySelector('label[for="my-input"]');
var clickNumber = 1;
function clickDetected(event) {
console.log('Click ' + clickNumber + ' detected');
clickNumber++;
}
myInput.addEventListener('click', clickDetected, false);
label {
position: relative;
top: 48px;
width: 200px;
height: 100px;
margin: 24px 6px;
padding: 24px;
background-color: rgb(255, 0, 0);
}
label[for="my-input"]::after {
content: '+';
position: absolute;
display: block;
top: -26px;
right: 4px;
width: 22px;
height: 22px;
color: rgb(255, 255, 255);
font-size: 21px;
line-height: 22px;
font-weight: bold;
text-align: center;
background-color: rgb(255, 0, 0);
border-radius: 2px;
box-shadow: 3px 3px 3px rgba(0, 75, 165, 0.4);
cursor: pointer;
}
<label for="my-input">
<input id="my-input" type="text" />
</label>
Do it like this:
var myInput = document.querySelector('label[for="my-input"]');
var clickNumber = 1;
function clickDetected(e) {
}
myInput.onclick = function (e) {
if (e.target.getAttribute('id') === 'label') {
console.log('Click ' + clickNumber + ' detected');
clickNumber++;
}
}
label {
position: relative;
top: 24px;
width: 200px;
height: 100px;
margin: 24px 6px;
padding: 24px;
background-color: rgb(255, 0, 0);
}
<label for="my-input" id="label">
<input id="my-input" type="text" />
</label>
Related
I have a modal that when I open it, it detects a single click, until there everything is correct, the problem is when I close it and open it again, it begins to detect a double event (click) and if I close and open it again detects 3 events (clicks), it is made in vanilla js
HTML:
<div id="modal-container-gestion-documental" class="modal-container-gestion-documental">
<div class="modal-gestion-documental">
<div class="cabecera-modal">
<h3 class="">GestiĆ³n Documental</h3>
CERRAR
</div>
<br>
<div class="div-padre-gestor">
</div>
</div>
</div>
Javascript:
const modalContainerGestionDocumental = document.getElementById(
"modal-container-gestion-documental"
);
document.addEventListener("click", (e) => {
if (e.target.matches(".abrir-gestion-documental")) {
e.preventDefault();
modalContainerGestionDocumental.classList.add("show-modal");
}
if (e.target.matches(".cerrar-gestion-documental")) {
e.preventDefault();
modalContainerGestionDocumental.classList.remove("show-modal");
}
}
Css:
.modal-container-gestion-documental {
z-index: 2;
margin: 0 auto;
display: flex;
background-color: rgba(0, 0, 0, 0.3);
align-items: center;
justify-content: center;
position: fixed;
pointer-events: none;
top: 0;
left: 0;
height: 100vh;
width: 100vw;
opacity: 0;
}
.modal-gestion-documental{
margin-top: 75px;
padding: 3rem;
background-color: #fff;
width: 85%;
height: 88%;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.show-modal {
pointer-events: auto;
opacity: 1;
}
Depends on where you have this document.addEventListener("click.. part of the code. Based on your description, it seems like that listener is being triggered every time the modal opens/closes.
Make sure to get the listener to be triggered only once on page load. If it's unavoidable, you can removeEventListener whenever the modal closes.
I have a drop down menu I need to make appear and disappear using pure JavaScript (no libraries/jQuery). Thus I am developing a toggle function. However despite trying several approaches, nothing seems to work. My current idea is to create a variable to hold the state of the menu (open or closed). Once the display of the menu changes from "none" to "block", the variable should change from "closed" to "open". Then an event listener would be added to the body element so when anything is clicked, the menu closes (i.e. the display property is changed back to "none").
Unfortunately the above doesn't seem work. When I put the If/else block outside of an event listener it fires when the page loads, but not when the menuToggle variable changes. If I put it or a function inside the menuPlaceholder event listener the menu won't open, probably due to the open and close code being called basically at the same time.
Clearly I am missing something, probably related to program control or function calling. Does anyone have any insights?
The code I am working with is below. Note the alert functions peppered throughout the code are for testing purposes only.
//Puts IDs for search preference selection box into variables
var menuPlaceholder = document.getElementById('searchSelection');
var menuDisplay = document.getElementById('searchOptions');
var boxLabel = document.getElementById('searchLabel');
//Puts IDs for text input box and submission into variables
var searchBoxPlaceholder = document.getElementById('searchInput');
var searchInput = document.getElementById('searchBox');
var submitButton = document.getElementById('submit');
//Adds class to each search option and puts ID of hidde field into variable
var searchPrefSubmission = document.getElementsByClassName('buttonSearch');
var hiddenInput = document.getElementById('searchChoice');
//Global variable to indicate whether searchOptions menu is opened or closed
var menuToggle = "closed";
//Closes element when one clicks outside of it.
function hideOnClickOutside(element) {
const outsideClickListener = event => {
if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
element.style.display = 'none'
removeClickListener()
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener)
}
document.addEventListener('click', outsideClickListener)
}
const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length )
//When the placeholder box is clicked, the option menu appears
menuPlaceholder.addEventListener('click', function (event){
menuDisplay.style.display = "block";
menuToggle = "open";
//Add click event to searchPref buttons
for (i = 0; i < searchPrefSubmission.length; i++) {
//Assigns value of the button to both the hidden input field and the placeholder box
searchPrefSubmission[i].addEventListener('click', function(event) {
hiddenInput.value=this.value;
boxLabel.innerHTML = this.value;
menuDisplay.style.display = "none";
menuPlaceholder.style.display = "inline-block";
});
}
});
//This code causes the text input box of the search form to appear when the background box is clicked
searchBoxPlaceholder.addEventListener('click', function(event){
searchInput.style.display = "inline";
submitButton.style.display = "inline";
//hideOnClickOutside(menuDisplay);
});
if (menuToggle == "open"){
document.body.addEventListener('click', function(event){
alert('Foo!');
})
}else{
alert('Boo!');
}
/*function toggleMenu () {
//menuDisplay.style.display = "none";
alert('Boo!');
menuToggle = "closed";
}*/
body {
font-family:Montserrat, sans-serif;
}
#searchOptionPlaceholder {
display: inline-block;
}
#searchSelection {
padding: 10px 20px;
margin-right: 10px;
background-color: #F0F3F5;
display: inline-block;
color: #000000;
width: 140px;
max-width: 200px;
max-height: 35px;
border: 2px solid black;
vertical-align: middle;
}
#searchSelection img {
float: right;
}
#searchLabel {
display: inline-block;
padding-top: 10px;
vertical-align: top;
}
#searchOptions {
display: none;
background-color: #F0F3F5;
position: absolute;
z-index: 2;
}
#searchOptions ul {
background-color: #F0F3F5;
padding: 5px;
}
#searchOptions li {
list-style-type: none;
border-bottom: 2px solid black;
}
#searchOptions li:hover {
background-color: #706868;
color: #ffffff;
}
.buttonSearch {
background-color: transparent;
border: none;
padding: 10px;
font-size: 14px;
}
.searchSubHeading {
font-size: 12px;
}
#searchInput {
display: inline-block;
background-color: #F0F3F5;
padding: 10px 100px;
position: relative;
top: 0px;
max-width: 350px;
border: 2px solid black;
vertical-align: middle;
}
#searchInput img {
position: relative;
left: 80px;
}
#searchBox {
display: none;
width: 80%;
background-color: #F0F3F5;
border: none;
font-size: 1.5em;
position: relative;
right: 50px;
vertical-align: middle;
}
#submit {
border: none;
background-image: url('https://library.domains.skidmore.edu/search/magnifyingGlass.png');
background-repeat: no-repeat;
background-size: contain;
width: 50px;
height: 30px;
position: relative;
right: -80px;
vertical-align: middle;
}
#otherLinks {
margin-top: 10px;
}
#otherLinks a{
color: #000000;
}
#otherLinks a:hover{
color: #006a52;
}
<h1>Library Search</h1>
<form method="post" action="https://library.domains.skidmore.edu/search/searchBox.php" id="librarySearch">
<div id="searchSelection"><span id="searchLabel">Catalog</span><img src="down.png" height="30px" width="30px" /></div>
<div id="searchOptions">
<ul>
<li><button type="button" name="searchPref" value="Catalog" class="buttonSearch">Catalog<br /><br /><span class="searchSubHeading">Search books and DVDs</span></button></li>
<li><button type="button" name="searchPref" value="SearchMore" class="buttonSearch">SearchMore<br /><br /><span class="searchSubHeading">Search everything</span></button></li>
<li><button type="button" name="searchPref" value="Journals" class="buttonSearch">Journals<br /><br /><span class="searchSubHeading">Search journals</span></button></li>
</ul>
</div>
<div id="searchInput">
<input type="hidden" id="searchChoice" name="searchPref" value="catalog" />
<input type="search" id="searchBox" size="60" name="searchText" placeholder="Search our holdings"/><button type="submit" id="submit"></button></div>
<div id="otherLinks">Advanced Catalog Search | WorldCat | eBooks</div>
</form>
Some issues:
Adding event listeners within an event listener is in most cases a code smell: this will add those inner listeners each time the outer event is triggered. Those listeners remain attached, and so they accumulate. So, attach all event handlers in the top-level script, i.e. on page load, and then never again.
The if ... else at the end will execute on page load, and then never again. So the value of menuToggle is guaranteed to be "closed". You need to put that if...else switch inside the handler, so that it executes every time the event triggers, at which time the menuToggle variable will possibly have a modified value.
The body element does not stretch (by default) over the whole window. If you want to detect a click anywhere on the page, you should attach the listener on the document element itself, not on document.body.
When the click on the menu placeholder is handled, you should avoid that this event "bubbles" up the DOM tree up to the document, because there you have the other handler that wants to hide the menu again. You can do this with event.stopPropagation().
The global variable is not absolutely necessary, but if you use it, then I would call it menuVisible and give it a boolean value: false at first, and possibly true later.
For actually toggling the menu, I would create a function, which takes the desired visibility (false or true) as argument, and then performs the toggle.
Do not use undeclared variables, like the for loop variable i. Define it with let.
Here is your code with those changes implemented. Of course, there is still a lot that could be improved, but I believe that goes beyond the scope of this question:
var menuPlaceholder = document.getElementById('searchSelection');
var menuDisplay = document.getElementById('searchOptions');
var boxLabel = document.getElementById('searchLabel');
var searchBoxPlaceholder = document.getElementById('searchInput');
var searchInput = document.getElementById('searchBox');
var submitButton = document.getElementById('submit');
var searchPrefSubmission = document.getElementsByClassName('buttonSearch');
var hiddenInput = document.getElementById('searchChoice');
// Changed name and type of global variable:
var menuVisible = false;
// Removed some functions ...
menuPlaceholder.addEventListener('click', function (event){
// Use new function for actually setting the visibility
toggleMenu(!menuVisible);
// Avoid that click event bubbles up to the document level
event.stopPropagation();
});
// Add these event handlers on page load, not within another handler
// Define loop variable with let
for (let i = 0; i < searchPrefSubmission.length; i++) {
//Assigns value of the button to both the hidden input field and the placeholder box
searchPrefSubmission[i].addEventListener('click', function(event) {
hiddenInput.value = this.value;
boxLabel.innerHTML = this.value;
// Use the new function for setting the visibility
toggleMenu(false);
menuPlaceholder.style.display = "inline-block";
});
}
searchBoxPlaceholder.addEventListener('click', function(event){
searchInput.style.display = "inline";
submitButton.style.display = "inline";
});
// Bind handler on document itself, and call new function
document.addEventListener('click', function(event) {
toggleMenu(false);
});
// new function to perform the toggle
function toggleMenu(show) {
menuDisplay.style.display = show ? "block" : "none";
menuVisible = show;
}
body {
font-family:Montserrat, sans-serif;
}
#searchOptionPlaceholder {
display: inline-block;
}
#searchSelection {
padding: 10px 20px;
margin-right: 10px;
background-color: #F0F3F5;
display: inline-block;
color: #000000;
width: 140px;
max-width: 200px;
max-height: 35px;
border: 2px solid black;
vertical-align: middle;
}
#searchSelection img {
float: right;
}
#searchLabel {
display: inline-block;
padding-top: 10px;
vertical-align: top;
}
#searchOptions {
display: none;
background-color: #F0F3F5;
position: absolute;
z-index: 2;
}
#searchOptions ul {
background-color: #F0F3F5;
padding: 5px;
}
#searchOptions li {
list-style-type: none;
border-bottom: 2px solid black;
}
#searchOptions li:hover {
background-color: #706868;
color: #ffffff;
}
.buttonSearch {
background-color: transparent;
border: none;
padding: 10px;
font-size: 14px;
}
.searchSubHeading {
font-size: 12px;
}
#searchInput {
display: inline-block;
background-color: #F0F3F5;
padding: 10px 100px;
position: relative;
top: 0px;
max-width: 350px;
border: 2px solid black;
vertical-align: middle;
}
#searchInput img {
position: relative;
left: 80px;
}
#searchBox {
display: none;
width: 80%;
background-color: #F0F3F5;
border: none;
font-size: 1.5em;
position: relative;
right: 50px;
vertical-align: middle;
}
#submit {
border: none;
background-image: url('https://library.domains.skidmore.edu/search/magnifyingGlass.png');
background-repeat: no-repeat;
background-size: contain;
width: 50px;
height: 30px;
position: relative;
right: -80px;
vertical-align: middle;
}
#otherLinks {
margin-top: 10px;
}
#otherLinks a{
color: #000000;
}
#otherLinks a:hover{
color: #006a52;
}
<h1>Library Search</h1>
<form method="post" action="https://library.domains.skidmore.edu/search/searchBox.php" id="librarySearch">
<div id="searchSelection">
<span id="searchLabel">Catalog</span>
<img src="down.png" height="30px" width="30px" />
</div>
<div id="searchOptions">
<ul>
<li>
<button type="button" name="searchPref" value="Catalog" class="buttonSearch">
Catalog<br /><br /><span class="searchSubHeading">Search books and DVDs</span>
</button>
</li>
<li>
<button type="button" name="searchPref" value="SearchMore" class="buttonSearch">
SearchMore<br /><br /><span class="searchSubHeading">Search everything</span>
</button>
</li>
<li>
<button type="button" name="searchPref" value="Journals" class="buttonSearch">
Journals<br /><br /><span class="searchSubHeading">Search journals</span>
</button>
</li>
</ul>
</div>
<div id="searchInput">
<input type="hidden" id="searchChoice" name="searchPref" value="catalog" />
<input type="search" id="searchBox" size="60" name="searchText" placeholder="Search our holdings"/>
<button type="submit" id="submit"></button>
</div>
<div id="otherLinks">
Advanced Catalog Search |
WorldCat |
eBooks
</div>
</form>
I have a custom switch in CSS that I am using in a template for django. I am loading the javascript file properly but when I go to use the switch I don't get the expected result. The expected result is that the background would change colour this does not work using the switch. I added a button into the template to see if the button would work which it did,
javascript file:
function darkModen() {
var element = document.body;
element.classList.toggle("dark-mode");
}
HTML switch this does nothing:
<div class="onoffswitch" style="position: fixed;left: 90%;top: 4%;" onclick="darkMode()">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" onclick="darkMode">
<label class="onoffswitch-label" for="myonoffswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
HTML button that does do what is expected.
<button onclick="darkMode()">Toggle dark mode</button>
CCS if this is causing the problem:
.onoffswitch {
position: relative; width: 90px;
-webkit-user-select:none; -moz-user-select:none; -ms-user-select: none;
}
.onoffswitch-checkbox {
display: none;
}
.onoffswitch-label {
display: block; overflow: hidden; cursor: pointer;
border: 2px solid #000000; border-radius: 20px;
}
.onoffswitch-inner {
display: block; width: 200%; margin-left: -100%;
transition: margin 0.3s ease-in 0s;
}
.onoffswitch-inner:before, .onoffswitch-inner:after {
display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px;
font-size: 16px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold;
box-sizing: border-box;
}
.onoffswitch-inner:before {
content: "ON";
padding-left: 5px;
background-color: #FAFAFA; color: #A87DFF;
darkMode()
}
.onoffswitch-inner:after {
content: "OFF";
padding-right: 5px;
background-color: #FAFAFA; color: #999999;
text-align: right;
}
.onoffswitch-switch {
display: block; width: 18px; margin: 6px;
background: #2E2E2E;
position: absolute; top: 0; bottom: 0;
right: 56px;
border: 2px solid #000000; border-radius: 20px;
transition: all 0.3s ease-in 0s;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner {
margin-left: 0;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch {
right: 0px;
background-color: #27A1CA;
}
body {
color: black;
}
.dark-mode {
background-color: rgb(66, 66, 66);
color: white;
}
I have been trying to understand how the button works and the switch doesn't. Does this happen because I cant use onclick inside a div tag? I am also wondering if django could cause this if there is special way to use javascript in django. I can see that the javascript file as been loaded prpperly into the site as I can get to: http://127.0.0.1:8000/static/lighting.js and see the script here.
I suggest you create an event handler for the checkbox and listen for the change event to determine whether it is checked or not to make sure that you are properly applying the dark-mode class to the body tag.
Here's a possible solution:
var body = document.body;
var checkbox = document.querySelector("#onoffswitch");
checkbox.addEventListener("change", function(event) {
var target = event.target;
var isChecked = target.checked;
if (isChecked) {
body.classList.add("dark-mode");
} else {
body.classList.remove("dark-mode");
}
});
.dark-mode {
background-color: grey;
color: white;
}
<div>
<label for="onoffswitch">
<span>Toggle dark mode on or off.</span>
</label>
<input type="checkbox" name="onoffswitch" id="onoffswitch" />
</div>
Also, the onclick event on the div element is probably not what you want, at least in your situation since you're using a checkbox to determine whether the dark-mode should be applied or not.
However, the onclick attribute on the input element that you have is missing the parenthesis (onclick="darkMode()"), so if you really want to go that route, you could still do it, but I'd recommend just dealing with the checkbox itself and checking if it's checked or not.
function toggleDarkMode() {
document.body.classList.toggle("dark-mode");
}
.dark-mode {
background-color: grey;
color: white;
}
<div>
<label for="onoffswitch">
<span>Toggle dark mode on or off.</span>
</label>
<input
type="checkbox"
name="onoffswitch"
id="onoffswitch"
onclick="toggleDarkMode()"
/>
</div>
Please check onclick function name your calling onclick="darkmode()" but in javascript you write
function myFunction() {
var element = document.body;
element.classList.toggle("dark-mode");
}
please change myFunction with darkmode
it will be look like
function darkmode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
Hopefully now it work
When selecting "A&L" in the select, the radio group is hidden and its value is set to "n".
I try to trigger the change event so that the "Hello"-div disappears too, but it doesn't work correctly - on debugging I noticed that the change event is executed twice - the first time correctly and then again with the value "j".
What's my mistake?
Here's the full code: https://jsfiddle.net/95Lxroqy/
After I looked through some other questions it seemed to me that .val(['n']).change(); (line 24) should have worked -
but it seems like I'm still missing something.
// find elements
var banner = $("#banner-message");
var button = $("#place");
var langs = $("#langs");
var trans = $("#trans");
var radioGroup = $("input[type=radio][name=translate]");
var div = $("#dynamic");
radioGroup.change(function() {
if (this.value === 'n') {
div.hide();
}
else if (this.value === 'j') {
div.show();
}
});
// handle click and add class
button.change(function(event){
var al = button.val() === "al";
if(al){
langs.show();
trans.hide();
radioGroup.val(['n']).change();
}else{
trans.show();
langs.hide();
}
}).change();
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<select id="place">
<option value="in">Internal</option>
<option value="al">A&L</option>
</select>
<select id="langs">
<option value="volvo">German</option>
<option value="saab">English</option>
</select>
<fieldset id="trans">
<input type="radio" id="n" name="translate" value="n">
<label for="n"> Nein</label>
<input type="radio" id="j" name="translate" value="j">
<label for="j"> Ja</label>
</fieldset>
<div id="dynamic">
Hello
</div>
</div>
val() get/set the value of the element. Your code matches all the options exist in the collection variable, it does not match the specific element you are looking for. You can target the parent element from which you can find the the specific element by using attribute selector.
Try
radioGroup.parent().find('[value=n]').change();
Update: The more feasible solution is using the filter()
radioGroup.filter('[value=n]').change();
I would like to create a command-line interface but I am stumped on finding the right ray to get input. I need to not allow multi-line commands but wrap the text to a newline when it reaches the end of a page. Right now I have a textarea set up to only be one line and use word-wrap and stuff, and whenever the user presses enter it sets the value of the textarea to nothing and adds the old value of the textarea to a paragraph
So basically:
What i want
User can enter as much text as they want
User can not enter multi-line text
Once user presses enter, the text gets added to a paragraph and textarea is cleared
My problem
When user presses enter the textarea gets set to no text but then
adds a newline(which i do not want)
When text is added to paragraph there is a space and newline(???) being added(maybe related to how textarea adds newline)
Maybe there is another way to do this that is better or can I just fix what I have already done?
Here is my code:
HTML
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "brdstyle.css" />
<title>BrD</title>
</head>
<script src = "brdapp.js"></script>
<body>
<div id = "background">
<div id = "console">
<p id = "consoletext">
Ispum dolor ugin hegar<br/>
dank daniel for life
</p>
<textarea rows = "1" id = "textinput" onkeydown = "checkInput();"></textarea>
</div>
</div>
</body>
</html>
CSS
* {
margin: 0px;
padding: 0px;
}
body {
background-color: rgb(0, 0, 0);
}
#background {
position: fixed;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
width: 100%;
height: 100%;
background-color: black;
margin: 0px;
padding: 0px;
}
#console {
margin: 0px;
padding: 0px;
}
#consoletext {
color: rgb(255, 255, 255);
font-family: Monospace;
margin: 10px 0px 0px 10px;
}
#textinput {
resize: none;
margin: 0px 0px 10px 10px;
border: none;
outline: none;
background-color: rgb(0, 0, 0);
color: rgb(255, 255, 255);
font-family: Monospace;
width: calc(100% - 20px);
overflow: hidden;
}
Javascript
function checkInput () {
var event = window.event || event.which;
if (event.keyCode == 13) {
addLine(document.getElementById("textinput").value);
document.getElementById("textinput").value = "";
}
document.getElementById("textinput").style.height = (document.getElementById("textinput").scrollHeight) + "px";
}
function addLine (line) {
var textNode = document.createTextNode(line);
document.getElementById("consoletext").appendChild(textNode);
}
If you answer this question, thank you for your help! :)
Alright, as you had multiple problems, I will break this into 2 parts:
1. Newline being added after text field is cleared. You can stop this by calling event.preventDefault() under where it recognizes the "enter" key being pressed.
function checkInput() {
var event = window.event || event.which;
if (event.keyCode == 13) {
event.preventDefault();
addLine(document.getElementById("textinput").value);
document.getElementById("textinput").value = "";
}
document.getElementById("textinput").style.height = (document.getElementById("textinput").scrollHeight) + "px";
}
function addLine(line) {
var textNode = document.createTextNode(line);
document.getElementById("consoletext").appendChild(textNode);
}
2. I was not able to replicate your newline/space error, however it may have something to do with the event not cancelling like above.
Here is the code snippet to try yourself:
function checkInput() {
var event = window.event || event.which;
if (event.keyCode == 13) {
event.preventDefault();
addLine(document.getElementById("textinput").value);
document.getElementById("textinput").value = "";
}
document.getElementById("textinput").style.height = (document.getElementById("textinput").scrollHeight) + "px";
}
function addLine(line) {
var textNode = document.createTextNode(line);
document.getElementById("consoletext").appendChild(textNode);
}
* {
margin: 0px;
padding: 0px;
}
body {
background-color: rgb(0, 0, 0);
}
#background {
position: fixed;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
width: 100%;
height: 100%;
background-color: black;
margin: 0px;
padding: 0px;
}
#console {
margin: 0px;
padding: 0px;
}
#consoletext {
color: rgb(255, 255, 255);
font-family: Monospace;
margin: 10px 0px 0px 10px;
}
#textinput {
resize: none;
margin: 0px 0px 10px 10px;
border: none;
outline: none;
background-color: rgb(0, 0, 0);
color: rgb(255, 255, 255);
font-family: Monospace;
width: calc(100% - 20px);
overflow: hidden;
}
<div id = "background">
<div id = "console">
<p id = "consoletext">
Ispum dolor ugin hegar<br/>
dank daniel for life
</p>
<textarea rows = "1" id = "textinput" onkeydown = "checkInput();"></textarea>
</div>
</div>
You should change the textarea element to a text input
<input type="text" id="textinput" onkeydown="checkInput();">
This should get rid of the weird newline and spaces. You should also note that there is automatically a space at the end of your original paragraph due to you adding a newline after "dank daniel for life" :).
P.S I'm still a little confused as to why you don't want the text appended on a new line because it's a terminal but good luck with whatever your doing
Hope this helps!
To prevent the newline from being added you need to call event.preventDefault() just after resetting the textarea.