i am trying to build post it notes. I am reading Head First Series.
I did this code.
but somehow it's no working.
<form action="post">
<input id="note_text" type="text" placeholder="enter your Note">
<input type="button" id="add_button" value="Add Note">
</form>
<ul id="postItNotesList">
<li>This is my very first note.</li>
<li>This is my very Second note.</li>
</ul>
And here is the Js
window.onload=init;
// Add Sticky to Page
function addStickyToPage(value) {
var sticky = document.createElement("li");
span.setAttribute("class", "sticky");
document.getElementById("postItNotesList").appendChild(sticky);
}
// Create and get Sticky Note into the localStorage
function createSticky() {
var value = document.getElementById("note_text").value;
var key = "sticky_" + localStorage.length;
localStorage.setItem(key, value);
addStickyToPage(value);
}
function init() {
var button = document.getElementById("add_button");
button.onclick = createSticky;
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
if (key.substring(0, 6) == "sticky") {
var value = localStorage.getItem(key);
addStickyToPage(value);
}
}
}
So i've buld up a fiddle so that you can easily check it out
Here is the Fiddle
Please tell me where i am doing it wrong.
Thanks.
I have updated your Fiddle. Note : first you should create DOM element and then append text to this element and finally append this node to you body so your code should be like this:
window.onload=init();
function addStickyToPage(value) {
var sticky = document.createElement("li");
sticky.setAttribute("class", "sticky");
var t = document.createTextNode(value);
console.log(t);
sticky.appendChild(t);
document.getElementById("postItNotesList").appendChild(sticky);
}
And also windows.onload = init()with brackets
Thanks
Related
So I'm trying to add a prompt which asks the user what they would like to add to an array. However, whenever I refresh the page, it gets deleted like it is only in local storage. I would like to add this to the actual code so it gets displayed permanently within the page.
Here is the relavent code:
<html>
<body>
<div class="ann" id="shadowbox">
<h4>Latest Announcements</h4>
<ul id="myUl"></ul>
</div>
<button onclick="fc()">populate</button>
<script>
var announcements = ["test",]
for (i = 0; i < announcements.length; i++) {
var li = document.createElement("li");
var text = document.createTextNode(announcements[i]);
li.appendChild(text);
document.getElementById("myUl").appendChild(li);
}
function fc() {
var asdkz = prompt("What would you like to add?")
announcements.push(asdkz);
}
</script>
You need to use localStorage to save the content of the array after refresh. Here is the solution with some modification:
<html>
<body>
<div class="ann" id="shadowbox">
<h4>Latest Announcements</h4>
<ul id="myUl"></ul>
</div>
<button onclick="fc()">populate</button>
<script>
var announcements = (localStorage.getItem("list")) ? localStorage.getItem("list").split(",") : ["test"]
updateList();
function updateList(){
document.getElementById("myUl").innerHTML = "";
for (i = 0; i < announcements.length; i++) {
var li = document.createElement("li");
var text = document.createTextNode(announcements[i]);
li.appendChild(text);
document.getElementById("myUl").appendChild(li);
}
}
function fc() {
var asdkz = prompt("What would you like to add?")
announcements.push(asdkz);
localStorage.setItem("list",announcements);
updateList();
}
</script>
I've made a start to a to do list. I've got it adding an item when you submit an item.
I want to now add local storage when you refresh the page so the items are saved in the browser.
I obviously need to save all the times when the page is refreshed but because my items only update on click I'm not sure how to grab that function data outside the function and save the items.
Any ideas?
Cheers
JS Fiddle:
https://jsfiddle.net/x1bj8mfp/
// When submit item
var submit = document.getElementById('form');
submit.addEventListener('submit', addItem);
var items = [];
var itemValues = document.getElementById('items');
var listContainer = document.createElement('ul');
itemValues.appendChild(listContainer);
// Add item
function addItem(e) {
e.preventDefault();
var item = this.querySelector('[name=item]');
var itemValue = item.value;
items.push(itemValue);
item.value = '';
// Output items
var listItems = document.createElement('li');
listItems.innerHTML = itemValue;
listContainer.appendChild(listItems);
}
You could write the whole array to local storage whenever you add an item:
localStorage.setItem('items', JSON.stringify(items));
Then on page load you would read from local storage the array and assign it back to your variable, or set it to [] (like now), if nothing is in local storage, and then display these items:
var items = JSON.parse(localStorage.getItem('items')) || [];
items.forEach(function (itemValue) {
var listItems = document.createElement('li');
listItems.textContent = itemValue;
listContainer.appendChild(listItems);
});
This updated JSFiddle has that code included.
Of course, you will need some function to delete items as well, otherwise you can only grow your list.
Here's a full solution for you. Note that the code snippet won't work here, due to the cors and sandbox. Just paste it into your code editor.
var submit = document.getElementById('form');
submit.addEventListener('submit', addItem);
var items = [];
var itemValues = document.getElementById('items');
var listContainer = document.createElement('ul');
itemValues.appendChild(listContainer);
//retrieve data after reload
window.onload = function() {
if (localStorage.userData != undefined) {
var userData = JSON.parse(localStorage.getItem('userData'));
for (var i = 0; i < userData.length; i++) {
var listItems = document.createElement('li');
listItems.innerHTML = userData[i];
listContainer.appendChild(listItems);
items = userData;
}
}
}
// Add item
function addItem(e) {
e.preventDefault();
var item = this.querySelector('[name=item]');
var itemValue = item.value;
items.push(itemValue);
item.value = '';
// Output items
var listItems = document.createElement('li');
listItems.innerHTML = itemValue;
listContainer.appendChild(listItems);
localStorage.setItem('userData', JSON.stringify(items));
}
<main>
<form id="form">
<input class="form-input" type="text" name="item" placeholder="Add item">
<input class="btn btn-block" type="submit" value="Submit">
</form>
<div id="items"></div>
<div id="completed"></div>
</main>
Here some helpful small example for local storage
function save() {
var fieldvalue = document.getElementById('save').value;
localStorage.setItem('text', fieldvalue);
}
function load() {
var storedvalue = localStorage.getItem('textfield');
if (storedvalue) {
document.getElementById('textfield').value = storedvalue;
}
}
function remove() {
document.getElementById('textfield').value = '';
localStorage.removeItem('textarea');
}
<body onload="load()">
<input type="textarea" id="textfield">
<input type="button" value="Save" id="save" onclick="save()">
<input type="button" value="remove" id="remove" onclick="clr()">
</body>
<!--save& run this in local to see local storage-->
I am currently working on making the to-do list app shown [here][1] work better. I have done things like change the font, but want to use Javascript cookies to make it so that the user's to-dos are properly saved and still there when the page is reopened.
All I need now (which I can't seem to get the idea of how to do) is the part where 1. the browser saves the data and 2. where the browser retrieves the data.
Any help would be greatly appreciated.
<body>
<!--To-Do Header, where you add tasks-->
<div id="myDIV" class="header">
<!--Change one: Make to-do list name different-->
<h2>To-Do</h2>
<input type="text" id="myInput" placeholder="Title..." style="padding-bottom: 20px;">
<span onclick="newElement();" class="addBtn">Add</span>
</div>
<!--To-do list-->
<ul id="myUL">
</ul>
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
};
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("You must write something to create a task.");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
};
}
}
Using local storage, as it lasts longer then cookies:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
EDIT: #MichaelMior pointed out that local storage may not last longer then cookies, but the cookies are sent with browser requests so it's unnecessary in this case.
You want to store the text content, so you need to get them first
var values=[...document.getElementsByTagName("li")].map(el=>el.textContent);
Now you can store this array
localStorage.setItem("todos",values);
If the page is loaded, add it back to the page:
localStorage.getItem("todos").forEach(fumction(value){
//create elem
elem.textContent=value;
});
You could also store a HTML collection, but i wouldnt, storing just the text is.much easier...
Here is a quick example where I store an item and give it a name in localStorage called input. This shows how to setItem() and getItem().
Looks like this example doesn't work in the SO sandbox, so here's a codepen - http://codepen.io/anon/pen/KaNZxX
$('button').on('click',function() {
localStorage.setItem("input", $('input').val());
fetch();
});
function fetch() {
$('#storage').html(localStorage.getItem('input'));
}
fetch(); // fetch on load
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"> <button>add</button>
<div id="storage"></div>
I apologize for posting this question, I'm just learning JavaScript and have tried using the information from other posts but just cannot get my code to work. The object is to create an li tag and insert list items to this newly created tag, then assign an event handler to remove an item if the user clicks on it.
I have the list populating and can remove an item if I hardcode it but cannot for the life of me figure out how to assign the value of the item being clicked on to the removeItem function. I am also trying to clear the list when an item is entered but keep getting the error "Object doesn't support property or method 'reset'".
If someone could point me in the right direction I would appreciate it.
thanks!
<!doctype html>
<html lang="en">
<head>
<title> Add and delete items Objective </title>
<meta charset="utf-8">
<style>
p {
font-style: italic;
}
li:hover {
cursor: pointer;
}
</style>
<script>
// your code here!
var itemList = [];
window.onload = init;
function init() {
var addButton = document.getElementById("submitButton");
addButton.onclick = addItem;
//var itemList = document.getElementById("list");
var itemsList = document.getElementsByTagName("li");
itemsList.onclick = removeItem;
}
function addItem() {
var newItem = document.getElementById("item").value;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(newItem));
ul.appendChild(li);
itemList.push(newItem);
document.getElementById("item").reset();
}
function removeItem() {
var editList = document.getElementsByTagName("li");
// var editList = document.getElementsById("list");
for (var i = 0; i < editList.length; i++) {
var item = editList[i];
if(editList.options[i].selected) {
editList.removeChild(editList.childNodes[i]);
}
}
}
</script>
</head>
<body>
<form>
<label form="item">Add an item: </label>
<input id="item" type="text" size="20"><br>
<input id="submitButton" type="button" value="Add!">
</form>
<ul id="list">
</ul>
<p>
Click an item to remove it from the list.
</p>
</body>
</html>
Why not set the value of the item input to an empty string rather than using reset?
document.getElementById("item").value = "";
As for removing the list items...
for (var i = 0; i < ul.children.length; i++) {
ul.children[i].addEventListener("click", removeItem);
}
you can only reset forms, so you have to select the form and then reset will work. f.e. with:
document.forms[0].reset()
your code is adding the eventhandler to all existing li-Elements, if you create some new li-Elements later, you have to add the eventhandler to it manually. f.e. in your addItem-Function with:
li.onclick = removeItem;
after pushing the new Item
in your removeItem-Function you have access on the clicked Element via this, so you can remove only this Element with:
this.remove()
You could change your addItem() and removeItem() functions :
function addItem() {
var newItem = document.getElementById("item").value;
$('#list').append("<li id='" + newItem + "' onclick='removeItem(this)'>" + newItem + "</li>");
}
function removeItem(id) {
$(id).remove();
}
http://jsfiddle.net/rfnslyr/CRqXm/1/
I have the following fiddle which extracts CSS classes and ID's, and posts them to console. I want to type a name into the top box, paste some code, and have it generate a separate set of unique css ID's and classes into a new instance of the #classes instance (which has uin0CE + a bunch of classes in it).
I have that posting to console done, I just don't know how to "spawn" a new instance of the the #classes section on submit every time I add a new name to #codeName and code to #codeInput.
index.html
<div id="container">
<input id="codeName" class="boxsizingBorder"></input><br>
<textarea id="codeInput" class="boxsizingBorder"></textarea><br>
<button id="submitCode">submit</button>
<div id="classes">
<div class="pageTitle">uin0CE</div>
<div class="cssClassesIDs">
ui-icon-nodisc,redDotClass,translate,test,ui-hide-label,ui-grid-a,ui-block-a,ui-block-b,alignRight,ui-grid-solo,ui-disabled,companyFieldset,longbutton,icon-map-marker,locationIcon,icon-phone,contactIcon,legalBlock,legal,legalDivider,signInInfoIcon,icon-info-sign,ui-icon-alt
</div>
</div>
</div>
<script src="functions.js"></script>
functions.js
$(function() {
$('#submitCode').click(function() {
var CSS_CLASSES = [];
var CSS_IDS = [];
var el = document.createElement( 'div' );
var text = $("#codeInput").val();
el.innerHTML = text;
var nodes = el.getElementsByTagName('*');
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.id.length > 0) {
CSS_IDS.push.apply(CSS_IDS, node.id.split(" "));
}
if (node.className.length > 0) {
CSS_CLASSES.push.apply(CSS_CLASSES, node.className.split(" "));
}
}
var uniqueNames = [];
$.each (CSS_CLASSES, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
console.log(uniqueNames + " --- " + uniqueNames.length);
});
});
Edit: I added this to your fiddle:
//Added this section here
var name = $('#codeName').val();
var code = uniqueNames;
$('#classes').empty();
$('#classes').append('<div class="pageTitle">'+name+'</div>');
$('#classes').append('<div class="cssClassesIDs">'+code+'</div>');
Here's the updated fiddle: http://jsfiddle.net/CRqXm/4/
I'm hoping I'm following your question correctly, but this seems to be what you're looking for.