by class name counter not work in javascript - javascript

i create a counter.
dk = parseInt(document.querySelector('.dm').innerText);
for (var i = 0; i <= dk; i++) {
(function(i) {
setTimeout(function() {
document.querySelector('.dm').innerText = i;
}, i * 100);
})(i);
}
console.log(dk);
.counter { display: flex; }
.dm {
background: tomato;
padding: 15px;
font-size: 5em;
font-weight: 700;
width: 100px;
height: auto;
text-align: center;
margin: 0 2px;
}
<div class="counter">
<div class="dm">40</div>
<div class="dm">30</div>
</div>
problem is only first div counter is working.
can we parse element of innerHTMl by html dom like classname...i try but result is Nan.
i want run all counter if i add same classname with different inner values.

Your problem is that you are using document.querySelector().
When you use document.querySelector('.dm') it will return only the first element matching this selector, you need to use document.querySelectorAll('.dm') to get all the matching elements.
But with multiple elements you will need a loop to do that, because querySelectorAll() will return a nodeList which is a collection(array).
This is how should be your code:
var elements = document.querySelectorAll('.dm');
Array.from(elements).forEach(function(el, ind){
let dk = parseInt(elements[ind].innerText)
for (var i = 0; i <= dk; i++) {
(function(i) {
setTimeout(function() {
elements[ind].innerText = i;
}, i * 100);
})(i);
}
});
Demo:
var elements = document.querySelectorAll('.dm');
Array.from(elements).forEach(function(el, ind){
let dk = parseInt(elements[ind].innerText)
for (var i = 0; i <= dk; i++) {
(function(i) {
setTimeout(function() {
elements[ind].innerText = i;
}, i * 100);
})(i);
}
});
.counter { display: flex; }
.dm {
background: tomato;
padding: 15px;
font-size: 5em;
font-weight: 700;
width: 100px;
height: auto;
text-align: center;
margin: 0 2px;
}
<div class="counter">
<div class="dm">40</div>
<div class="dm">30</div>
</div>

Your question is not very clear, but if I understood correctly, you want both timer to run simultaneous, right?
If so, then the code below should help.
Use the querySelectorAll() to get all elements with same class, then loop through them to get the value and make it increase like you was doing.
const dms = document.querySelectorAll('.dm');
for (let j = 0; j < dms.length; j++){
let dk = dms[j].innerText;
for(let i = 0; i <= dk; i++){
setTimeout(function() {
dms[j].innerText = i;
}, i * 100);
}
console.log(dk);
}
.counter{
display: flex;
}
.dm {
background: tomato;
padding: 15px;
font-size: 5em;
font-weight: 700;
width: 100px;
height: auto;
text-align: center;
margin: 0 2px;
}
<div class="counter">
<div class="dm">40</div>
<div class="dm">30</div>
</div>

Related

JS todo list item checked, and add item

I am aiming to create a JS todo list similar to https://www.w3schools.com/howto/howto_js_todolist.asp
I have created the basic structure of my todo list application and the function of the close buttons.
These are working well, but I have a problem with adding new todo list items and checking and unchecking todo items.
I'm not sure if I'm using the classlist toggle property well, and also cannot figure why the add button doesn't work at all.
var todoitemlist = document.getElementsByClassName('todo-item');
var i;
for (i = 0; i < todoitemlist.length; i++) {
var span = document.createElement("SPAN");
span.innerHTML = "Close";
span.className = "closebutton";
todoitemlist[i].appendChild(span);
}
var close = document.getElementsByClassName("closebutton");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var listitem = this.parentElement;
listitem.style.display = "none";
}
}
var todoitemlistx = document.getElementsByClassName('todo-item');
//checked element
var i;
for (i = 0; i < todoitemlistx.length; i++) {
todoitemlistx[i].onclick = function(ev) {
ev.style.backgroundColor = "red";
ev.classList.toggle("todo-item-checked");
}
}
//add another list item
function add() {
var listitem = document.createElement("LI");
listitem.className = "todo-item";
var text = document.getElementById('todoinput').value;
var myul = getElementById('todo-list');
var t = document.createTextNode(text);
listitem.appendChild(t);
myul.appendChild(listitem);
var span = document.createElement("SPAN");
span.innerHTML = "Close";
span.className = "closebutton";
listitem[i].appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
* {
box-sizing: border-box;
}
body {
text-align: center;
margin: 0;
padding: 0;
background-color: #dbf9fc;
font-family: Arial, Helvetica, sans-serif;
color: rgba(0, 27, 39);
}
#todoinput {
margin: 5px;
padding: 5px;
width: 65%;
}
#add-button {
padding: 5px;
margin: 5px;
width: 5%;
background-color: rgba(0, 27, 39);
color: #dbf9fc;
border: none;
border-radius: 5px;
height: 1fr;
cursor: pointer;
}
#add-button:hover {
background-color: black;
}
#todo-list {
display: inline-block;
margin: 0;
padding: 0;
list-style: none;
width: 70%;
}
.todo-item {
position: relative;
display: flex;
justify-content: flex-start;
background-color: white;
border: 2px solid black;
padding: 5px;
margin: 5px;
}
.closebutton {
cursor: pointer;
justify-self: flex-end;
background-color: #e6772d;
position: absolute;
right: 0;
top: 0;
color: white;
float: right;
padding: 5px;
width: 30%;
margin: 0;
}
.closebutton:hover {
background-color: #c46526;
}
.todo-item-checked {
position: relative;
display: flex;
justify-content: flex-start;
background-color: rgb(187, 187, 187);
border: 2px solid black;
padding: 5px;
margin: 5px;
text-decoration: line-through;
}
.black {
background-color: black;
}
<main class="centered">
<h1>ToDo List JS</h1>
<h3>js project</h3>
<form action="">
<input type="text" name="" id="todoinput" placeholder="Enter the activity you've wented to do">
<input type="button" value="Add" id="add-button" onclick="add()">
</form>
<ul id="todo-list">
<li class="todo-item">
Hit the lights
</li>
<li class="todo-item">
Hit the lights
</li>
<li class="todo-item">
Hit the lights
</li>
<li class="todo-item-checked todo-item">
Hit the lights
</li>
</ul>
</main>
I remember what it was like starting development and how hard it could be, so I persevered with this.
I thought it would be a few small changes but it turned into a massive rewrite.
Una grande padulo, as the Italians like to say.
I hope you can or try to understand what I did here.
The big lesson would be, don't write the same code twice, put it in a separate function.
So this seems to work.
Let me know if it doesn't.
var todoitemlist=document.getElementsByClassName('todo-item');
for(var i=0;i<todoitemlist.length;i++)
{
myawesomeclosebutton(todoitemlist[i]);
todoitemlist[i].addEventListener('click',myawesomebackground);
}
function myawesomeclosebutton(myawesomeitem)
{
var span=document.createElement('span');
span.innerHTML='Close';
span.className='closebutton';
span.addEventListener('click',myawesomecloseevent);
myawesomeitem.appendChild(span);
}
function myawesomebackground(ev)
{
if(ev.target.style.backgroundColor!='red')
{
ev.target.style.backgroundColor='red';
}
else
{
ev.target.style.backgroundColor='transparent';
}
}
function myawesomecloseevent(event)
{
var div=event.target.parentElement;
div.style.display='none';
}
function add()
{
var listitem=document.createElement('li');
listitem.className='todo-item';
var myawesomeinput=document.getElementById('todoinput');
var text=myawesomeinput.value;
var myul=document.getElementById('todo-list');
var t=document.createTextNode(text);
listitem.appendChild(t);
myul.appendChild(listitem);
listitem.addEventListener('click',myawesomebackground);
myawesomeclosebutton(listitem);
myawesomeinput.value='';
}

Remove the corresponding array object when deleting the <li> element with JS

I'm creating a small landing page that, at the end, is going to pick a random city stored between a choice that the user inputs choose where to go for the next trip. When the user inputs the city name inside the input field, everything is ok, a new list element is created inside the ordered list and the name is pushed into the array (for later on randomly choose between one). But when I'm trying to remove the city name with the close function, the list element correctly disappears, but inside the array, instead of removing the selected item, it removes the object on position 0. I'm trying to figure out what's wrong with my code. Below, the code that I've written so far:
const submitBtn = document.querySelector(".addCity");
const cityList = document.querySelector(".city-ol");
let createdLi = document.getElementsByTagName("li");
const lis = document.querySelectorAll(".city-ol li");
let array = [];
submitBtn.addEventListener("click", newElement);
function newElement() {
let li = document.createElement("li");
let inputValue = document.querySelector(".inputTextField");
let t = document.createTextNode(inputValue.value);
li.appendChild(t);
if (inputValue.value === "") {
alert(
"Attenzione, il campo di inserimento della città è vuoto. Inserire una città."
);
} else {
cityList.appendChild(li);
array.push(inputValue.value);
inputValue.value = "";
}
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
let div = this.parentElement;
div.style.display = "none";
array.splice(close[i], 1);
};
};
};
body {
font-family: "Poppins", sans-serif;
height: 900px;
text-align: center;
}
#landing-section {
height: 100%;
}
.container {
height: 100%;
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(6, 1fr);
gap: 5px;
justify-content: center;
align-content: center;
}
.header {
/* background-color: #935ee9; */
grid-column: 1 / -1;
border: 1px solid #000000;
}
.main-head {
font-size: 3rem;
text-transform: uppercase;
margin-bottom: 0;
}
.main-para {
font-size: 1.2rem;
margin-top: 10px;
}
.cityInput {
display: flex;
justify-content: center;
align-items: center;
/* background-color: #a8d051; */
grid-column: 1 / 2;
grid-row: 2 / 3;
border: 1px solid #000000;
}
.inputTextField {
width: 200px;
}
.cityList {
display: flex;
justify-content: center;
align-items: center;
/* background-color: #a98649; */
grid-column: 1 / 2;
grid-row: 3 / -1;
width: 100%;
border: 1px solid #000000;
}
.city-ol {
font-size: 1.5rem;
width: 100%;
}
.city-ol li:nth-child(odd) {
background: #f9f9f9;
}
li {
margin: 5px 20px;
}
.close {
position: relative;
top: 3px;
float: right;
}
.close:hover {
background-color: #DCDCDC;
color: white;
}
.cityImage {
/* background-color: #14d50e; */
grid-column: 2 / -1;
grid-row: 2 / -1;
border: 1px solid #000000;
}
<section id="landing-section">
<div class="container">
<div class="header">
<h1 class="main-head">Make That Trip</h1>
<p class="main-para">Are we ready to choose our next trip?</p>
</div>
<div class="cityInput">
<input class="inputTextField" type="text" value="" data-type="city" placeholder="Inserisci la meta">
<button class="addCity">Aggiungi</button>
</div>
<div class="cityList">
<table>
<ol class="city-ol">
</ol>
</table>
</div>
<div class="cityImage">City Image</div>
</div>
</section>
Problem FIX can be put 2 ways
When you are adding any any new element all 'close' on dom are added to close[]
Here element is present on DOM, Which get audited during add Element
let div = this.parentElement;
div.style.display = "none";
FIX: Remove it from DOM
let elm = this.parentElement;
elm.remove();
During loop execution i variable will be incrementing as 1 2 3... but it wont be same during function execution
FIX : Delecare i using let
for (let i = 0; i < close.length; i++) {
Thanks to all of your answers I was able to figure out and fix the problem, I will explain it below:
Here I've isolated the text content of the list without the span, so that it matches exactly to the array objects
let textNode = div.childNodes[0],
text = textNode.textContent;
And here, finally, I've set the array.indexOf() to be equal to the isolated text above and then I've checked with an if statement, if the value of index is greater of -1 then trigger the array.splice() method
let index = array.indexOf(text);
if (index > -1) {
array.splice(index, 1);
};

Loops with unexpected result

This is a color guessing game I'm working on. Basically it allows users to select a color out of six, and output correct if the color is the same as mentioned in the title or output try again if the color is wrong. When I try the first game, everything seems fine but when I select play again and select the colors again, an unexpected recursion occurs and I don't know where's the problem. Here is my code:
window.onload = () => {
"use strict";
let header = document.getElementsByTagName("header")[0];
let titleColor = document.getElementById("title_color");
let nav = document.getElementsByTagName("nav")[0];
let newColors = document.getElementById("new_colors");
let prompt = document.getElementById("prompt");
let easy = document.getElementById("easy");
let hard = document.getElementById("hard");
let active = document.getElementsByClassName("active")[0];
let colors = document.querySelectorAll("[id^=color]");
const initialize = () => {
let t = Math.floor(Math.random() * 5);
for (let i = 0; i < colors.length; i++) {
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
colors[i].style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
}
titleColor.innerHTML = colors[t].style.backgroundColor;
addingEventHandlers(t);
}
const addingEventHandlers = t => {
for (let i = 0; i < colors.length; i++) {
colors[i].addEventListener("click", () => {
console.log(i);
if (t === i) {
header.style.backgroundColor = colors[t].style.backgroundColor;
for (let j = 0; j < nav.children.length; j++) {
if (nav.children[j] === active) {
nav.children[j].style.color = "rgb(FF, FF, FF)";
nav.children[j].style.backgroundColor = colors[t].style.backgroundColor;
} else {
nav.children[j].style.color = colors[t].style.backgroundColor;
nav.children[j].style.backgroundColor = "rgb(FF, FF, FF)";
}
}
for (let j = 0; j < colors.length; j++) {
colors[j].style.backgroundColor = colors[t].style.backgroundColor;
}
prompt.innerHTML = "Correct";
newColors.innerHTML = "Play Again";
newColors.addEventListener("click", () => initialize())
} else {
console.log(i);
colors[i].style.transitionProperty = "background-color";
colors[i].style.transitionDuration = "1s";
colors[i].style.transitionTimingFunction = "ease-in-out";
colors[i].style.backgroundColor = "rgb(0, 0, 0)";
prompt.innerHTML = "Try Again";
newColors.innerHTML = "New Colors";
newColors.addEventListener("click", () => initialize())
}
})
}
}
initialize();
}
* {
box-sizing: border-box;
}
body {
margin: 0;
text-transform: uppercase;
font-family:'Courier New', Courier, monospace;
font-weight: normal;
font-size: 100%;
text-align: center;
}
header {
color: white;
background-color: navy;
margin: 0;
}
header>h3 {
font-size: 2em;
margin: 0;
}
header>h1 {
font-size: 4em;
margin: 0;
}
nav {
background-color: white;
color: navy;
position: relative;
height: 38px;
}
nav>button {
background-color: white;
color: navy;
border: none;
font-size: 1.5em;
padding: 5px;
text-transform: uppercase;
}
#new_colors {
position: absolute;
left: 20%;
}
#easy {
position: absolute;
left: 62%;
}
#hard {
position: absolute;
left: 72%;
}
nav>button:not(.active):hover {
cursor: pointer;
background-color: navy;
color: white;
}
button.active {
cursor: pointer;
background-color: navy;
color: white;
border: none;
}
#container {
background-color: black;
display: grid;
grid-gap: 20px;
align-content: center;
justify-content: center;
width: 100%;
height: 792px;
}
[id^=color] {
border-radius: 10px;
background-color: white;
width: 200px;
height: 200px;
}
[id^=color]:hover {
cursor: pointer;
opacity: 0.9;
}
#color1 {
grid-area: 1 / 1 / 2 / 2;
}
#color2 {
grid-area: 1 / 2 / 2 / 3;
}
#color3 {
grid-area: 1 / 3 / 2 / 4;
}
#color4 {
grid-area: 2 / 1 / 3 / 2;
}
#color5 {
grid-area: 2 / 2 / 3 / 3;
}
#color6 {
grid-area: 2 / 3 / 3 / 4;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="keywords" content="color guessing game">
<meta name="description" content="color guessing game">
<meta name="author" content="Nick">
<link rel="stylesheet" href="color_guessing.css">
<script src="color_guessing.js"></script>
</head>
<body>
<header>
<h3>The Great</h3>
<h1 id="title_color"></h1>
<h3>Guessing Game</h3>
</header>
<nav>
<button id="new_colors">New Colors</button>
<button id="prompt"></button>
<button id="easy" >Easy</button>
<button id="hard" class="active">Hard</button>
</nav>
<div id="container">
<div id="color1"></div>
<div id="color2"></div>
<div id="color3"></div>
<div id="color4"></div>
<div id="color5"></div>
<div id="color6"></div>
</div>
</body>
</html>
Just like #Thomas said in the comments you need to check if there is an event already and add an event listener if there is none.
if (!colors[i].onclick) {
// your add event listener code goes here
}
You call addingEventHandlers from within initialise. This means that when initialise is called again (like when you start a new game) you will call addEventListener on the same element a second time, meaning you will call a handler twice when the event occurs. And this only gets worse as you call initialise again and again.
So move the call to addingEventHandlers outside of the initialise function body, so that it only gets called on page load, and then no more.

Call functions instead of reloading page

Basically I have this function that picks two different random images from a folder. At the moment I'm using onClick="window.location.reload() to run the function everytime you click.
Is there anyway I can call the funcion onClick without refreshing the page?
Thanks in advance.
body {
border: 0;
color: #000;
background: #fff;
margin: 0;
padding: 0;
font: 2.1vw/1.2em HelveticaNeue, Arial, sans-serif;
letter-spacing: .02em
}
.logo {
cursor: pointer;
position: fixed;
top: 0;
left: 0;
width: 100vw;
text-align: center;
z-index: 100
}
#one,
#two {
position: fixed;
width: 50vw;
top: 0;
display: table
}
#one {
left: 0;
text-align: right
}
#two {
right: 0;
text-align: left
}
.inner {
display: table-cell;
vertical-align: middle;
height: 100vh;
width: 100vw
}
<script>
var IMG = new Array()
IMG[0] = 'https://cdn.shopify.com/s/files/1/0224/5205/products/Siser_EasyWeed_Bright_Red_2048x.jpg?v=1523704262'
IMG[1] = 'http://thezilla.com/wp-content/uploads/2015/07/blue.png'
IMG[2] = 'http://d18nh7ureywlth.cloudfront.net/wp-content/uploads/6901-vibrant-green.jpg'
var j = 0
var p = IMG.length;
var preBuffer = new Array()
for (i = 0; i < p; i++) {
preBuffer[i] = new Image()
preBuffer[i].src = IMG[i]
}
var WI1 = Math.floor(Math.random() * p);
var WI2 = Math.floor(Math.random() * (p - 1));
if (WI2 >= WI1) {
WI2 += 1;
}
function showImage1() {
document.write('<img src="' + IMG[WI1] + '">');
}
function showImage2() {
document.write('<img src="' + IMG[WI2] + '">');
}
</script>
<div class=logo onClick="window.location.reload()"><span class=inner>( RANDOM DYPTICHS )</span></div>
<div id=one><span class=inner><script>showImage1();</script></span></div>
<div id=two><span class=inner><script>showImage2();</script></span></div>
Ideally, there is no need to use ajax either.
I simply used an addEventListener('click'...) and encapsulated your code.
Click on the screen and the images will change randomly.
To Note: Take into a habit of adding (;) where is needed, Javascript is not strict (unless using "use strict") on colons but it can cause a lot of bugs in the future. Also, use commas (' or ") in your attributes in HTML.
Read Javascript Style Guide written by W3 Schools, they do a
good job explaining to newbies about famous javascript conventions
around the globe.
var IMG = new Array(
'https://i.picsum.photos/id/562/200/200.jpg?hmac=F4ylYRNFPH6rDzYo48_NUieJXXI2yaMl9ElwGeFQHZo',
'https://i.picsum.photos/id/650/200/200.jpg?hmac=gu3C13pBxCSHokbnumczMYlmWRLt3CFGx1sDaPpfRnk',
'https://i.picsum.photos/id/67/200/200.jpg?hmac=sN5XCCMqqmBvgDbYmAowWy2VToCkSYP5igDL_iRxK3M');
function getRandomImagePair() {
var j = 0;
var p = IMG.length;
var preBuffer = new Array();
for (i = 0; i < p; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = IMG[i];
}
WI1 = Math.floor(Math.random() * p);
WI2 = Math.floor(Math.random() * (p - 1));
if (WI2 >= WI1) {
WI2 += 1;
}
document.querySelector('#imgOne').src = IMG[WI1];
document.querySelector('#imgTwo').src = IMG[WI2];
}
getRandomImagePair();
document.querySelector('.logo .inner').addEventListener('click', e => {
getRandomImagePair();
});
body {
border: 0;
color: #000;
background: #fff;
margin: 0;
padding: 0;
font: 2.1vw/1.2em HelveticaNeue, Arial, sans-serif;
letter-spacing: .02em
}
.logo {
cursor: pointer;
position: fixed;
top: 0;
left: 0;
width: 100vw;
text-align: center;
z-index: 100;
}
#one,
#two {
position: fixed;
width: 50vw;
top: 0;
display: table
}
#one {
left: 0;
text-align: right
}
#two {
right: 0;
text-align: left
}
.inner {
display: table-cell;
vertical-align: middle;
height: 100vh;
width: 100vw
}
<div class='logo'><span class='inner'>( RANDOM DYPTICHS )</span></div>
<div id='one'><span class='inner'><img id="imgOne" src="#" /></span></div>
<div id='two'><span class='inner'><img id="imgTwo" src="#" /></span></div>

Javascript - Lists created through user input with a sort button

What I want: User types word into input bar -> user presses Add button -> word is added to two lists "unsortedUL" and "sortedUL" - > user presses Sort button -> the list "sortedUL" gets sorted by descending (z-a), while "unsortedUL" remains exactly how the user inputted it.
I cannot figure out how to get TWO lists while only ONE of them is sorted.
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);
}
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";
}
}
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 a word!");
} else {
document.getElementById("sortedUL").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";
}
}
}
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("sortedUL");
switching = true;
while (switching) {
switching = false;
b = list.getElementsByTagName("LI");
for (i = 0; i < (b.length - 1); i++) {
shouldSwitch = false;
if (b[i].innerHTML.toLowerCase() < b[i + 1].innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
}
if (shouldSwitch) {
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
document.getElementById("date").innerHTML = new Date().toDateString();
document.getElementById("time").innerHTML = new Date().toLocaleTimeString();
body {
margin: 0;
min-width: 250px;
background-color: green;
}
* {
box-sizing: border-box;
}
ul {
margin: 0;
padding: 0;
width: 100%;
float: right;
}
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
list-style-type: number;
background: #eee;
font-size: 18px;
transition: 0.2s;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.header {
background-color: green;
padding: 30px 40px;
color: white;
text-align: center;
}
.header:after {
content: "";
display: table;
clear: both;
}
input {
border: none;
width: 50%;
padding: 10px;
float: center;
font-size: 16px;
}
.addBtn {
padding: 10px;
width: 10%;
background: #d9d9d9;
color: #555;
float: right;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
}
.sortBtn {
padding: 10px;
width: 10%;
background: #d9d9d9;
color: #555;
float: left;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
}
<!DOCTYPE html>
<html>
<title>Assignment Two</title>
<body>
<h1 style="color:white;"align="center"id="date"></h1>
<h1 style="color:white;"align="center"id="time"></h1>
<div id="myDIV" class="header">
<h2 style="margin:5px">Enter a list of words</h2>
<input type="text" id="myInput" placeholder="Word...">
<span onclick="newElement()" class="addBtn">Add</span>
<span onclick="sortList()" class="sortBtn">Sort</span>
</div>
<ul id="sortedUL">
</ul>
<ul id="unsortedUL">
</ul>
</body>
</html>
You have to clone the HTML Node to append it twice.
Or create it twice like I did.
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);
}
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";
}
}
function newElement() {
if (inputValue === '') {
alert("You must write a word!");
} else {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
document.getElementById("sortedUL").appendChild(li);
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
document.getElementById("unsortedUL").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";
}
}
}
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("sortedUL");
switching = true;
while (switching) {
switching = false;
b = list.getElementsByTagName("LI");
for (i = 0; i < (b.length - 1); i++) {
shouldSwitch = false;
if (b[i].innerHTML.toLowerCase() < b[i + 1].innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
}
if (shouldSwitch) {
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
document.getElementById("date").innerHTML = new Date().toDateString();
document.getElementById("time").innerHTML = new Date().toLocaleTimeString();
body {
margin: 0;
min-width: 250px;
background-color: green;
}
* {
box-sizing: border-box;
}
p {
font-size: 16px;
margin-left: 20px;
color: white;
text-transform: uppercase;
}
ul {
margin: 0 0 20px 0;
padding: 0;
width: 100%;
float: right;
}
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
list-style-type: number;
background: #eee;
font-size: 18px;
transition: 0.2s;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.header {
background-color: green;
padding: 30px 40px;
color: white;
text-align: center;
}
.header:after {
content: "";
display: table;
clear: both;
}
input {
border: none;
width: 50%;
padding: 10px;
float: center;
font-size: 16px;
}
.addBtn {
padding: 10px;
width: 10%;
background: #d9d9d9;
color: #555;
float: right;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
}
.sortBtn {
padding: 10px;
width: 10%;
background: #d9d9d9;
color: #555;
float: left;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
}
<!DOCTYPE html>
<html>
<title>Assignment Two</title>
<body>
<h1 style="color:white;"align="center"id="date"></h1>
<h1 style="color:white;"align="center"id="time"></h1>
<div id="myDIV" class="header">
<h2 style="margin:5px">Enter a list of words</h2>
<input type="text" id="myInput" placeholder="Word...">
<span onclick="newElement()" class="addBtn">Add</span>
<span onclick="sortList()" class="sortBtn">Sort</span>
</div>
<p>Sorted</p>
<ul id="sortedUL">
</ul>
<p>Unsorted</p>
<ul id="unsortedUL">
</ul>
</body>
</html>
While you need list you can use Javascript Array
Here you can have two Arrays which would be SortedList and UnsortedList
I have declare both the list globally so that you can sort one list and keep one list without change
Refer The Below Code for the Work Flow
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form>
<div>
<input type="text" name="txtName" id="txtName"/>
<input type="button" value="Add" onclick="AddToList()"/>
<input type="button" value="Sort" onclick="SortList()"/>
</div>
</form>
</body>
</html>
<script>
var sortedList = [];
var unsortedList = [];
function AddToList() {
var data = document.getElementById("txtName").value;
sortedList.push(data);
unsortedList.push(data);
}
function SortList() {
sortedList.sort();
sortedList.reverse();
console.log(sortedList);
console.log(unsortedList);
}
</script>
Here I have created two buttons as you said
And Called a function to sort and other to add in the List.
As you said you need the Unsorted List to be as it is, So in the SortList() function we have printed sortedList and unsortedList Both two see a diffrence.
As expected sortedList will print the descending order data and unsortedList will print normal data.
You just need to insert it into both lists as each word is added, i.e. where you have:
document.getElementById("sortedUL").appendChild(li);
you should add a second line like this:
document.getElementById("unsortedUL").appendChild(li.cloneNode(true));
The node cloning might be what you were missing if you tried it before, otherwise it would move the same element and it ends up in only one list. The 'true' argument makes a deep copy so that the text node underneath it is copied as well.
Incidentally, this whole operation would be a lot easier with jQuery, it's the kind of DOM manipulation that the library was meant for. However people jump to jQuery so quickly and it's good that you are doing it with vanilla JavaScript.

Categories

Resources