Creating two divs with a button - javascript

I am creating a simple note editor that has two divs a heading and a body. I'm trying to add a new note by creating the two divs with a button. Such that when you click the button the new divs will be created with texts appended to it through localStorage. When I click the button none of the divs is added. here is the html
<div id ="heading" contenteditable="true">
</div>
<div id="content" contenteditable="true">
</div>
<button type="button" onclick="addNote()" name="button">Add new Note</button>
here is the js
document.getElementById("heading").innerHTML = localStorage['title'] || 'Heading goes here';
document.getElementById('content').innerHTML = localStorage['text'] || 'Body of text editor';
setInterval(function () {
localStorage['title'] = document.getElementById('heading').innerHTML;
localStorage['text'] = document.getElementById('content').innerHTML;
}, 1000);
function addNote() {
const heading = document.createElement('div');
const content = document.createElement('div');
heading.id = "heading";
content.id = "content";
localStorage['title'] = document.getElementById('heading').innerHTML;
localStorage['text'] = document.getElementById('content').innerHTML;
}

your are missing to append the created elements to the dom (https://www.w3schools.com/jsref/met_node_appendchild.asp) :
function addNote() {
var heading = document.createElement('div');
var content = document.createElement('div');
heading.id = "heading";
content.id = "content";
document.getElementById("myDivs").appendChild(heading);
document.getElementById("myDivs").appendChild(content);
}
and you will need to have an div with id myDivs
<div id="myDivs"></div>
<button type="button" onclick="addNote()" name="button">Add new Note</button>
greetings

There are many problems in your code.
Proper way to set localStorage is via localStorage.setItem(key, val)
You need to append your DIVs somewhere on your HTML page.
Also you need to handle your setTimeout properly.
Please find solution below
HTML
<button type="button" onclick="addNote()" name="button">Add new Note</button>
JavaScript
var intervalObj = null;
function addNote() {
if(intervalObj) {
clearInterval(intervalObj)
}
const heading = document.createElement('div');
heading.setAttribute('contenteditable', true)
heading.id = "heading";
const content = document.createElement('div');
content.setAttribute('contenteditable', true)
content.id = "content";
heading.innerHTML = window.localStorage.getItem('title') || 'Heading goes here';
content.innerHTML = window.localStorage.getItem('text') || 'Body of text editor';
document.getElementsByTagName("body")[0].append(heading);
document.getElementsByTagName("body")[0].append(content);
intervalObj = setInterval(function () {
localStorage.setItem('title', document.getElementById('heading').innerHTML);
localStorage.setItem('text', document.getElementById('content').innerHTML);
}, 1000);
}

Instead of using the setInterval function you can load the data using an onload function and update to local storage whenever the AddNote button is clicked.
Modify the html as follows:
<body onload="load()">
<div id ="heading" contenteditable="true">
</div>
<div id="content" contenteditable="true">
</div>
<button type="button" onclick="addNote()" name="button">Add new Note</button>
</body>
And also you can modify your JS file as follows
function load() {
var headingText = localStorage['title'] || 'Heading goes here';
var bodyText = localStorage['text'] || 'Body of text editor';
document.getElementById("heading").innerHTML = headingText;
document.getElementById('content').innerHTML = bodyText;
}
function addNote() {
localStorage['title'] = document.getElementById('heading').innerHTML;
localStorage['text'] = document.getElementById('content').innerHTML;
}

Related

how can I write the function of two or more photocopies in a single <script>?

I would like to ask for help, how can I write the function of two or more mycopy in a single ?
I have a page where I have to insert more buttons that copy and I don't want to write the same for each button.
Thank you all
enter code here
<button onClick="mycopy('copia')">copy</button></p>
<div id="copia" >
<p>[text1]</p>
</div>
<p><script>
function mycopy (containerid) {
var textarea = document.createElement('textarea')
textarea.id = 'temp_element'
textarea.style.height = 0
document.body.appendChild(textarea)
textarea.value = document.getElementById(containerid).innerText
var selector = document.querySelector('#temp_element')
selector.select()
document.execCommand('copy')
document.body.removeChild(textarea)
}
</script></p>
<button onClick="mycopy1('copia1')">copy</button></p>
<div id="copia1">
<p>[text2 ]</p>
</div>
<p><script>
function mycopy1 (containerid) {
var textarea = document.createElement('textarea')
textarea.id = 'temp_element'
textarea.style.height = 0
document.body.appendChild(textarea)
textarea.value = document.getElementById(containerid).innerText
var selector = document.querySelector('#temp_element')
selector.select()
document.execCommand('copy')
document.body.removeChild(textarea)
}
</script></p>

Javascript method to remove a specific field

I want to attach more than one field to a div along with a remove button. Something similar to Gmail file attaching methods if the user presses the remove button it should remove the specified p along with the button. But if I press the remove button it is not working properly I know the javascript array method is the problem but I am not able to understand where I am going wrong
<form name="create" action ="">
<input type="text" id="text">
<button name="submit" onclick="attach()" type="button">Submit</button>
</form>
<div id="attach">
</div>
<script>
function attach(){
var value =document.getElementById('text').value;
var content = document.createElement('p'); // is a node
content.className = 'element';
// Insert text
var btn = document.createElement("BUTTON");
btn.innerHTML = "Delete This element";
var i =0;
btn.onclick = function(){
console.log(i);
remove(i);
i++;
};
content.innerHTML = value;
document.getElementById("attach").appendChild(content);
document.getElementById("attach").appendChild(btn);
}
function remove(i){
var elem = document.getElementsByClassName('element');
elem[i].remove();
return false;
}
</script>
The working plunker is here.
http://plnkr.co/edit/eYhfN85FH4XabzE4rO4M?p=preview
What is going wrong here? How can I fix this?
A slightly different approach that simplifies your original example, is to take advantage of the function/closure you create for the button you create. In there, you can literally just reference the content and btn elements, and remove them directly
function attach(){
var value =document.getElementById('text').value;
var content = document.createElement('p'); // is a node
content.className = 'element';
// Insert text
var btn = document.createElement("BUTTON");
btn.className = 'element';
btn.innerHTML = "Delete This element";
btn.onclick = function(){
content.remove();
btn.remove();
};
content.innerHTML = value;
var attach = document.getElementById("attach");
attach.appendChild(content);
attach.appendChild(btn);
}
<form name="create" action ="">
<input type="text" id="text">
<button name="submit" onclick="attach()" type="button">Submit</button>
</form>
<div id="attach">
</div>
That way, you don't have to worry about what index you're removing or anything
Here you go!
function attach() {
const attachEl = document.getElementById("attach");
const value = document.getElementById("text").value;
const contentEl = document.createElement("p"); // is a node
contentEl.className = "element";
// Insert text
const btnEl = document.createElement("button");
btnEl.innerHTML = "Delete This element";
const wrapperEl = document.createElement("div");
btnEl.onclick = function() {
attachEl.removeChild(wrapperEl);
};
attachEl.appendChild(wrapperEl);
wrapperEl.appendChild(contentEl);
wrapperEl.appendChild(btnEl);
contentEl.innerHTML = value;
}
#attach{
background-color: teal;
}
.element {
background-color: wheat;
}
<form name="create" action="">
<input type="text" id="text">
<button name="submit" onclick="attach()" type="button">Submit</button>
</form>
<div id="attach">
</div>
We should use a wrapper to wrap a p & button together so that when we initiate delete it deletes the complete wrapper
function attach(){
var value =document.getElementById('text').value;
var content = document.createElement('p'); // is a node
var wrapper = document.createElement('div');
wrapper.className="wrapper";
content.className = 'element';
// Insert text
var btn = document.createElement("BUTTON");
btn.innerHTML = "Delete This element";
var i =0;
btn.onclick = function(){
console.log(i);
remove(i);
i++;
};
content.innerHTML = value;
wrapper.appendChild(content);
wrapper.appendChild(btn);
document.getElementById("attach").appendChild(wrapper);
}
function remove(i){
var elem = document.getElementsByClassName('wrapper');
elem[i].remove();
return false;
}
<form name="create" action ="">
<input type="text" id="text">
<button name="submit" onclick="attach()" type="button">Submit</button>
</form>
<div id="attach">
</div>

Creating nodes in Javascript

I'm learning Javascript and I would like to understand something.
I tried to build HTML nodes using Javascript and my code works when I split instructions but not when I try to compress :
I have a tab with text :
var tabText = [
'The ',
'Moon',
];
This code works :
var s1 = document.createElement('strong');
s1.appendChild(document.createTextNode(tabText[1]));
div.appendChild(s1);
But this one doesn't :
div.appendChild(document.createElement('strong').appendChild(document.createTextNode(tabText[1])));
Could you give me some explanations ?
Thanks.
document.createElement('strong').appendChild(document.createTextNode(tabTexte[1]))
node.appendChild returns the appended child node , therefore the upper code will return the textNode(wich is then appended to to div wich makes the strong elem go to nowhere)...
You may want this:
div.appendChild(document.createElement('strong')).appendChild(document.createTextNode(tabText[1]));
The result of appendChild is the child, not the parent. In other words, your code is equivalent to
var strongNode = document.createElement('strong');
var textNode = document.createTextNode(tabText[1]));
strongNode.appendChild(textNode); // returns textNode
div.appendChild(textNode);
Therefore, strongNode will not be added to the document.
//Create Node
(function () {
function createTodoNode(todo) {
const node = document.createElement("li");
node.classList.add("todo-item");
node.innerHTML = `
<button class="done-state">
<div class="done-state-filler"></div>
</button>
<div class="todo-name"></div>
<button class="delete-todo">✖</button>
`;
node.querySelector(".todo-name").textContent = todo.value;
const doneButton = node.querySelector("button.done-state");
const deleteButton = node.querySelector("button.delete-todo");
node.setAttribute("data-completed", todo.isComplete);
doneButton.addEventListener("click", () => {
const currentlyCompleted = JSON.parse(
node.getAttribute("data-completed") || "false"
);
node.setAttribute("data-completed", !currentlyCompleted);
todo.isComplete = !currentlyCompleted;
todoService.updateTodo(todo);
});
deleteButton.addEventListener("click", () => {
node.parentNode.removeChild(node);
todoService.removeTodo(todo.id);
});
return node;
}
window.todoView = {
createTodoNode,
};
})();
// Second Variation
<button onclick="create()">Aufgabe erstellen</button>
<ul class="items">
Meine Aufgabe:
</ul>
function create(){
let list = document.querySelector(".items");
let node = document.createElement("li");
node.classList.add("todo-item");
node.style ="color: orangered";
node.innerHTML = '<div class= "todo-item"></div>';
list.appendChild(node);
node.querySelector(".todo-item").textContent = "Eine erste Aufgabe";
console.log(node);
}
// Third Variation
(function() {
function createTaskNode(param) {
let categorie = document.querySelector("#" + param.key);
let newTaskDiv = document.createElement("div");
newTaskDiv.classList.add("task");
newTaskDiv.setAttribute("id", param.id);
newTaskDiv.setAttribute("data-assigned", param.isComplete);
if (newTaskDiv.getAttribute("data-assigned") == "undefined") {
newTaskDiv.setAttribute("data-assigned", false);
}
newTaskDiv.innerHTML = `
<div class="task-name">
<div class="task-value"></div>
<div class="data-assigned-button"></div>
</div>
<div class="button-div">
<button class="prev-button">⬅</button>
<button class="delete-button">âŒ</button>
<button class="next-button">âž¡</button>
</div>`;
newTaskDiv.setAttribute("task-value", param.value);
categorie.appendChild(newTaskDiv);
}
window.taskViewService = {
createTaskNode
};
})();

Transferring iframe value to textarea

I'm making an app that submits posts, but I originally designed it with a textarea in mind, I've since put in an iframe to create a rich text field, set the display style to hidden for the textarea and wanted to know how I could modify it to use the iframe value.
HTML
<div id="textWrap">
<div class="border">
<h1>Start Writing</h1><br />
<input id="title" placeholder="Title (Optional)">
<div id="editBtns">
<button onClick="iBold()">B</button>
<button onClick="iUnderline()">U</button>
<button onClick="iItalic()">I</button>
<button onClick="iHorizontalRule()">HR</button>
<button onClick="iLink()">Link</button>
<button onClick="iUnLink()">Unlink</button>
<button onClick="iImage()">Image</button>
</div>
<textarea id="entry" name="entry" rows="4" cols="50" type="text" maxlength="500" placeholder="Add stuff..."></textarea>
<iframe name="richTextField" id="richTextField"></iframe><br />
<button id="add">Submit</button>
<button id="removeAll" onclick="checkRemoval()">Delete All Entries</button>
<ul id="list"></ul>
<ul id="titleHead"></ul>
</div><!--end of border div-->
</div><!--end of textWrap-->
Here is the JS to submit the posts.
//target all necessary HTML elements
var ul = document.getElementById('list'),
removeAll = document.getElementById('removeAll'),
add = document.getElementById('add');
//richText = document.getElementById('richTextField').value;
//make something happen when clicking on 'submit'
add.onclick = function(){
addLi(ul)
};
//function for adding items
function addLi(targetUl){
var inputText = document.getElementById('entry').value, //grab input text (the new entry)
header = document.getElementById('title').value, //grab title text
li = document.createElement('li'), //create new entry/li inside ul
content = document.createElement('div'),
title = document.createElement('div'),
//textNode = document.createTextNode(inputText + ''), //create new text node and give it the 'entry' text
removeButton = document.createElement('button'); //create button to remove entries
content.setAttribute('class','content')
title.setAttribute('class','title')
content.innerHTML = inputText;
title.innerHTML = header;
if (inputText.split(' ').join(' ').length === 0) {
//check for empty inputs
alert ('No input');
return false;
}
removeButton.className = 'removeMe'; //add class to button for CSS
removeButton.innerHTML = 'Delete'; //add text to the remove button
removeButton.setAttribute('onclick', 'removeMe(this);'); //creates onclick event that triggers when entry is clicked
li.appendChild(title); //add title textnode to created li
li.appendChild(content); //add content textnode to created li
li.appendChild(removeButton); //add Remove button to created li
targetUl.appendChild(li); //add constructed li to the ul
}
//function to remove entries
function removeMe(item){
var deleteConfirm = confirm('Are you sure you want to delete this entry?');
if (deleteConfirm){var parent = item.parentElement;
parent.parentElement.removeChild(parent)}
};
function checkRemoval(){
var entryConfirm = confirm('Are you sure you want to delete all entries?');
if (entryConfirm){
ul.innerHTML = '';
}
};
demo I'm working on for reference.. http://codepen.io/Zancrash/pen/VemMxz
you can use either local storage for passing iframe values to the parent DOM.
or ( use this to pass value from iframe to parent container )
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalFunction();
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalVariable;
From IFrame html
<script type="text/javascript">
var myLocalVariable = "text";
function myLocalFunction () {
return "text";
}
</script>

Deleting specific div's with JavaScript

I am trying to spawn different div's and remove them after they do their job. A simple version of my code is:
function eraseDiv(){
var c = document.getElementById("cn1");
c.parentNode.removeChild(child);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child";
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<a href=\"?\" onclick=eraseDiv(); return false; > Delete</a>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>'
The problem is that when the first spawned div is deleted, all div's are deleted. Any help is appreciated on how to fix this.
How about something like this:
function eraseDiv(target){
var div = target.parentNode;
var container = div.parentNode;
container.removeChild(div);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<button onclick=eraseDiv(this);> Delete</button>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<button type="button" name="submit" onclick="spawnDiv();">Spawn</button>
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
First thing, since you're returning false every time you obviously don't want to use the submit functionality of your submit input, so change it to a button instead.
Second thing, remove the ID from the spawned div since you should never have two divs with the same ID.
Third thing (like the first thing) since you're not using the link functionality of the anchor element, you should change it to a button instead (using CSS you can style this like an anchor if you want to).
Fourth thing, inside the delete button, add this as a parameter to the eraseDiv function. You can now access the button that was clicked using the function parameter rather than trying to find it by an ID.
The simplest fix to your code without modifying the functionality (and view of the page) of what you did is to replace the href="?" with href="#".
In your original code, when you do something like link with the "?" as the hyperlink, this actually performs a GET request which will reload the page. This is tricky because it makes it seem like your delete code is removing all the spawned divs from both cn1 and cn2 divs.
Changing the href=? to href=# prevents a GET request from happening. Below is a snippet that directly makes this change that results in the correct behavior of your original code (by deleting the spawned element in cn1). You will have to further modify your code to make it do what you want.
function eraseDiv(){
var c = document.getElementById("cn1");
c.parentNode.removeChild(c);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child";
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<a href=\"#\" onclick=eraseDiv(); return false; > Delete</a>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
Another way of doing it would be to create a id for div like this
<html>
<body>
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
<script>
function eraseDiv(j){
var c = document.getElementById('child'+j);
c.parentNode.removeChild(c);
}
var i=1;
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child"+i;
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<u ><a onclick=eraseDiv("+i+++"); > Delete</a></u>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
</script>
</body>
</html>

Categories

Resources