Separating text on the screen entered by the user - javascript

I have an HTML page, and I have a <textarea> element in it. Let's also say I have a send button that displays the message on the screen. When multiple messages are sent, their position will move to below the previous message sent. New messages will be in separate containers (I made borders). I've used this code that worked. Actually, it didn't completely work. When you enter multiple messages, instead of creating a new message border with the message inside it, it puts all your text in the same element.
const button = document.getElementById("sendButton");
button.addEventListener("click", displayText);
function displayText() {
const display = document.getElementById("msg");
const textArea = document.getElementById("enterMsg");
display.append(
textArea.value,
document.createElement("br")
);
textArea.value = "";
}
body {
background-color: skyblue;
font-weight: bolder;
}
#enterMsg {
margin-top: 34%;
height: 130px;
width: 100%;
font-family: Arial, sans-serif;
font-size: 15px;
color: darkorange;
background-color: #d796ff;
font-weight: bolder;
}
.enterText {
font-family: Arial, sans-serif;
font-size: 15px;
color: darkorange;
background-color: #d796ff;
font-weight: bolder;
}
#sendButton {
margin-left: 96%;
}
#msg {
margin-left: 80%;
border: solid;
border-color: #b19cd9;
background-color: #b4ff94;
border-radius: 50px;
color: darkorange;
}
.extraSpace {
padding: 5px;
}
textarea::placeholder {
color: darkorange;
}
div.centered {
text-align: center;
border: solid;
border-color: blue;
margin-top: 10%;
margin-bottom: 10%;
}
.confirmButton {
text-align: center;
margin-bottom: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Main Page</title>
<link rel="stylesheet" href="style.css">
<script src="tools.js"></script>
</head>
<body>
<p id="msg" class="extraSpace"></p>
<textarea id="enterMsg" placeholder="Enter your message here..."></textarea>
<button id="sendButton" onclick="displayText('msg', 'enterMsg')">Send</button>
</body>
</html>
As I said, this code works but it puts all messages in a single element. Is there any way to make it so that a new border appears with the entered text inside it instead of putting every message into a single element?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Main Page</title>
<link rel="stylesheet" href="style.css">
<script src="tools.js"></script>
</head>
<body>
<div id="messages"></div>
<textarea id="enterMsg" placeholder="Enter your message here..."></textarea>
<button id="sendButton" onclick="displayText('msg', 'enterMsg')">Send</button>
</body>
</html>
const button = document.getElementById("sendButton");
button.addEventListener("click", displayText);
const textArea = document.getElementById("enterMsg");
const container = document.getElementById("messages");
function displayText() {
// Create a new element with the message as it's inner text.
const message = document.createElement("p");
message.innerText = textArea.value;
message.setAttribute("class", "msg");
// Add that to the document
container.appendChild(message);
textArea.value = "";
}
You'll also have to change your stylesheet because msg is a class now rather than an ID (since there will be more than one of them

Related

How to store output in localStorage?

I'm working on my first ever JavaScript project (a palindrome checker) and I'm kind of getting stuck. I've learned about localStorage() but I can't seem to implement it in my own project. It'd be awesome if someone could point me in the right direction, or write pseudo code as to what I should do to get it to work. I really want to solve it myself, but a little help is much needed here. Thanks :). My JavaScript code (and HTML and CSS for reference:
Edit: I want to show the results (each on a separate line) on the screen using localStorage() and use it again to enable the user to delete the results when clicking on the button.
const checkBtn = document.getElementById("check-word");
const clearBtn = document.getElementById("clear-history");
const outputField = document.getElementById("word-checked");
let array = [];
checkBtn.addEventListener("click", () => {
const str = document.getElementById("input").value;
array = [...array, str];
console.log(array);
palindrome(str);
renderResult();
function palindrome(str) {
const lettersOnly = str.toLowerCase().match(/[a-z0-9]/g);
return lettersOnly.join("") === lettersOnly.reverse().join("");
}
renderResult();
function renderResult() {
if (palindrome(str) === true) {
outputMessage = `︎✔︎ '${str}' is a palindrome!`
} else {
outputMessage = `𐄂 '${str}' is not a palindrome!`
}
outputField.textContent = outputMessage;
}
document.getElementById("input").value = ""; // clear input field after clicking on checkBtn
})
// clearBtn.addEventListener("click", () => {
// localStorage.clear();
// array = [];
// // render again!
// })
* {
background-color: #121212;
font-size: 16px;
margin: 0;
padding: 0;
}
h1 {
font-family: "VT323", monospace;
font-size: 5rem;
color: #CE1212;
text-align: center;
margin-top: 50px;
}
.container {
font-family: "Nanum Gothic Coding", monospace;
color: white;
width: 75%;
height: 62.5vh;
margin: 25px auto 25px auto;
/* border: 2.5px solid; */
border-color: white;
padding: 15px;
}
.input {
margin-left: 25px;
}
.input-field {
margin-left: 25px;
margin-top: 12.5px;
padding: 7.5px;
font-family: "Nanum Gothic Coding", monospace;
color: white;
border: 1px solid;
}
.input-field:focus::placeholder {
color: transparent;
}
.check-word, .clear-history {
padding: 7.5px;
font-family: "Nanum Gothic Coding", monospace;
color: white;
border: 1px solid;
border-color: white;
cursor: pointer;
}
.check-word:hover, .clear-history:hover {
color: #CE1212;
}
.child-1 {
margin-top: 50px;
margin-left: 25px;
/* border: 1px solid; */
padding: 15px;
}
#word-checked {
margin-top: 15px;
}
.footer {
font-family: "Nanum Gothic coding", monospace;
color: white;
text-align: center;
margin-bottom: 25px;
}
a:link, a:visited {
color: white;
text-decoration: none;
}
a:hover, a:active {
color: #CE1212;
text-decoration: underline;
}
/*
top, right, bottom, left
*/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Palindrome Checker</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Nanum+Gothic+Coding&family=VT323&display=swap" rel="stylesheet">
<link rel="stylesheet" href="index.css">
</head>
<body>
<main>
<h1>🌮 Palindrome Checker 🐱</h1>
<div class="container">
<label for="input" class="input">Type a word or phrase</label>
<br>
<input type="text" name="input" class="input-field" id="input" placeholder="Type something...">
<button type="button" class="check-word" id="check-word">Check word</button>
<button type="button" class="clear-history" id="clear-history">Clear history</button>
<div class="child-1">
<p id="word-checked">Results will be shown here!</p>
</div>
</div>
</main>
<footer class="footer">
<p>Built by Yin Chu</p>
</footer>
<script src="index.js"></script>
</body>
</html>
It's really easy. (At least much easier than cookies)
localStorage.setItem('key', 'value'); // to store data
var myData = localStorage.getItem('key') // to get data
localStorage.removeItem('key') // to remove one data
localStorage.clear() // to remove all data
Replace key and value with the data key and the data to store respectively.

Recording of anonymous edits of text on page

In the following code, I am allowing users to edit text content, save and recall changes from own "local storage". So every editor's browser "remembers" their own editing, and each editor sees his changes only. I want to realise an idea of the anonymous wiki and import every user edits and display the last one in the final HTML page.
function saveEdits() {
//get the editable element
var editElem = document.getElementById("edit");
//get the edited element content
var userVersion = editElem.innerHTML;
//save the content to local storage
localStorage.userEdits = userVersion;
//write a confirmation to the user
document.getElementById("update").innerHTML = "Готово";
}
function checkEdits() {
//find out if the user has previously saved edits
if (localStorage.userEdits !== null)
document.getElementById("edit").innerHTML = localStorage.userEdits;
}
body {
display: block;
padding: 50px;
margin: 50px;
width: 90%;
font-family: 'Oranienbaum', serif;
font-size: 30px;
margin-right: 50px;
height: 90%
}
#edit {
background-color: white;
margin: 5px;
padding: 0px;
text-align: inherit;
font-size: 40px;
font-family: 'Oranienbaum', serif;
}
#button {
background-color: silver;
border: none;
top: 100px;
margin: 5px;
padding: 10px;
font-family: 'Oranienbaum', serif;
font-size: 20px;
}
#update {
background-color: white;
top: 100px;
margin: 5px;
padding: 5px;
font-size: 20px;
}
hr {
display: block;
margin-left: auto;
margin-right: auto;
border-style: dashed;
border-width: 1px;
}
.footer {
background-color: inherit;
top: 100px;
margin: 5px;
padding: 5px;
font-size: 10px;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Indexmod Encyclopedia — anonymous real-time editing </title>
<script src="code.js" type="text/javascript" charset="utf-8"></script>
<link href="style.css" rel="stylesheet" type="text/css">
<style>
#import url('https://fonts.googleapis.com/css?family=Oranienbaum');
</style>
</head>
<body onload="checkEdits()">
Indexmod Россия
<hr>
<div id="edit" contenteditable="true">
Here is Indexmod Encyclopedia anonymous real-time editing sandbox area
</div>
<hr>
<input type="button" id=button value="Сохранить" onclick="saveEdits()" />
<div id="update">Редактируй текст и нажми сохранить до следующего раза</div>
<p class="footer" id="footer"><span><script src="footer.js"></script></span>
</p>
</body>
</html>
While you're going to set item on local storage, the method goes to:
localStorage.setItem('userEdits', userVersion);
And get item
localStorage.getItem('userEdits');
Hope it would be help, This works for me.
See the reference: http://www.w3schools.com/html/html5_webstorage.asp

Add CSS class to change style of HTML element

#charset "utf-8";
html, body {
margin: 0px;
font-family: Helvetica, sans-serif;
min-height: 100%;
height: 100%;
}
.center-container {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
/*height: 500px;*/
}
.main-container {
/*height: 100%;*/
}
.darktitle {
color: #000000;
background: grey;
font-size: 25px;
}
.titlebar {
text-align: center;
color: #FF0000;
background: blue;
font-size: 40px;
}
button {
padding: 00px;
font-weight: bold;
font-size:1em;
font
color: #000000;
height: 40px;
width: 200px;
}
<!DOCTYPE html>
<html lang="de">
<head>
<link href="styles/styles.css" rel="stylesheet"/>
<meta charset="utf-8">
</head>
<body>
<div class="main-container">
<h1 id="titlebar" class="titlebar"> Titlebar</h1>
<div class="center-container" >
<button id="button1">Button1</button>
<button id="button2">Button2</button>
<button id="button3">Button3</button>
</div>
</div>
<script>
var titlebar = document.querySelector('h1#titlebar');
var button1 = document.querySelector('#button1');
var button2 = document.querySelector('#button2');
var button3 = document.querySelector('#button3');
button1.addEventListener('click', function() {
titlebar.innerHTML = 'Button1';
var result = titlebar.classList.contains('darktitle');
console.log(result);
titlebar.classList.add('darktitle');
var result = titlebar.classList.contains('darktitle');
console.log(result);
});
</script>
</body>
</html>
Hey earthlings,
i started learning HTML and CSS. Currently I'm dealing with style classes. I created a simple example. What I want to reach is, that the titlebar changes the font color, the font-size and the background color if button1 is clicked.
Initially the titlebar has appended the titlebar-class, after button1 is clicked the darktitle-class should also be added and overwrite certain attributes.
However in this configuration it doesn't happen. If you change the order of the .darktitle and .titlebar class in css file it works. I wonder why.
The CSS Styles should be on the same priority level, so I would expect that the laterly assigned would overwrite the attributes.
TNX
you can use !important to override styles like this
.darktitle {
color: #000000!important;
background: grey!important;
font-size: 25px!important;
}
#charset "utf-8";
html, body {
margin: 0px;
font-family: Helvetica, sans-serif;
min-height: 100%;
height: 100%;
}
.center-container {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
/*height: 500px;*/
}
.main-container {
/*height: 100%;*/
}
.titlebar {
text-align: center;
color: #FF0000;
background: blue;
font-size: 40px;
}
.darktitle {
color: #000000;
background: grey;
font-size: 25px;
}
button {
padding: 00px;
font-weight: bold;
font-size:1em;
font
color: #000000;
height: 40px;
width: 200px;
}
<!DOCTYPE html>
<html lang="de">
<head>
<link href="styles/styles.css" rel="stylesheet"/>
<meta charset="utf-8">
</head>
<body>
<div class="main-container">
<h1 id="titlebar" class="titlebar"> Titlebar</h1>
<div class="center-container" >
<button id="button1">Button1</button>
<button id="button2">Button2</button>
<button id="button3">Button3</button>
</div>
</div>
<script>
var titlebar = document.querySelector('h1#titlebar');
var button1 = document.querySelector('#button1');
var button2 = document.querySelector('#button2');
var button3 = document.querySelector('#button3');
button1.addEventListener('click', function() {
titlebar.innerHTML = 'Button1';
var result = titlebar.classList.contains('darktitle');
console.log(result);
titlebar.classList.add('darktitle');
var result = titlebar.classList.contains('darktitle');
console.log(result);
});
</script>
</body>
</html>
The order of your css selectors matter when both selectors are being applied to the same element. Move the ".darktitle" below the ".titlebar" as in this example. Then when applied by the button the ".darktitle" sstyles will override those same properties in ".titlebar".
Please take a look at this link about CSS specificity, there you will read about your question and why not to use !important declaration.
Specificity at MDN

Clicking input field triggers jQuery function

I'm trying to create a selectable list that when you click on an item, it displays an input field that you can use to edit the description but until the item is clicked on, the input field is hidden.
However, when I select an item and then click on the input field, it unselects the item and the input field is hidden again.
I've recreated the issue here with just one list item. How can I allow for the user to click in the input field without triggering the jQuery function?
Also, the user will be able to click multiple items in the list so I've updated the jsbin with a second item.
If you don't want to change the html arrangement of the input , you can prevent the event propagation on click of the input element to its parent which in turn will avoid any class toggle.
The only addition you need is this.
$('.fund input').click(function(e) {
e.stopPropagation();
});
Here is the working sample
$('.fund').click(function() {
$(this).toggleClass('selected');
});
$('.fund input').click(function(e) {
e.stopPropagation();
});
* {
font-family: 'Lato', sans-serif;
}
.fund {
background-color: #fff;
width: 500px;
border: 1px solid #444;
height: 50px;
padding: 0 10px;
border-radius: 3px;
}
.fund:hover {
background-color: #efefef;
cursor: pointer;
}
.fund .description,
.fund .alt-description {
width: 50%;
float: left;
}
.fund .description {
line-height: 50px;
font-size: 12px;
letter-spacing: 1px;
text-transform: uppercase;
font-weight: 700;
color: #555;
}
.fund .alt-description {
visibility: hidden;
line-height: 50px;
font-size: 14px;
}
.fund .alt-description input {
height: 30px;
font-size: 12px;
}
.fund.selected {
border: 1px solid #00cc00;
}
.fund.selected .description {
color: #00cc00;
}
.fund.selected .alt-description {
visibility: visible;
}
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="[be able to click in input but don't toggle div]">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<div class='fund'>
<div class='description'>
Fund Name
</div>
<div class='alt-description'>
Description:
<input type='text' value='Fund Name'>
</div>
</div>
</body>
</html>
This will do the trick:
$('.fund').click(function() {
$('.fund').removeClass('selected');
$(this).addClass('selected');
});
The issue is that you have alt-description within fund, so anytime you click on "fund" it will toggle the show hide of your alt-description input. Move the alt-description out of the fund class. Otherwise make the trigger description instead of fund.
<div class='fund'>
<div class='description1'>
Fund Name
</div>
</div>
<div class='alt-description1'>
Description: <input type='text' value='Fund Name'>
</div>
Here I change the javascript a little.
$('.fund').click(function() {
if(!$(this).hasClass('selected')){
$(this).toggleClass('selected');
}
});
So when ever the div with the .fund class has a class selected don't toggle the class.

How can I update local html file after adding new element using javascript?

I am new to web development.
I am try to add a list item to a unorded list.
using javascript
html
<!DOCTYPE html>
<html>
<head>
<title>Item Add Test</title>
<script src="item.js"></script>
<link rel="stylesheet" type="text/css" href="item.css">
</head>
<body>
<input type="text" id="initem"></input>
<br /><br />
<button onclick="myFunction1()" id="submit">SUBMIT</button>
<ul id="menu">
<li>ABC</li>
<li>BLA</li>
</ul>
</body>
</html>
css item.css
body {
font-family: monospace;
text-align: center;
font-size: 1.5em;
}
input {
text-align: center;
width: 300px;
height: 30px;
border: 1px solid blue;
border-radius: 5px;
margin: 10px auto;
padding-left: 10px;
font-size: 1.2em;
font-weight: bold;
}
#submit {
font-size: 1em;
}
javascript item.js
function myFunction1() {
var name = document.getElementById("initem").value;
var node = document.createElement("LI");
var textnode = document.createTextNode(name);
node.appendChild(textnode);
document.getElementById("menu").appendChild(node);
}
I successfully add items to the list.
But when I refresh the page all items are gone.
How can I save the html file or update the html file after adding the items,so that if I refresh the page list items remain there.
You can save the text of <li> elements in the local storage and retrieve on load event of the body.
The snippet won't work for security reasons but I tried on Sublime Text and it's fine.
var li_texts = [];
function myFunction1() {
var name = document.getElementById("initem").value;
var node = document.createElement("LI");
var text = 'Test';
node.innerHTML = text;
document.getElementById("menu").appendChild(node);
li_texts.push(text);
localStorage.setItem("li_texts", JSON.stringify(li_texts));
}
function loadList(){
if (localStorage.getItem("li_texts") !== null) {
var stored_names = JSON.parse(localStorage.getItem("li_texts"));
for(i=0; i<stored_names.length; i++){
var node = document.createElement("LI");
node.innerHTML = stored_names[i];
document.getElementById("menu").appendChild(node);
}
}
else{
return;
}
}
body {
font-family: monospace;
text-align: center;
font-size: 1.5em;
}
input {
text-align: center;
width: 300px;
height: 30px;
border: 1px solid blue;
border-radius: 5px;
margin: 10px auto;
padding-left: 10px;
font-size: 1.2em;
font-weight: bold;
}
#submit {
font-size: 1em;
}
<!DOCTYPE html>
<html>
<head>
<title>Item Add Test</title>
<script src="item.js"></script>
<link rel="stylesheet" type="text/css" href="item.css">
</head>
<body onload="loadList()">
<input type="text" id="initem"></input>
<br /><br />
<button onclick="myFunction1()" id="submit">SUBMIT</button>
<ul id="menu">
<li>ABC</li>
<li>BLA</li>
</ul>
</body>
</html>

Categories