When working with JavaScript, the `textarea` value property will not recognize line breaks or white spaces when being read

Recently, I've been developing a browser-based notebook app. However, I encountered an issue where if I type a note like this:

*hello

this is my first note

The app displays it as:

hello this is my first note

Additionally, I want elements with the IDs of header and footer to remain fixed on the screen even while scrolling (similar to setting position to fixed, although this solution hasn't worked for me).

If you'd like to take a look at the project, check out the codes and test it yourself by visiting: Codepen

Answer №1

To convert linebreaks and whitespaces into HTML, use the following code:

note.value.replace(/\n/g, '<br>\n').replace(/\s/g,'&nbsp;');

Then, insert it into the innerHTML of the <li> instead of creating a textnode.

li.innerHTML = show;

See my example below:

const main = document.getElementById("main");
const add = document.getElementById("add"); //new note
const submit = document.getElementById("submit"); //submit the new note
const cancel = document.getElementById("cancel");
const screen = document.getElementById("screen");
const ul = document.getElementById("list");
const del = document.getElementById("delete");
const note = document.getElementById("note");
const back = document.getElementById("back");

let mynotes = {};
let i = 0;

add.addEventListener('click', function() {
  main.style.display = "block";
  submit.style.display = "inline";
  cancel.style.display = "inline";
  add.style.display = "none";
  screen.style.display = "none";
  del.style.display = "none";
  back.style.display = "none";
});

// Add event listener for submitting a new note
submit.addEventListener('click', function() {
  if (note.value) {
    newNote = note.value.replace(/\n/g, '<br>\n').replace(/\s/g,'&nbsp;');
    if (newNote.length > 50) {
      show = newNote.substring(0, 46) + "...";
    } else {
      show = newNote;
    }

    if (mynotes.hasOwnProperty(show)) {
      show = show + `${++i}`;
    }

    mynotes[show] = newNote;

    var li = document.createElement("li");
    li.setAttribute('class', 'item');
    li.innerHTML = show;
    ul.appendChild(li);
    note.value = "";
  } else {
    alert("Can't add an empty note");
  }

  main.style.display = "none";
  screen.style.display = "block";
  submit.style.display = "none";
  cancel.style.display = "none";
  add.style.display = "inline";
  del.style.display = "none";
  back.style.display = "none";
});

// Add event listener for clicking on a note item
ul.addEventListener('click', function(event) {
  node = event.target;
  item = event.target.innerHTML;
  text.innerHTML = mynotes[item];
  fullnote.style.display = "block';
  main.style.display = 'none';
  submit.style.display = 'none';
  add.style.display = 'none';
  screen.style.display = 'none';
  cancel.style.display = 'none';
  del.style.display = 'inline';
  back.style.display = 'inline';
});

// Add event listener for deleting a note
del.addEventListener('click', function() {
  ul.removeChild(node);
  delete mynotes[item];
  main.style.display = 'none';
  screen.style.display = 'block';
  submit.style.display = 'none';
  add.style.display = 'inline';
  fullnote.style.display = 'none';
  back.style.display = 'none';
  del.style.display = 'none';
});

// Add event listener for cancelling
cancel.addEventListener('click', function() {
  note.value = "";
  main.style.display = 'none';
  screen.style.display = 'block';
  submit.style.display = 'none';
  add.style.display = 'inline';
  fullnote.style.display = 'none';
  del.style.display = 'none';
  back.style.display = 'none';
  cancel.style.display = 'none';
})

back.addEventListener('click', function() {
  main.style.display = 'none';
  screen.style.display = 'block';
  submit.style.display = 'none';
  add.style.display = 'inline';
  fullnote.style.display = 'none';
  back.style.display = 'none';
  del.style.display = 'none';
});

Answer №2

If you want to display text with line breaks, you have two options:

text = text.replace(/(?:\r\n|\r|\n)/g, '<br>');

Alternatively, you can achieve the same result using CSS:

.content, .line {
    white-space: pre-wrap;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimizing CSS across various pages and screens sizes with critical importance

My CSS file is in need of optimization for quicker loading times. It contains numerous components utilized across various pages (such as the start page, category pages, and detail pages) on different screen sizes (mobile, tablet, desktop). Manual optimizat ...

Whenever a user tries to retrieve a page using ajax and then proceeds to submit the form associated with that page, they encounter

In my addQuestions.php file, I have four options available - single, multiple, matrix, and true false type questions with values 1-4 assigned to each respectively. To dynamically load the appropriate question type based on user selection, I am using AJAX w ...

Is it possible to dynamically load JavaScript?

I'm currently working on a project that requires me to dynamically add JavaScript. I have a global.js file that contains all the global variables I need to add dynamically. However, I'm facing an issue where global.js is not being added before ut ...

Converting Background Images from html styling to Next.js

<div className="readyContent" style="background-image: url(assets/images/banner/banner-new.png);"> <div className="row w-100 align-items-center"> <div className="col-md-7 dFlex-center"> ...

Create a way to allow users to download html2canvas with a customized filename

I have a div where I want to use html2canvas to save a PNG file of its content. The issue is that the name of the saved file is static in my code and does not change unless I manually edit it. Is there a way to dynamically set the filename based on user i ...

What is the best way to update this payload object?

Currently, I'm developing a route and aiming to establish a generic normalizer that can be utilized before storing user data in the database. This is the function for normalization: import { INormalizer, IPayloadIndexer } from "../../interfaces/ ...

The art of aligning text in CKEditor5

I am attempting to configure my page using the CK5 editor. So far, I have done the following: ClassicEditor.create(document.querySelector('#editor'), { language: 'pt-br', toolbar: ['heading', '|', 'bold&apo ...

The lookahead will only find a match if there are brackets present within the string

Trying to use a negative lookahead to search for a particular pattern within a single line string: /\s+(?![^[]*]).+/g Applicable to the following cases: // Case 1 a.casd-234[test='asfd asdf'] abc defg // Case 2 asf.one.two.three four fiv ...

Storing a color palette in a MySQL database from an HTML table

In my project to create a website for sharing quilting patterns, I have encountered an issue with the color changes in the HTML table. Despite allowing users to click and change cell colors, these adjustments are not saved permanently. As a solution, I a ...

What are some reasons why the XMLHttpRequest ProgressEvent.lengthComputable property could return a value of

I've been struggling to implement an upload progress bar using the XMLHttpRequest level 2 support for progress events in HTML5. Most examples I come across show adding an event listener to the progress event like this: req.addEventListener("progress ...

Arrange two input fields side by side if the quantity of input fields is unspecified

I am currently in the process of developing a project using Angular. I have implemented an *ngFor loop to dynamically add input fields based on the data retrieved from the backend. Is there a way I can ensure that two input fields are displayed on the same ...

Change the class of <body> when the button is clicked

One of my tasks involves adding a button that, when clicked, should give the body the class "open-menu". Implementing this using jQuery was quite straightforward - I just needed to add the following line of code: $('.burger').click(function() ...

How to automatically refresh a page when the URL changes with Next.js router?

On my page, users have the option to narrow down their search using filters. However, there is an issue where if a user selects a filter for "rent" or "buy", the URL does not automatically refresh to reflect the changes. Even though the changes are reflect ...

Tips for accessing elements other than the root element using this.$el

Within my template, the structure is as follows: <div v-show="showContent" class="content-block-body"> <div class="slider-pro"> <div class="sp-slides"> <slide v-for="block in subItems" ...

Cloning a table row through editing functionality in ReactJS

Hey there, I'm currently working on implementing an edit feature in react.js. The current functionality is such that when the edit button is clicked, it displays the row data in the name and email address fields. If submitted without any changes, it c ...

How to efficiently target and manipulate links using jQuery Mobile

I previously asked a question about loading an external page without ajax while maintaining it as an iOS web app window. In that example, I used the following code: <script> $(document).bind('pageinit', function() { $("#test").click(func ...

What is the best way to extract data using Angular from the backend and then transfer it to the frontend using Node.js?

Recently, I decided to make a change in my node.js application. Previously, I was using the EJS template engine but now I want to switch to Angular. To do this, I have already installed Angular and it is working well. However, I am facing an issue while t ...

Align buttons in the center of a card or container using HTML and CSS

Hi everyone, this is my first time posting so please go easy on me. I've been struggling to align the buttons at the bottom of my cards to make them look neater. I've tried using flexbox but it doesn't seem to be working. Some people have su ...

Transforming a JSON structure into a tree model for use with the angular-tree-control component

I need help converting a complex JSON schema into a format compatible with Angular Tree Control. The issue is that the schema does not follow the required treemodel structure for Angular Tree Control, particularly because the children in the schema are not ...

What is the process for establishing the default type for an Activity Entity in Microsoft Dynamics?

Currently in the process of restructuring a portion of script code associated with the Fax Activity Entity within Microsoft Dynamics. Within the script code, the following can be found: document.getElementById("regardingobjectid").setAttribute("defaulttyp ...