While loop act twice JS - javascript

I used this code:
var list = was_talkWindows.querySelectorAll('.msg:not(.was_added)');
var i;
for (i = 0; i < list.length; i++)
{
list[i].className += cssClass;
var btn = document.createElement('button');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'was_addButton');
btn.addEventListener('click', function() {
was_button_act(this.parentElement);
});
btn.innerHTML = buttonName;
list[i].appendChild(btn);
}
however, friend told me that .msg:not(.was_added) is too slow, so doing it in the opposite way:
var cssClass = ' was_added';
var buttonName = 'start waiting';
if (was_set_standby_auto == true)
{
cssClass += ' was_standby';
buttonName = 'cancel';
}
try {
var currectMSG = was_talkWindows.querySelector('.msg:last-child');
while (currectMSG.classList.contains('was_added') == false)
{
currectMSG.className += cssClass;
var btn = document.createElement('button');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'was_addButton');
btn.addEventListener('click', function() {
was_button_act(this.parentElement);
});
btn.innerHTML = buttonName;
currectMSG.appendChild(btn);
currectMSG = currectMSG.previousElementSibling;
}
} catch (err) {}
but the code add the button twice each time for the last one.
not really understand this behavor.

Use previousElementSibling instead of previousSibling, so that it skips over text nodes.
And add the was_added class to the element so it won't be processed again later.
var was_talkWindows = document;
var cssClass = " newclass";
var buttonName = "Click me";
try {
var currectMSG = was_talkWindows.querySelectorAll('.msg:last-child')[0];
while (currectMSG.classList.contains('was_added') == false) {
currectMSG.className += cssClass;
currectMSG.classList.add('was_added');
var btn = document.createElement('button');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'was_addButton');
btn.addEventListener('click', function() {
was_button_act(this.parentElement);
});
btn.innerHTML = buttonName;
currectMSG.appendChild(btn);
currectMSG = currectMSG.previousElementSibling;
}
} catch (err) {}
<ol>
<li class="msg was_added">Text</li>
<li class="msg was_added">Text</li>
<li class="msg">Text</li>
<li class="msg">Text</li>
<li class="msg">Text</li>
</ol>

The problem with a site that is not under your control, it does not always know what is running, and it took me a long time to realize that the problem is not adding buttons twice (against logic), but anyone who does not I edit the code at the same time.
so declare just once:
var was_msgList = was_talkWindows.getElementsByClassName('msg');
and the loop (every 2 seconds):
for ( var i=was_msgList.length; i-- && was_msgList[i].getAttribute('data-status') == null; )
{
was_load_addButton(was_msgList[i],attStatus,buttonText);
}
any ideas for change are welcome.

Related

How to use local storage on append child

<button id="showlinks" onclick="myFunction">show</button>
<div id="buttonlinks"></div>
function myFunction() {
var button = document.createElement("button");
document.getElementById("buttonlinks").appendChild(button);
}
I used This Code to create buttons on clicking a button. when clicking the show button the buttons appear but after refresh they are gone.
can I store the buttons with localStorage?
You can store the information about your buttons in the localStorage whenever you create a button, and add an eventListener to window.onload to read the buttons from localStorage and append it to the page when page has loaded, in the below exmpale to keep it simple, I just store the length of buttons.
<button id="showlinks" onclick="myFunction">show</button> <div id="buttonlinks"></div>
js:
let buttonsLength = 0;
document.getElementById('showlinks').addEventListener('click', function () {
createButton();
buttonsLength++;
localStorage.setItem('buttonsLength', buttonsLength)
});
function createButton() {
var button = document.createElement('button');
button.innerHTML = 'click me';
document.getElementById('buttonlinks').appendChild(button);
}
window.addEventListener('load', (event) => {
buttonsLength = Number(localStorage.getItem('buttonsLength')) || 0;
for (let i = 0; i < buttonsLength; i++) {
createButton();
}
});
const showlinks = document.getElementById('showlinks')
showlinks.addEventListener("click", function () {
localStorage.setItem("showClicked", true)
displayButtonInDom()
})
function displayButtonInDom() {
const showClicked = localStorage.getItem("showClicked")
if (showClicked) {
const button = document.createElement("button");
button.innerText = "click me"
document.getElementById("buttonlinks").appendChild(button);
}
}
displayButtonInDom()
<button id="showlinks">show</button>
<div id="buttonlinks"></div>
Foreache button created you have to add the button information to the localstorage. And on page load you execute an init function that rebuild all button created from the localstorage
<button id="showlinks" onclick="createButton('')">show</button>
<div id="buttonlinks"></div>
<script>
function Initbutton() {
//on load check if the button has been already add using the localStorage
var buttons = getButtonInformationFromLocalStorage();
if(buttons != null){
buttons.forEach(function(btnName){
createButton(btnName);
})
}
}
// fo the purpose of having different button name
// i have picket this function here https://www.codegrepper.com/code-examples/javascript/find+random+name+javascript
function getRandomString(length) {
var randomChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var result = '';
for ( var i = 0; i < length; i++ ) {
result += randomChars.charAt(Math.floor(Math.random() * randomChars.length));
}
return result;
}
function createButton(btnName){
if(btnName == undefined || btnName == ""){
btnName = "button" + getRandomString(10);
updateButtonInformationToLocalStorage(btnName);
}
var button = document.createElement("button");
button.innerHTML = btnName;
document.getElementById("buttonlinks").appendChild(button);
}
function updateButtonInformationToLocalStorage(name){
var lstrg = localStorage.getItem("alreadyaddbuttontobuttonlinks");
if(lstrg == null){
localStorage.setItem("alreadyaddbuttontobuttonlinks", name);
return name;
}else{
var nLstrg = lstrg + "|" + name;
localStorage.setItem("alreadyaddbuttontobuttonlinks", nLstrg);
return nLstrg;
}
}
function getButtonInformationFromLocalStorage(){
var lstrg = localStorage.getItem("alreadyaddbuttontobuttonlinks");
if(lstrg == null){
return null;
}else{
return lstrg.split("|");
}
}
window.onload = Initbutton();
</script>

creating multiple children using appendChild

I am creating a simple todo app.
When I add a todo and list them, I want to show delete and change status button with every todo,
But only one button appears,
See, first button(delete button) is very tiny and doesn't even function. But it works perfectly when I add only 1 button.
Here is the js for adding the list item and button,
var view = {
displaytodos: function(){
var todoul = document.querySelector('ul');
todoul.innerHTML = '';
for (var i=0;i < todolist.todos.length;i++){
var newli = document.createElement('li');
newli.setAttribute('class','text-success');
var todotextwithstatus = '';
if (todolist.todos[i].completed === true){
todotextwithstatus = '(X) - ' + todolist.todos[i].todotext + ' --> ';
}
else{
todotextwithstatus = '( ) - ' + todolist.todos[i].todotext + ' --> ';
}
newli.id = i;
newli.textContent = todotextwithstatus;
delbtn = this.createdeletebutton();
statusbtn = this.createstatusbutton();
newli.appendChild(statusbtn);
newli.appendChild(delbtn);
todoul.appendChild(newli);
}
},
createdeletebutton: function(){
var delbtn = document.createElement('button');
delbtn.textContent = 'Delete';
delbtn.className = 'DeleteElement';
return delbtn;
},
createstatusbutton: function(){
var statusbtn = document.createElement('button');
delbtn.textContent = 'Change Status';
delbtn.className = 'changestatusbutton';
return statusbtn;
},
This is the html,
<div class='col-xs-4'>
<h3>Your todos will appear here.</h3>
<ul>
<li>You have not added any todos yet.</li>
</ul>
<button onclick='handlers.toggle_all()'>Change status of all Todos</button>
</div>
What is the solution for this? Why is this happening?

how do i add functionality to each of the buttons?

The first part of the code is working correctly, but now that each button appears, how do i add functionality to each of them? currently the only button which does something when pressed is always the last one, the rest do nothing.
Change it to
{
var output = "";
var data = JSON.parse(e.target.responseText);
for(var i=0; i<data.length; i++)
{
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
p.appendChild(button);
div.appendChild(p);
button.addEventListener ("click", () =>
{
alert("Test");
});
}
}
You are adding the below code out side the for loop
button.addEventListener ("click", () =>
{
alert("Test");
} );
Keep the above code inside the for loop. So that for each button the event listener will be added.
Another way to approach this would be to add the callback function to the onclick variable of the elements prototype:
function doStuff() {
var output = "";
var data = JSON.parse(e.target.responseText);
for (var i = 0; i < data.length; i++) {
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
// Adds the callback function here
button.onclick = () => {
// fill in your arrow function here...
alert("Test");
};
p.appendChild(button);
div.appendChild(p);
};
}
doStuff();
Here is a jsFiddle
You should use event delegation for dynamically added elements
// sample data
var data = [{
title: 'one'
}, {
title: 'two'
},{
title: 'three'
}];
var output = "";
for (var i = 0; i < data.length; i++) {
var output = data[i].title + " ";
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
// added output to button text for identification
button.innerHTML = output + " Download";
p.appendChild(button);
div.appendChild(p);
}
// Get the parent element, add a click listener
document.getElementById("response").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a button
if (e.target && e.target.nodeName == "BUTTON") {
// Button found! Output the identifying data!
// do other work on click
document.getElementById("display").innerHTML = e.target.innerHTML + " Clicked";
}
});
<div id="response"></div>
<div id="display">Display</div>

joining functions onclick and onkeyup

I just went over my code with an experienced developer and he made a lot of very helpful changes, but, unfortunately, the code did not save properly and I lost all the edits!!!
The main thing he helped with was eliminating some of my code repetition. I have two functions that share a lot of code: //Add item to To-Do List with "Add" Button AND //Add item to list with ENTER KEY.
What he did for this was to add the bulk of these functions to the //Add new item to To-Do List function, so the other functions were simpler. I forgot how he did this, though! If anyone can help I would really appreciate it!
//Add new item to To-Do List
function addNewItem(list, itemText) {
totalItems++;
var listItem = document.createElement("li");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "cb_" + totalItems;
checkbox.onclick = updateStatus;
var span = document.createElement("span");
span.id = "item_" + totalItems;
span.textContent = itemText;
var spanDelete = document.createElement("span2");
spanDelete.id= "spanDelete_" + totalItems;
spanDelete.textContent = "DELETE";
spanDelete.onclick = deleteItem;
var spanEdit = document.createElement("span3")
spanEdit.id = "editId_" + totalItems;
spanEdit.textContent = "EDIT";
spanEdit.onclick = editItem;
listItem.appendChild(checkbox);
listItem.appendChild(span);
listItem.appendChild(spanDelete);
listItem.appendChild(spanEdit);
list.appendChild(listItem);
}
//Add item to list with ENTER KEY
var totalItems = 0;
var inItemText = document.getElementById("inItemText");
inItemText.focus();
inItemText.onkeyup = function(event) {
if (event.which === 13) {
var itemText = inItemText.value;
if (!itemText || itemText === "") {
return false;
}
addNewItem(document.getElementById("todoList"), itemText);
inItemText.focus();
inItemText.select();
}
}
//Add item to To-Do List with "Add" Button
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = function() {
var itemText = inItemText.value;
if (!itemText || itemText === "") {
return false;
}
addNewItem(document.getElementById("todoList"), itemText);
inItemText.focus();
inItemText.select();
}
Here is the Fiddle: https://jsfiddle.net/Rassisland/7bkcLfhu/
To avoid code duplication, save your function to a variable, and then reference it using as many event handlers are applicable. The important lesson here is you don't always need to use anonymous functions.
;(function(){
"use strict";
var button = document.getElementById('button');
var doStuff = function(event){
// do some stuff
alert('i did some stuff');
};
document.addEventListener('keypress',doStuff);
button.addEventListener('click',doStuff);
})();
<button id="button" name="button">i am a button</button>
<textarea id="textarea" name="textarea">press a key</textarea>

JavaScript and the DOM Manipulation (Creating and Deleting)

So I'm trying to to basically dynamically create li's inside an array, and I would like to create a 'delete' button within each li, so that when I click that li, I can delete that specific li.
I know this seems very basic, but I've been looking at JS for hours now, and am starting to really confuse myself here.
I keep getting errors like addChild() is not a function... I feel like I'm close, but no cigar. Thanks in advance!
Anyway, here's my add function:
function add(){
var deleteBtn = document.createElement('input');
deleteBtn.type = 'submit';
deleteBtn.name = 'addButton';
deleteBtn.className = 'deleteButton';
for(i=0;i<1;i++){
id_number[i] = i+1;
var newSong = '<li class="li_test" id="' + id_number[i] + '">' + "<span>" + "</span>" + '</li>';
// $(newSong).appendChild(deleteBtn);
$(deleteBtn).appendTo("#playlist-1");
$(newSong).appendTo("#playlist-1");
showList.push(newSong);
deleteBtn.addEventListener('click', function(evt) {
deleteFromPlaylist(newSong);
});
}
}
Here's my delete function
function deleteFromPlaylist(newSong){
var deleteBtn = document.getElementsByTagName('deleteButton');
// var deleteMe = deleteBtn.parentNode;
alert(deleteBtn);
for(i=0;i<showList.length;i++){
if(newSong === showList[i]){
showList.splice(i,1);
// var pp = p.parentNode;
// pp.removeChild (p);
deleteMe = deleteMe.parentNode.remove("li_test");
deleteMe.removeChild(deleteBtn);
}
// console.log(deleteMe);
}
}
EDIT: 1 More Related Question
I would like to only add an item if it doesn't exist already in the array. Here is what I have so far. Any tips on where I'm going wrong?
for (i = 0; i < showList.length; i++) {
if (newSong !== showList[i]){
ul_list.innerHTML = newSong;
container_div.appendChild(ul_list); //append the info
container_div.appendChild(deleteBtn);
document.getElementById('playlist-1').appendChild(container_div); //finally add it to the playlist div
showList.push(newSong);
deleteBtn.addEventListener('click', function(evt) {
deleteFromPlaylist(evt, newSong);
});
inc++;
alert("It IS in the Array!");
}else{
alert("This already exists!");
}
}
You seem to have a strange mix of code. Forget the jQuery stuff until you know javascript.
> function add(){
> var deleteBtn = document.createElement('input');
> deleteBtn.type = 'submit';
I don't think that's a good idea. Much better to use type button or a button element.
> deleteBtn.name = 'addButton';
> deleteBtn.className = 'deleteButton';
>
> for(i=0;i<1;i++){
Presumably i will go a bit higher in future. ;-)
> id_number[i] = i+1;
Where did id_number come from?
>
> var newSong = '<li class="li_test" id="' + id_number[i] + '">' + "<span>" + "</span>" + '</li>';
> // $(newSong).appendChild(deleteBtn);
Stick to one method of creating elements. Consider using a document fragment to hold the parts.
> $(deleteBtn).appendTo("#playlist-1");
> $(newSong).appendTo("#playlist-1");
> showList.push(newSong);
Where did showList come from?
> deleteBtn.addEventListener('click', function(evt) {
> deleteFromPlaylist(newSong);
> });
Not all browsers support addEventListener. Since you are only adding one listener, consider just assigning to the button's onclick property. Note that newSong is just a string.
> }
> }
In the other function:
> function deleteFromPlaylist(newSong){
> var deleteBtn = document.getElementsByTagName('deleteButton');
There is no HTML "deleteButton" element, so that will return an empty collection.
> // var deleteMe = deleteBtn.parentNode;
> alert(deleteBtn);
> for(i=0;i<showList.length;i++){
> if(newSong === showList[i]){
> showList.splice(i,1);
> // var pp = p.parentNode;
>
> // pp.removeChild (p);
> deleteMe = deleteMe.parentNode.remove("li_test");
Where did deleteMe come from? You commented out where it was declared and it hasn't been assigned a value, so deleteMe.parentNode will throw an error.
> deleteMe.removeChild(deleteBtn);
> }
> // console.log(deleteMe);
> }
> }
> }
Anyhow, here's some working code, it's still pretty awful but I'll leave it to you go improve it.
<script>
var showList = [];
function add(){
var id_number = [];
var deleteBtn = document.createElement('input');
deleteBtn.type = 'button';
deleteBtn.name = 'addButton';
deleteBtn.className = 'deleteButton';
deleteBtn.value = 'Delete Button';
for (i=0; i<1; i++) {
id_number[i] = i + 1;
// '<li class="li_test" id="' + id_number[i] + '">' + "<span>" + "</span>" + '</li>';
var newSong = document.createElement('li');
newSong.className = 'li_test';
newSong.id = id_number[i];
newSong.appendChild(document.createElement('span').appendChild(document.createTextNode('song')));
showList.push(newSong);
deleteBtn.onclick = (function(id) {
return function(){deleteFromPlaylist(id);}
}(newSong.id));
newSong.appendChild(deleteBtn);
document.getElementById('playlist-1').appendChild(newSong);
}
}
function deleteFromPlaylist(id) {
var song = document.getElementById(id);
if (song) {
song.parentNode.removeChild(song);
}
}
window.onload = function() {
add();
}
</script>
<ul id="playlist-1">
<li>Original
</ul>
I've altered your code and functions to purely use javascript, instead of a mixture containg jquery. I've added comments in the code to explain my actions. If you have any questions, feel free to ask.
var showList = [];
var inc = 1;
function add() {
//create the container element. If we do this, keeping track of all elements
//becomes easier, since we just have to remove the container.
var container_div = document.createElement('div');
container_div.id = "cont_" + inc;
var ul_list = document.createElement('ul');
var deleteBtn = document.createElement('input');
deleteBtn.type = 'button';
deleteBtn.value = 'remove song';
deleteBtn.name = 'addButton';
deleteBtn.className = 'deleteButton';
var id_number = [];
var newSong = "";
for (i = 0; i < 1; i++) {
id_number[i] = i + 1;
newSong += '<li class="li_test" id="cont_' + inc + '_song_id_' + id_number[i] + '">' + "<span>test " + inc + "</span>" + '</li>\n'; //all ids must be unique, so we construct it here
}
ul_list.innerHTML = newSong;
container_div.appendChild(ul_list); //append the info
container_div.appendChild(deleteBtn);
document.getElementById('playlist-1').appendChild(container_div); //finally add it to the playlist div
showList.push(newSong);
deleteBtn.addEventListener('click', function(evt) {
deleteFromPlaylist(evt, newSong);
});
inc++;
}
function deleteFromPlaylist(evt, newSong) {
var deleteBtn = evt.target; //target the button clicked, instead of a list of all buttons
var container_div = deleteBtn.parentNode; //get the parent div of the button
var cont_parent = container_div.parentNode; //and the parent of the container div
for (i = 0; i < showList.length; i++) {
if (newSong === showList[i]) {
showList.splice(i, 1);
}
}
cont_parent.removeChild(container_div); //finally, remove the container from the parent
}
Update:
I've modified the above function to strictly use objects, rather than strings, because it is easier to extract relevant information from objects, than strings.
I've added in comments to assist with understanding the code. Again, if you have any questions, feel free to ask.
function add() {
var list_bool;
//create the container element. If we do this, keeping track of all elements
//becomes easier, since we just have to remove the container.
var container_div = document.createElement('div');
container_div.id = "cont_" + inc;
var ul_list = document.createElement('ul');
var deleteBtn = document.createElement('input');
deleteBtn.type = 'button';
deleteBtn.value = 'remove song';
deleteBtn.name = 'addButton';
deleteBtn.className = 'deleteButton';
var list_item = document.createElement("li"); //create list element
list_item.className = "li_test"; //set element class
var list_span = document.createElement("span"); //create span element
list_span.innerHTML = "test"; //set span text
list_item.appendChild(list_span); //append span to list element
ul_list.appendChild(list_item); //append list element to un-ordered list element
var list_bool = false; //create local boolean variable
if (showList.length > 0) { // loop through showList if it isn't empty
for (var i = 0; i < showList.length; i++) {
if (showList[i].innerText !== list_item.innerText) {
list_bool = true; //if song exists(comparing text values, set bool to true
} else if (showList[i].innerText === list_item.innerText) {
list_bool = false; //else, set it to false
break; //break out of loop.. we don't want it becoming true again, now do we?
}
}
} else {
list_bool = true; //showList is empty, set to true
}
if (list_bool) { //if true, do action of appending to list
container_div.appendChild(ul_list); //append the info
container_div.appendChild(deleteBtn);
document.getElementById('playlist-1').appendChild(container_div); //finally add it to the playlist div
showList.push(list_item);
deleteBtn.addEventListener('click', function(evt) {
deleteFromPlaylist(evt, newSong);
});
inc++;
}
}
DEMO, notice that add() is executed twice, but because the song 'test' already exists, it only executes the end action once.

Categories