Javascript Statistics Calculator - javascript

I am trying to make a JS function that takes in:
- Count of entries
- Minimum of entries
- Maximum of entries
- Range of entries
- Sum of entries
- Average of entries
I am trying to use a loop alert to take in the user input but with no luck, here is my code so far:
<!DOCTYPE html>
<html>
<head>
<script>
function show_prompt() {
i = 1;
do {
var number = prompt("Please Enter a Number");
i++;
if (number % 2) {
document.write("Number: " + number);
document.write("<br>");
}
}
while (i <= 15);
}
show_prompt();
</script>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 55px;
text-decoration: none;
}
li a:hover {
background-color: #111;
}
.tasks {
color: white;
font-size: 250%;
text-align: center;
}
</style>
<body>
</body>
</html>
Many Thanks
James

I tried some codes. Try this snippet.https://jsfiddle.net/2fo8ctgv/2/
var i = 0,
answer=true,
nums=[],
min,
max,
avrg = 0,
sum = 0;
do{
var num;
if(num=prompt('number')){
nums.push(num)
i++;
} else {
answer = false;
}
} while(answer);
nums.forEach(function(c){sum+=c;});
nums.sort(function(a,b){return a-b});
min = nums[0];
max = nums[nums.length-1];
avrg=sum/i;
console.log(min,max,avrg,sum);

Related

trying to make a wordle game, but the letters are going up to down, instead of right to left, i don't know how to tackle it

I am making a 4x4 wordle game, and I used js to make the squares and input letters. When I input letters they go top to bottom instead of left to right and I'm not really sure how to fix it. I don't know how to modify the key events to go from the first column to the second, this is the code that deals with it, but I don't know why it isn't working, i feel like the code that is affecting it is this, but im not sure
if (col < gameWidth) {
let currsquare = document.getElementById(row.toString() + '-' + col.toString());
currsquare.innerText = e.code[3];
col++;
}
var gameHeight = 4; //number of guesses
var gameWidth = 4; //length of the word
var row = 0; //current guess (attempt #)
var col = 0; //current letter for that attempt
var gameOver = false;
var word = "RAAA";
window.onload = function() {
initialize();
};
function initialize() {
const darkModeToggle = document.getElementById("dark-mode-toggle");
darkModeToggle.addEventListener("click", () => {
document.body.classList.toggle("dark");
});
const instructionsToggle = document.getElementById("info");
const instructionsContainer = document.getElementById("instructions-container");
// Hide the instructions by default
instructionsContainer.style.display = "none";
// Show or hide the instructions when the button is clicked
instructionsToggle.addEventListener("click", () => {
if (instructionsContainer.style.display === "none") {
instructionsContainer.style.display = "block";
} else {
instructionsContainer.style.display = "none";
}
});
// Create the game board
for (let i = 0; i < gameHeight; i++) {
let row = document.createElement("div");
row.classList.add("row");
for (let j = 0; j < gameWidth; j++) {
let square = document.createElement("span");
square.id = i.toString() + "-" + j.toString();
square.classList.add("square");
square.innerText = "";
row.appendChild(square);
}
document.getElementById("board").appendChild(row);
}
// Listen for Key Press
document.addEventListener("keyup", (e) => {
if (gameOver) return;
if ("KeyA" <= e.code && e.code <= "KeyZ") {
if (col < gameWidth) {
let currsquare = document.getElementById(row.toString() + '-' + col.toString());
currsquare.innerText = e.code[3];
col++;
}
} else if (e.code == "Backspace") {
if (col > 0) {
col--;
let currsquare = document.getElementById(row.toString() + '-' + col.toString());
currsquare.innerText = "";
}
} else if (e.code == "Enter") {
update();
row += 1; // start new row
col = 0; // reset current index to 0 for new row
}
if (!gameOver && row == gameHeight) {
gameOver = true;
document.getElementById("answer").innerText = word;
}
});
}
function update() {
let correct = 0;
for (let column = 0; column < gameWidth; column++) {
let currsquare = document.getElementById(row.toString() + '-' + column.toString());
let letter = currsquare.innerText;
// Is it in the correct position?
if (word[row*gameWidth + (column % gameWidth)] == letter) {
currsquare.classList.add("correct");
correct += 1;
} // Is it in the word?
else if (word.includes(letter)) {
currsquare.classList.add("present");
} // Not in the word
else {
currsquare.classList.add("absent");
}
}
if (correct == gameWidth) {
gameOver = true;
document.getElementById("congrats").style.display = "block";
}
if (!gameOver && row == gameHeight - 1) {
gameOver = true;
document.getElementById("answer").innerText = word;
}
}
this is the updated html
<html>
<head>
<title>Wordle</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale = 1.0">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.15.3/css/all.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
<link rel="stylesheet" href="wordle.css">
</head>
<body>
<h1 id="title">Wordle</h1>
<i id = "info" class="fas fa-info-circle"></i>
<i id="dark-mode-toggle" class="fas fa-circle"></i>
<hr>
<br>
<div id="board">
</div>
<br>
<div id="instructions-container">
<p>The goal is to guess the word </p>
</div>
<img id="congrats" src="https://res.cloudinary.com/mkf/image/upload/v1675467141/ENSF-381/labs/congrats_fkscna.gif" alt="Congratulations">
<script src="wordle.js"></script>
</html>
This is the updated css
body {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
--correct:#6baa64;
--background-color:white;
--text-color:black;
color: var(--text-color);
background-color: var(--background-color);
}
body.dark{
font-family: Arial, Helvetica, sans-serif;
text-align: center;
--correct:#6baa64;
--background-color:black;
background-color: var(--background-color);
--text-color:white;
color:white;
}
hr {
width: 500px;
}
#title {
font-size: 36px;
font-weight: bold;
letter-spacing: 2px;
}
#board {
width: 350px;
height: 420px;
margin: 0 auto;
margin-top: 3px;
display: flex;
flex-wrap: wrap;
}
.square {
border: 2px solid lightgray;
width: 60px;
height: 60px;
margin: 2.5px;
color: black;
font-size: 36px;
font-weight: bold;
display: flex;
justify-content: center;
align-items: center;
}
.correct {
background-color: var(--correct);
color: white;
border-color: white;
}
.present {
background-color: #C9B458;
color: white;
border-color: white;
}
.absent {
background-color: #787C7E;
color: white;
border-color:white;
}
#congrats {
display: none;
}
#dark-mode-toggle {
position: fixed;
top: 10px;
right: 250px;
}
#question{
position: fixed;
top: 10px;
right: 200px;
}
#info{
position: fixed;
top: 10px;
right: 300px;
}
You dont need display: flex; in board but you need to add display: flex; to row
#board {
width: 350px;
height: 420px;
margin: 0 auto;
margin-top: 3px;
}
.row {
display: flex;
}

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.

how can i get a listbox in my Word counter?

I am trying to create an online word counter. HTML+JS.
I tried inserting a calculation based on the words counted. For example if we have 156 words, I would like to have 2 choices to multiply "156".Select list box "X 2", "X 3" and get result selected in a box => RESULT ► 312
How to do that?
The answer matches with the following phrase.
For example if we have 156 words, I would like to have 2 choices to
multiply "156".Select list box "X 2", "X 3" and get result selected in
a box => RESULT ► 312
$('.selectpicker').change(calcVal);
function calcVal() {
var p = $(this).parent().parent()
var m = p.find('input.txtMult')
var mul = parseInt($(m[0]).val())
$("#grandTotal").html($(this).children(':checked').data('cubics') * mul)
}
// call on document load
calcVal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<input type="text" value="" class="txtMult"/>
<select class="selectpicker">
<option data-cubics='2'>X 2</option>
<option data-cubics='3'>X 3</option>
</select>
<span id="grandTotal">Value Shows here</span>
</div>
</div>
/*
**
** User stories:
** - Shows number of characters, words, sentences, paragraphs - Done
** - Show reading time - Done
** - Show keyword count - Done
** - Show reading level (Optional - how?) - Done
** - Above data should change/appear on every keypress - Done
**
*/
// Readability (Mashape) API Key for testing: PQ4FOFuaR6mshI6qpnQKQvkDZQXjp1o6Zcqjsnug7GvNggTzUE
"use strict";
var input = document.querySelectorAll('textarea')[0],
characterCount = document.querySelector('#characterCount'),
wordCount = document.querySelector('#wordCount'),
sentenceCount = document.querySelector('#sentenceCount'),
paragraphCount = document.querySelector('#paragraphCount'),
readingTime = document.querySelector('#readingTime'),
readability = document.querySelector('#readability'),
keywordsDiv = document.querySelectorAll('.keywords')[0],
topKeywords = document.querySelector('#topKeywords');
$('.selectpicker').change(calcVal);
function calcVal() {
var p = $(this).parent().parent()
var m = p.find('input.txtMult')
var mul = parseInt($(m[0]).val())
$("#grandTotal").html($(this).children(':checked').data('cubics') * mul)
}
// call on document load
calcVal();
// updating the displayed stats after every keypress
input.addEventListener('keyup', function() {
//keeping the console clean to make only the latest data visible
console.clear();
// character count
// just displaying the input length as everything is a character
characterCount.innerHTML = input.value.length;
// word count using \w metacharacter - replacing this with .* to match anything between word boundaries since it was not taking 'a' as a word.
// this is a masterstroke - to count words with any number of hyphens as one word
// [-?(\w+)?]+ looks for hyphen and a word (we make both optional with ?). + at the end makes it a repeated pattern
// \b is word boundary metacharacter
var words = input.value.match(/\b[-?(\w+)?]+\b/gi);
// console.log(words);
if (words) {
wordCount.innerHTML = words.length;
} else {
wordCount.innerHTML = 0;
}
// sentence count using ./!/? as sentense separators
if (words) {
var sentences = input.value.split(/[.|!|?]+/g);
console.log(sentences);
sentenceCount.innerHTML = sentences.length - 1;
} else {
sentenceCount.innerHTML = 0;
}
// paragraph count from http://stackoverflow.com/a/3336537
if (words) {
// \n$ takes care of empty lines: lines with no characters, and only \n are not paragraphs
// and need to be replaced with empty string
var paragraphs = input.value.replace(/\n$/gm, '').split(/\n/);
paragraphCount.innerHTML = paragraphs.length;
} else {
paragraphCount.innerHTML = 0;
}
// console.log(paragraphs);
// reading time based on 150 words/minute
if (words) {
var seconds = Math.floor(words.length * 60 / 150);
// need to convert seconds to minutes and hours
if (seconds > 59) {
var minutes = Math.floor(seconds / 60);
seconds = seconds - minutes*60;
readingTime.innerHTML = minutes + "m "+ seconds + "s";
} else {
readingTime.innerHTML = seconds + "s";
}
} else {
readingTime.innerHTML = "0s";
}
// finding out top keywords and their count
// step-1: remove all the stop words
// step-2: form an object with keywords and their count
// step-3: sort the object by first converting it to a 2D array
// step-4: display top 4 keywords and their count
if (words) {
// step-1: removing all the stop words
var nonStopWords = [];
var stopWords = ["à","allô","aucuns","auriez","auxdits","aviez","ayons","bof","çà","certaines","chez","comment","da","desquels","deviez","devras","doit","dues","dût","es","êtes","eurêka","excepté","fouchtra","fûmes","ho","hurrah","laquelle","leur","mazette","mâtin","ne","nulle","or","outre","pas","plein","pourraient","pourvu","pouviez","puis","pussent","que","quoi","saperlipopette","serait","sien","sommes","ta","telles","touchant","une","veuillez","voilà","voudrez","voulante","voulue","vôtre afin","alors","auquel","aurions","auxquelles","avions","aïe","boum","car","certains","chic","concernant","dans","devaient","devions","devrez","doive","duquel","eh","et","étiez","eus","eûmes","furent","fût","holà","hé","le","leurs","me","miséricorde","ni","nulles","ôté","palsambleu","patatras","plouf","pourrais","pouvaient","pouvions","puisque","put","quel","quoique","sapristi","seras","sienne","son","tandis","tels","tous","unième","veuillons","vos","voudriez","voulantes","voulues","vôtres ah","apr.","aura","aurons","auxquels","avoir","bah","bravissimo","ce","ces","chiche","contre","de","devais","devoir","devriez","doivent","durant","elle","étaient","étions","eusse","eût","fus","fûtes","hop","il","ledit","lorsque","merci","moi","nonobstant","nuls","ou","pan","pechère","plus","pourrait","pouvais","pouvoir","puisse","pécaïre","quelle","rataplan","sauf","serez","siennes","sont","tant","tes","tout","unièmes","veulent","votre","voudrions","voulants","voulurent","zut ai","as","aurai","auront","avaient","avons","basta","bravo","ceci","cet","chouette","corbleu","debout","devait","devons","devrions","doives","durent","elles","étais","être","eussent","eûtes","fusse","grâce","hormis","ils","lequel","lui","merde","moins","nos","ô","où","par","pendant","plusieurs","pourras","pouvait","pouvons","puissent","pût","quelles","revoici","se","seriez","siens","sous","taratata","tien","toute","v'lan","veut","voudra","voudrons","voulez","voulus","aie","attendu","auraient","autant","avais","ayant","beaucoup","ç'a","cela","cette","chut","coucou","depuis","devant","devra","devrons","donc","dus","en","était","eu","eusses","évohé","fussent","ha","hors","jarnicoton","les","là","mes","mon","notre","oh","ouais","parbleu","peu","pouah","pourrez","pouvant","psitt","puisses","qq.","quelqu'un","revoilà","selon","serions","sinon","soyez","tayaut","tienne","toutes","va","veux","voudrai","voudront","vouliez","voulussent","aient","au","aurais","autre","avait","ayante","bernique","ç'aura","celle","ceux","ciao","couic","des","devante","devrai","devront","dont","dussent","encontre","étant","eue","eussiez","évoé","fusses","hein","hou","je","lesdites","ma","mien","morbleu","nôtre","ohé","ouf","parce","peuchère","pour","pourriez","pouvante","pst","puissiez","qqch.","quelqu'une","rien","sera","serons","soi","soyons","taïaut","tiennes","tu","vers","via","voudraient","voulaient","voulions","voulut","aies","aucun","aurait","autres","avant","ayantes","bien","ç'aurait","celles","chacun","clic","crac","desdites","devantes","devraient","dia","du","dut","endéans","étante","eues","eussions","fi","fussiez","hem","hourra","jusque","lesdits","made","mienne","motus","nôtres","olé","ouille","pardi","peut","pourquoi","pourrions","pouvantes","pu","puissions","qqn","quels","sa","serai","seront","soient","stop","te","tiens","tudieu","veuille","vivement","voudrais","voulais","vouloir","voulût","ait","aucune","auras","aux","avec","ayants","bigre","ç'avait","celui","chacune","clac","cric","desdits","devants","devrais","diantre","dudit","dès","entre","étantes","euh","eut","fichtre","fussions","hep","hue","la","lesquelles","mais","miennes","moyennant","nous","on","oust","pardieu","peuvent","pourra","pourrons","pouvants","pue","purent","quand","qui","sacristi","seraient","ses","sois","suis","tel","toi","turlututu","veuillent","vlan","voudrait","voulait","voulons","vous","al.","aucunes","aurez","auxdites","avez","ayez","bis","ça","cependant","chaque","comme","crénom","desquelles","devez","devrait","dois","due","dû","envers","étants","eurent","eux","fors","fut","heu","hum","ladite","lesquels","malgré","miens","na","nul","ont","ouste","parmi","peux","pourrai","pourront","pouvez","pues","pus","quant","quiconque","sans","serais","si","soit","sur","telle","ton","un","veuilles","voici","voudras","voulant","voulu","vu"];
for (var i = 0; i < words.length; i++) {
// filtering out stop words and numbers
if (stopWords.indexOf(words[i].toLowerCase()) === -1 && isNaN(words[i])) {
nonStopWords.push(words[i].toLowerCase());
}
}
// console.log(nonStopWords);
// step-2: forming an object with keywords and their count
var keywords = {};
for (var i = 0; i < nonStopWords.length; i++) {
// checking if the word(property) already exists
// if it does increment the count otherwise set it to one
if(nonStopWords[i] in keywords) {
keywords[nonStopWords[i]] += 1;
} else {
keywords[nonStopWords[i]] = 1;
}
}
// step-3: sorting the object by first converting it to a 2D array
var sortedKeywords = [];
for (var keyword in keywords){
sortedKeywords.push([keyword, keywords[keyword]])
}
sortedKeywords.sort(function(a, b) {return b[1] - a[1]});
// console.log(sortedKeywords);
// step-4: displaying top 4 keywords and their count
topKeywords.innerHTML = "";
for (var i = 0; i < sortedKeywords.length && i < 4; i++) {
var li = document.createElement('li');
li.innerHTML = "<b>" + sortedKeywords[i][0] + "</b>: " + sortedKeywords[i][1];
topKeywords.appendChild(li);
}
}
// displaying top keywords only if there is a word in the text area
if (words) {
keywordsDiv.style.display = "block";
} else {
keywordsDiv.style.display = "none";
}
});
// readability level using readability-metrics API from Mashape
readability.addEventListener('click', function() {
// placeholder until the API returns the score
readability.innerHTML = "Fetching score...";
var requestUrl = "https://ipeirotis-readability-metrics.p.mashape.com/getReadabilityMetrics?text=";
var data = input.value;
var request = new XMLHttpRequest();
request.open('POST', encodeURI(requestUrl + data), true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader("X-Mashape-Authorization", "PQ4FOFuaR6mshI6qpnQKQvkDZQXjp1o6Zcqjsnug7GvNggTzUE");
request.send();
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
readability.innerHTML = readingEase(JSON.parse(this.response).FLESCH_READING);
} else {
// We reached our target server, but it returned an error
readability.innerHTML = "Not available.";
}
};
request.onerror = function() {
// There was a connection error of some sort
readability.innerHTML = "Not available.";
};
});
// function to convert FLESCH READING SCORE into meaningful string.
function readingEase(num) {
switch(true) {
case (num <= 30):
return "Readability: College graduate.";
break;
case (num > 30 && num <= 50):
return "Readability: College level.";
break;
case (num > 50 && num <= 60):
return "Readability: linéaire.";
break;
case (num > 60 && num <= 70):
return "Readability: 8th - 9th grade.";
break;
case (num > 70 && num <= 80):
return "Readability: fluide.";
break;
case (num > 80 && num <= 90):
return "Readability: 6th grade.";
break;
case (num > 90 && num <= 100):
return "Readability: 5th grade.";
break;
default:
return "Not available.";
break;
}
}
/*
Reset CSS:
http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* Alignement à droite */
.right {
text-align: right;
float: no;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/* End of reset CSS */
/* border box */
html {
box-sizing: border-box;
-webkit-user-select: none; /* Chrome all / Safari all */
-moz-user-select: none; /* Firefox all */
-ms-user-select: none; /* IE 10+ */
user-select: none; /* Likely future */
}
*, *:before, *:after {
box-sizing: inherit;
}
b {
font-weight: bold;
}
/* main app styles */
body {
width: 800px;
margin: 0 auto;
background-color: #FAFAFA;
font-family: 'Source Sans Pro', sans-serif;
color: #111;
}
.container {
margin: 2% auto;
padding: 15px;
background-color: #FFFFFF;
-webkit-box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
}
h1 {
font-size: 3rem;
font-weight: 900;
text-align: center;
margin: 1% 0 3%;
}
textarea {
width: 100%;
height: 250px;
padding: 10px;
border: 1px solid #d9d9d9;
outline: none;
font-size: 1rem;
resize: none;
line-height: 1.5rem;
}
textarea:hover {
border-color: #C0C0C0;
}
textarea:focus {
border-color: #4D90FE;
}
.output.row {
width: 100%;
border: 1px solid #DDD;
font-size: 1.2rem;
margin: 1% 0;
background-color: #F9F9F9;
}
.output.row div {
display: inline-block;
width: 42%;
padding: 10px 25px;
margin: 1%;
}
.output.row span {
font-weight: bold;
font-size: 1.5rem;
}
#readability {
width: 52%;
font-weight: bold;
}
#readability:hover {
background-color: #4D90FE;
color: #FFF;
border-radius: 2px;
cursor: pointer;
}
#readability:active {
background-color: #307AF3;
}
.keywords {
display: none;
margin: 4% 0 0;
font-size: 2rem;
font-weight: 900;
}
.keywords ul {
font-weight: 400;
border: 1px solid #DDD;
font-size: 1.2rem;
background-color: #F9F9F9;
margin: 2% 0;
}
.keywords li {
display: inline-block;
width: 44%;
padding: 10px;
margin: 1%;
}
/*
** Making it responsive
*/
#media (max-width: 750px) {
body {
width: 600px;
}
.output.row {
font-size: 1.2rem;
}
.output.row span {
font-size: 1.3rem;
}
.keywords ul {
font-size: 1.2rem;
}
}
#media (max-width: 600px) {
/* rewriting old styles */
body {
width: 95%;
}
.output.row {
border: none;
background-color: #FFF;
}
.output.row div {
display: block;
width: 100%;
padding: 10px 15px;
margin: 2% auto;
border: 1px solid #DDD;
font-size: 1.8rem;
background-color: #F9F9F9;
}
.output.row span {
font-size: 2rem;
}
#readability {
width: 100%;
font-size: 1.6rem;
font-weight: 400;
}
.keywords {
margin: 10% auto;
}
.keywords ul {
font-weight: 400;
border: none;
font-size: 1.8rem;
background-color: #F9F9F9;
margin: 5% 0;
}
.keywords li {
display: block;
width: 100%;
padding: 10px;
margin: 2% auto;
border: 1px solid #DDD;
}
}
<!DOCTYPE html>
<html>
<head>
<title>JS</title>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,900' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta name="description" content="A word counter built in HTML/CSS/JS. Shows number of characters, words, reading time and readability score. Also generates a list of top keywords.">
</head>
<body>
<div class="container">
<h1>JS</h1>
<textarea placeholder="Collez ici..."></textarea>
<div class="right">
Réinitialiser JS
</div>
<div class="output row">
<div>DURÉE ► <span id="readingTime">0</span></div>
<div>NOMBRE DE MOTS ► <span id="wordCount">0</span></div>
</div>
<div class="output row">
<div>PHRASES ► <span id="sentenceCount">0</span></div>
<div>PARAGRAPHES ► <span id="paragraphCount">0</span></div>
</div>
<div class="output row">
<div>CHARACTÈRES ► <span id="characterCount">0</span></div>
<div id="readability">Show readability score.</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<input type="text" value="" class="txtMult"/>
<select class="selectpicker">
<option data-cubics='2'>X 2</option>
<option data-cubics='3'>X 3</option>
</select>
<span id="grandTotal">Value Shows here</span>
</div>
</div>
<div>
<input type="checkbox" id="option20" name="option20">
<label for="option20">+20€</label>
</div>
<div class="keywords">
Mots les plus utilisés :
<ul id="topKeywords">
</ul>
</div>
<div class="">
<span> PRIX :</span><span id="sp_prix"></span>
</div>
</div>
</body>
</html>

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.

Targeting and Manipulating setInterval Timer Value [duplicate]

This question already has answers here:
Changing the interval of SetInterval while it's running
(17 answers)
Closed 5 years ago.
I have a simple function that changes the color of a square from red to blue every 2 seconds. I need the speed of the setInterval to reflect the value in the counter. I can't seem to figure out how to target the time value in the setInterval. No jQuery, thanks. Heres a demo of my code.
function Tempo() {
var tempoVal = document.getElementById("tempo-value");
var tempoBtn = tempoVal.querySelectorAll("[data-btn]");
var tempoNum = tempoVal.querySelector("[data-value]");
for (var i = 0; i < tempoBtn.length; i++) {
tempoBtn[i].onclick = function() {
if (this.getAttribute("data-btn") == "-") {
tempoNum.innerHTML = parseFloat(tempoNum.innerHTML) - 1;
} else if (this.getAttribute("data-btn") == "+") {
tempoNum.innerHTML = parseFloat(tempoNum.innerHTML) + 1;
}
};
}
}
let myTempo = new Tempo(document.getElementById("tempo-value"));
//BLOCK
setInterval(function() {
var block = document.getElementById("block");
block.classList.toggle("color");
}, 2000);
#tempo-value {
font-family: Sans-Serif;
font-size: 24px;
text-align: center;
padding: 16px;
user-select: none;
}
.btn {
display: inline-flex;
cursor: pointer;
}
.value {
display: inline-block;
width: 40px;
text-align: right;
}
#block {
width: 100px;
height: 100px;
background-color: red;
margin: 0 auto;
}
#block.color {
background-color: blue;
}
<div id="tempo-value">
<div data-btn='-' class="btn">&#9669</div>
<div data-value class="value">1</div><span> second(s)</span>
<div data-btn='+' class="btn">&#9659</div>
</div>
<div id="block"></div>
You can assign setTimeout / setInterval to a variable. Then use clearTimeout / clearInterval to remove it when necessary. Then set new one again. See code below:
function Tempo() {
var toggle = function() {
document.getElementById('block')
.classList.toggle('color');
}
var t = 1000;
var blink = setInterval(toggle, t);
var tempoVal = document.getElementById('tempo-value');
var tempoBtn = tempoVal.querySelectorAll('[data-btn]');
var tempoNum = tempoVal.querySelector('[data-value]');
for (var i = 0; i < tempoBtn.length; i++) {
tempoBtn[i].onclick = function() {
clearInterval(blink);
tempoNum.innerHTML = +
this.getAttribute('data-btn') +
+tempoNum.innerHTML;
t = 1000 * tempoNum.innerHTML;
blink = setInterval(toggle, t);
}
}
};
let myTempo = new Tempo(document.getElementById('tempo-value'));
body,
html {
height: 100%;
}
#tempo-value {
font-family: Sans-Serif;
font-size: 24px;
text-align: center;
padding: 16px;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.btn {
display: inline-flex;
cursor: pointer;
}
.value {
display: inline-block;
width: 40px;
text-align: right;
}
#block {
width: 100px;
height: 100px;
background-color: red;
margin: 0 auto;
}
#block.color {
background-color: blue;
}
<div id="tempo-value">
<div data-btn='-1' class="btn">&#9669</div>
<div data-value class="value">1</div><span> second(s)</span>
<div data-btn='+1' class="btn">&#9659</div>
</div>
<div id="block"></div>

Categories

Resources