Use case is to create Add/show/select/delete text messages on a page. I have used array to store the messages on each click till here it works fine but when I try to create Divs and show the messages in grid, I am having duplication on each click. I can see that my function is reading the array fine and creating the div's on the first click but it does not clear the previously created div on second iteration. Not sure how to approach this. Please advise.
here is the snippet.
<script>
//<!-- Fetch data from Textarea when user Click Save and create or push in an array -->
let ArrNotes = [];
function SaveNote() {
let edittext = document.getElementById("editor").value;
ArrNotes.push(edittext);
document.getElementById("SavedNote").innerHTML = ArrNotes;
let container = document.getElementById("GridNotes");
container.className= "GridNotes";
ArrNotes.forEach(createGrid);
function createGrid(item,index)
{
text = undefined;
var tag = document.createElement("div");
tag.className= "grid";
var text = document.createTextNode(index + ": " + item);
//tag.appendChild(text);
container.appendChild(text);
}
}
Related
Im making a note taking application and the idea here is im trying to make a selection function to transfer my notes from the side list to the editor on the right side of the screen when clicked. So I have the list items all being created dynamically while the ul is created static.
The trouble im facing is how hard it is to click the list items. I have it console.log the work "click' whenever it registers and im not sure why its not working like its suppose it it looks like it only registers when I click the margins of the children of the li and not the h1 or p tags. Also if I click to the side, it makes my ul clickable which is not good as it would just throw everything in the editor.
I have it so when the li tags are created. It dynamically creates then via JS, adds li,h1,p,p. Appends the h1,p,p tags to the li then the li to the container.
Below is an example of my code:
//This is just to show you what happens when you click
//the submit button and how my divs are being dynamically created.
//I have them being created automatically from
//localstorage on load as well in this same fashion.
submitbutton.addEventListener('click', () => {
//Creating local variables for new notes
let NewNoteContainer = document.createElement('li')
let NewNoteTitle = document.createElement('h1')
let NewNoteDueDate = document.createElement('p')
let NewNoteContent = document.createElement('p')
let RemoveButton = document.createElement('button')
//Adds values of the input boxes to the newley created Elements
NewNoteContainer.id = NoteID
NewNoteContainer.className = 'notes-list-item'
NewNoteTitle.innerHTML = title.value
NewNoteDueDate.innerHTML = dueDate.value
NewNoteContent.innerHTML = content.value
//This appends the newly created elements to the container and then
//Appends the container to its div "note-list-container"
NewNoteContainer.append(NewNoteTitle, NewNoteDueDate,NewNoteContent)
NoteListContainer.append(NewNoteContainer)
//Creates an array, makes it a JSON string. Then stores it in localStorage
let StorageArray = [NoteID,title.value,dueDate.value,content.value]
localStorage.setItem('Note' + NoteID, JSON.stringify(StorageArray))
NoteID += 1
})
//This is the debug function im using to try and diag the click issue.
NoteListContainer.addEventListener('click', (a) => {
if(a.target.parentNode.className == 'notes-list-container') {
console.log('click')
}
})
Hi I just wondering if i can get some pointers with my code, I am trying to capture and save the input value of a textarea. I am fairly new to JavaScript and I have been wrecking my brain trying to figure it out. My issue is regarding the saveEntry() function, which isn't complete I have only posted how my code is right now, and isn't causing errors/unwanted effects. Any tips or hints would be fantastic, as I keep getting errors
function addTextEntry(key, text, isNewEntry) {
// Create a textarea element to edit the entry
var textareaElement = document.createElement("textarea");
textareaElement.rows = 5;
textareaElement.placeholder = "(new entry)";
// Set the textarea's value to the given text (if any)
textareaElement.value = text;
// Add a section to the page containing the textarea
addSection(key, textareaElement);
// If this is a new entry (added by the user clicking a button)
// move the focus to the textarea to encourage typing
if (isNewEntry) {
textareaElement.focus();
}
// Create an event listener to save the entry when it changes
// (i.e. when the user types into the textarea)
function saveEntry() {
// Save the text entry:
// ...get the textarea element's current value
var currentValue = document.getElementById('textarea').value;
// ...make a text item using the value
// ...store the item in local storage using the given key
localstroage.setItem(key, item);
}
// Connect the saveEntry event listener to the textarea element 'change' event
textareaElement.addEventListener("change", saveEntry());
}
function addImageEntry(key, url) {
// Create a image element
var imgElement = new Image();
imgElement.alt = "Photo entry";
// Load the image
imgElement.src = url;
// Add a section to the page containing the image
addSection(key, imgElement);
}
/**
* Function to handle Add text button 'click' event
*/
function addEntryClick() {
// Add an empty text entry, using the current timestamp to make a key
var key = "diary" + Date.now();
var text = "";
var isNewEntry = true;
addTextEntry(key, text, isNewEntry);
I was told to utilise something similar to this code below, but not exactly the same as I need to capture the data value of the user input text, not pre-created data.
function createDemoItems() {
console.log("Adding demonstration items to local storage");
var item, data, key;
// Make a demo text item
data =
"Friday: We arrived to this wonderful guesthouse after a pleasant journey " +
"and were made most welcome by the proprietor, Mike. Looking forward to " +
"exploring the area tomorrow.";
item = makeItem("text", data);
// Make a key using a fixed timestamp
key = "diary" + "1536771000001";
// Store the item in local storage
localStorage.setItem(key, item);
// Make a demo text item
data =
"Saturday: After a super breakfast, we took advantage of one of the many " +
"signed walks nearby. For some of the journey this followed the path of a " +
"stream to a charming village.";
item = makeItem("text", data);
// Make a key using a fixed timestamp
key = "diary" + "1536771000002";
// Store the item in local storage
localStorage.setItem(key, item);
// Make a demo image item
data = window.DUMMY_DATA_URL;
item = makeItem("image", data);
// Make a key using a fixed timestamp
key = "diary" + "1536771000003";
// Store the item in local storage
localStorage.setItem(key, item);
// Make a demo text item
data =
"Sunday: Following a tip from Mike we drove to a gastropub at the head of " +
"the valley - a great meal and fabulous views all round.";
item = makeItem("text", data);
// Make a key using a fixed timestamp
key = "diary" + "1536771000004";
// Store the item in local storage
localStorage.setItem(key, item);
}
You are very close, you just have to make some adjustments here and there!
Just as a disclaimer, I had to re-create your addSection() function, in order to have it properly working. If you already had one, you could discard mine
When we create a new entry, in order to make it distinguishable, I have assigned it the id of the key. Before, you were trying to call getElemenyById("textarea"), but no element had id textarea, which is in fact the tag name of the textarea element that you created. Read more about getElementByTagName if you want.
I have changed the way the event listener is set to:
textareaElement.addEventListener(
'input',
function () { saveEntry(); },
false
);
The difference between change and input are that change will fire only when you are done with the changes and click outside of the textarea, whilst input will fire everytime that you input something. Now you know, so of course, feel free to change it to what you would like it to behave.
Lastly, I have made the just-created item to be retrieved immediately and logged to console. This will be useful just for testing, you can comment out those lines when you are happy.
Beware that the snippet below is playable, but it won't actually save data to LocalStorage because of SO limitations, so you won't be able to fully test it on this page.
function addSection(key, element) {
element.id = key;
var test = document.querySelector("#test");
test.appendChild(element);
}
function addTextEntry(key, text, isNewEntry) {
// Create an event listener to save the entry when it changes
// (i.e. when the user types into the textarea)
function saveEntry() {
// Save the text entry:
// ...get the textarea element's current value
var currentValue = document.getElementById(key).value;
// ...store the item in local storage using the given key
localStorage.setItem(key, currentValue);
//Testing if we can retrieve the item, comment out when you're happy
var item = localStorage.getItem(key);
console.log(item);
}
// Create a textarea element to edit the entry
var textareaElement = document.createElement("textarea");
textareaElement.rows = 5;
textareaElement.placeholder = "(new entry)";
// Set the textarea's value to the given text (if any)
textareaElement.value = text;
// Add a section to the page containing the textarea
addSection(key, textareaElement);
// If this is a new entry (added by the user clicking a button)
// move the focus to the textarea to encourage typing
if (isNewEntry) {
textareaElement.focus();
}
textareaElement.addEventListener(
'input',
function () { saveEntry(); },
false
);
// Connect the saveEntry event listener to the textarea element 'change' event
//textareaElement.addEventListener("change", saveEntry());
}
function addImageEntry(key, url) {
// Create a image element
var imgElement = new Image();
imgElement.alt = "Photo entry";
// Load the image
imgElement.src = url;
// Add a section to the page containing the image
addSection(key, imgElement);
}
/**
* Function to handle Add text button 'click' event
*/
function addEntryClick() {
// Add an empty text entry, using the current timestamp to make a key
var key = "diary" + Date.now();
var text = "";
var isNewEntry = true;
addTextEntry(key, text, isNewEntry);
}
window.onload = () => addEntryClick();
<html>
<head>
</head>
<body>
<div id="test"></div>
</body>
</html>
There are a number of things wrong with the way you're doing things, but you know that: that's why you're here!
You have a typo: localstroage should be localStorage
You create a text area but don't give it an ID. In your saveData function you attempt to find it, but you're searching for it by tag name. There's no need to search: your event handler will already have this set to the element.
In your event handler you refer to your function as saveData(). This will invoke the function immediately and assign its return value as an event handler. Just pass the function name.
Here's a demonstration of concept for you:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Explore local storage</title>
</head>
<body>
<textarea id="txt" placeholder="Enter text and press TAB"></textarea>
<script>
"use strict";
let txtKey = "someKey"
// Save the data. No need to search for the text area:
// the special value 'this' is already set to it.
function saveEntry() {
localStorage.setItem(txtKey, this.value);
}
// Look fr the previous text and if it exists, put it in the textarea
let storedText = localStorage.getItem(txtKey);
if (storedText) {
document.getElementById('txt').value = storedText;
}
// Now add the event listener.
tArea.addEventListener('change', saveEntry); // Pass just the function name
</script>
</body>
</html>
This code uses a hard-coded value for txtKey. Your code might need to generate and track some value for the key, otherwise you risk overwriting earlier data with later data.
I have this idea where if you press a button, it'll display a text, but not only one text, but multiple, just not at once. If you press the button again, it'll display another text after it. So far, I'm only limited to only one text being displayed. I'm not really sure how to go from what I'm trying to achieve. I had an idea about using arrays but arrays and buttons didn't seem to work all that great, at least for me. I might have done something wrong for it to not work. Anyways, the idea was that the button would call from the array each time you'd click it so it'd display a different text.
So if you press the button once, it would output: "Hello"
And if you press it again, it would output: "How are you?"
and so on and so forth.
How would I do this in terms of making something like this happen?
Disclaimer: I don't want the text to be replaced with a new text. I want it solely outputted afterwards.
<button id = "age-button" button onClick = "ageButton()">AGE!</button>
<script>
function ageButton() {
var text = "You are born.";
document.getElementById("age1").innerHTML = text;
}
</script>
This code above only displays one text. How would I let it display another text after I press the button again?
// Define array of string that you would like to show on each click
const labels = [
"String 1",
"String 2",
"String 3"
// ... so on (add as many as you like)
];
// lets start from zero index
let currentIndex = 0;
// get the button HTMLElement
const nextBtn = document.querySelector("#next-btn");
const contentsEl = document.querySelector("#contents");
// attach onClick event handler / listner
nextBtn.addEventListener("click", function(event) {
// get the label string to show
const label = labels[currentIndex];
const p = document.createElement("p");
p.textContent = label;
contentsEl.append(p);
// increment the index
currentIndex++;
// set a trap
if (currentIndex === labels.length) {
//(bonus) disable the button when you reach the end
this.disabled = true;
}
});
<button id="next-btn">Show Next</button>
<div id="contents"></div>
Here is an example how you can do that.
let texts = ["You are born", "Hi there", "I'm ready"];
function ageButton() {
let line = texts.shift(); //use shift to get the first element in array
if (line) {
//use += operator to append to previous content
document.getElementById("age1").innerHTML += "<p>" + line + "</p>";
}
}
<button id="age-button" onclick="ageButton()">AGE!</button>
<div id="age1"></div>
I'm trying to loop through an array until it matches the value of the object that is clicked.
When the object is created the text input box shares it's value with the object and the array. I would like to be able to loop through the array until there is a match, then find the index, after that pass the index value to a variable to be used. From there remove the object that is clicked from the webpage and the array.
Additional details are that there is an input box with a button. The user enters a line of information into the input box and selects a button to appendChild it to the list. The object created is a div with the input value as the paragraph with a span element with an X which is supposed to remove the object when clicked.
Here is the HTML Code being used
<div id="outerDiv">
<div id="taskList">
</div>
</div>
Here is the code to create the object.
var magicArray = [];
function makeOutline() {
var textValue = document.getElementById("inputBox").value;
if (textValue == "" || textValue == null){
alert("Please enter a item you want to add to the to-do list");
} else {
var inputField = document.getElementById("taskList");
var inputText = document.createTextNode(textValue);
var mainHeading = document.createElement("p");
mainHeading.setAttribute("class", "outlineBorder");
var spanText = document.createTextNode("x");
var spanBox = document.createElement("span");
spanBox.setAttribute("class", "close");
spanBox.setAttribute("onclick", "removeMe()");
var outlineList = document.createElement("div");
outlineList.setAttribute("value", textValue);
spanBox.appendChild(spanText);
mainHeading.appendChild(inputText);
mainHeading.appendChild(spanBox);
outlineList.appendChild(mainHeading);
inputField.appendChild(outlineList);
magicArray[magicArray.length] = textValue;
document.getElementById("inputBox").value = "";
}
}
Here is the code to remove the item.
I am able to have it set to a static number and work every time; however,
struggling to find a dynamic solution since there can be multiple objects.
function removeMe() {
var removeList = document.getElementById("taskList");
removeList.removeChild(removeList.childNodes[1];
}
Here is a screenshot of the family tree structure
First, you can use this to get the element. docs:
When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered.
function removeMe()
{
// this refers to the item that invoked removeMe()
var removeList = document.getElementById("taskList");
removeList.removeChild(this.parentNode.parentNode);
}
Also, this is how you properly add event listeners
spanBox.addEventListener("click", removeMe);
Here is a working jsfiddle for you
When you click the addFruit button, the input text value gets appended to the fruitList as it should. localStorage is activated at the same time, and it works, the data is still there after page refresh.
When you double click on the item that you just appended, you can edit it (contentEditiable), but when you refresh the page, the localStorage retrieves the original name instead of the modified one.
I think it's an an updating issue. When you double click on a list item, it should call the storestate function as soon as you're done editing, so it overwrites what was previously added to localStorage.
I've tried adding storestate() numerous places, and tried to move around my functions, suspecting that my code is written in the wrong order.
Sometimes it actually works after page refresh, but it's usually if I add several items, and then edit one of them. But not always. It's confusing!
I can't find a single similar example on SO, can someone point me in the right direction? :)
(function() {
var fruitList = document.querySelector('#fruitList');
var fruitInput = document.querySelector('.fruitInput');
var addFruitButton = document.querySelector('.addFruitButton');
var removeFruits = document.querySelector('.removeFruits');
// Add fruits
// Store fruits
function storestate() {
localStorage.fruitList = fruitList.innerHTML;
};
// Retrieve stored fruits from localStorage
function retrievestate() {
if (localStorage.fruitList) {
fruitList.innerHTML = localStorage.fruitList;
}
}
retrievestate();
// Remove fruit storage
function removeStorage() {
localStorage.clear(fruitList);
fruitList.innerHTML = ''; // removes HTML
}
function addFruit() {
if (fruitInput.value) {
var li = document.createElement('li');
li.className = 'fruit-item';
li.innerHTML = fruitInput.value;
li.contentEditable = 'true';
fruitList.append(li);
fruitInput.value = ''; // Reset input field
}
storestate();
}
// Clear all fruits
removeFruits.onclick = removeStorage;
//Add fruit
addFruitButton.onclick = addFruit;
})();
I tried to embed the entire code-snippet on SO, but I get an error because of localStorage. Works fine on jsFiddle and other editors:
https://jsfiddle.net/bx39gd0n/10/
https://jsfiddle.net/xbrra7yt/1/
(function() {
...
//change state of item
function changestate() {
console.log('changed');
}
...
fruitList.addEventListener('keyup', changestate);
})();
You would simply chain an eventlistener to be called on keyup. In the fiddle it simply logs 'changed' to the console. Just replace that with your own code to replace the list in localStorage and you should be fine!