script which loads consecutive numeric values until 0 is encountered, then find the highest value among the given numbers my script below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!---Napisz skrypt który pozwoli na wczytanie kolejnych wartości liczbowych aż do napotkania 0 następnie
wsród podanych liczb znajdź wartość największą-->
<script>
let tab = [], i = 0, max, min;
//wczytywanie danych
do
{
tab[i] = parseInt(prompt("Podaj jakąś wartość. \n Zero kończy wprowadzanie danych:"));
i++;
}
while(tab[i-1]);
max = tab[0]; min = tab[0];
for(i=1; i < tab.length-1; i++)
{
if(tab[i]>max) max = tab[i];
}
document.write()
</script>
</body>
</html>
How to fix it?
if,else it should show the biggest and the lowest typed number
you can do something like this
const numbers = []
while(true) {
const num = parseInt(prompt('Insert a number. zero to exit'))
if(num === 0){
break;
}
numbers.push(num)
console.log(`the max number entered is ${Math.max(...numbers)}`)
console.log(`the min number entered is ${Math.min(...numbers)}`)
}
Window.prompt() is easy to write in your code, but the experience it creates for the user can be quite disruptive. From the linked MDN documentation:
Dialog boxes are modal windows; they prevent the user from accessing the rest of the program's interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box (or modal window).
In the case of your question, making use of a number input provides multiple advantages (non-blocking, built-in validation, etc.)
Here's an example of using a number input element and keeping track of the user's input history, which allows for an always updated value for min and max as the user commits new values:
If you want to prevent input of duplicate values, you could use a Set instead of an array.
const numbersElm = document.getElementById('numbers');
const minElm = document.getElementById('min');
const maxElm = document.getElementById('max');
const input = document.querySelector('input');
const button = document.querySelector('button');
const state = {
numbers: [],
min: NaN,
max: NaN,
};
// Allow the user to commit values using the keyboard's Enter key:
input.addEventListener('keyup', (ev) => {
if (ev.key === 'Enter') handleCommit();
});
// Or by clicking the button:
button.addEventListener('click', handleCommit);
function updateOutput () {
numbersElm.textContent = state.numbers.join(', ');
if (Number.isFinite(state.min)) minElm.textContent = state.min;
if (Number.isFinite(state.max)) maxElm.textContent = state.max;
}
function parseInput () {
const trimmed = input.value.trim();
// Avoid invalid (or a lack of) input:
if (!trimmed) return NaN;
const number = Number(trimmed);
if (Number.isNaN(number)) return NaN;
// You can return the valid number now:
// return number;
// Or convert it to an integer first:
return parseInt(number, 10);
}
function handleCommit () {
const number = parseInput();
// Cancel if the input is not valid:
if (Number.isNaN(number)) {
// Select the value in the input
// so that the user can overwrite it easily (or modify it):
input.select();
return;
}
state.numbers.push(number);
state.min = Math.min(...state.numbers);
state.max = Math.max(...state.numbers);
updateOutput();
// Clear the input so that the user doesn't have to:
input.value = '';
input.focus();
}
* { box-sizing: border-box; } body, button { font-family: sans-serif; font-size: 1rem; } input[type="number"], #numbers { font-family: monospace; } button, input { font-size: 1rem; padding: 0.5rem; } #output { margin-bottom: 1rem; display: flex; flex-direction: column; gap: 1rem; }
<div id="output">
<div id="numbers">Commit a number to get started</div>
<div>Min: <span id="min"></span></div>
<div>Min: <span id="max"></span></div>
</div>
<input type="number" />
<button>Commit number</button>
Related
this is my code:
const clcBtn = document.getElementById("calcButton");
let clcInput = document.getElementById("calcInput");
const result = document.getElementById('paragraph');
const loader = document.getElementById('spinner');
clcBtn.addEventListener("click", calcFunc);
function calcFunc() {
loader.classList.add("display")
fetch(`http://localhost:5050/fibonacci/`).then(function (response) {
return response.json().then(function (data) {
result.innerHTML = data.clcInput.value; // i want to get the input value from the input field and the server to calculate it and present it to the user.
});
});
}
basically what i want to do, is to add the value the user types in to the innerHTML paragraph id name.
and then i want to make the button react to the click and re-display the "loader" (which i gave it display:none in the CSS file)
and then, i need to make the button to display an error message if the input is higher than 50.
what i have tried to do:
inside the
clcBtn.addEventListener("click", calcFunc);
function calcFunc() {
i have tried to add:
loader.classlist.add("display")
and inside
return response.json().then(function (data) {
result.innerHTML = data.clcInput.value;
i have tried to add and change it to:
clcInput.value = innerHTML.result;
what am i doing wrong?
what is wrong with my syntax and what is the order i need to write everything?
thank you!!!
If i understand correctly what is you need, you should look at the small snippets I did below. It show a loader during the API Call and hide it when you get the result as well as updating the info paragraph depending on the value you typed.
The main thing I recommend you changing in order for your code to work properly is not adding or removing a class to your spinner element to hide it and show it, but simply changing directly it's style by using loader.style.display = "value"
Hope it helps.
const clcBtn = document.getElementById("calcButton");
let clcInput = document.getElementById("calcInput");
const result = document.getElementById('paragraph');
const loader = document.getElementById('spinner');
clcBtn.addEventListener("click", calcFunc);
function calcFunc() {
paragraph.innerText= "";
loader.style.display = "block";
// TimeOut to simulate API Call
setTimeout(function() {
loader.style.display = "none";
if (clcInput.value > 50) {
paragraph.innerText = clcInput.value + " - Error, value too high";
} else {
paragraph.innerText = clcInput.value + " - Value correct";
}
}, 2000);
}
#spinner {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: white;
border: 5px solid black;
display: none;
}
<input type="number" id="calcInput" />
<button id="calcButton">calcButton</button>
<div id="spinner"></div>
<p id="paragraph"></p>
I had an issue inside my code, there it is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function typeWriter() {
function genOutput() {
function genText() {
//generate random alphabet via ASCII char code
return String.fromCharCode(0|Math.random()*26+97);
}
const text = document.getElementById("genText");
text.textContent = genText() + text.textContent;
}
const text = document.getElementById("genText");
const score = document.getElementById("scoreBoard");
text.textContent = "";
window.setInterval(genOutput, 400); //automatically generate one charracter per 0.4 sec
document.addEventListener('keypress', (e) => {
const input = String.fromCharCode(e.charCode);
const lastCharacter = text.textContent.charAt(text.textContent.length-1);
if (input == lastCharacter) {
const newText = text.textContent.slice(0, -1);
text.textContent = newText;
score.innerText = "" + (parseInt(score.innerText)+3);
}
else if (input == " ") {
//check if user type space bar
alert("Click to continue"); //if remove this alert will occur exception
}
else {
score.innerText = "" + (parseInt(score.innerText)-1);
}
})
}
</script>
<div class="container">
<p id="title">Typewriter 2.0</p>
</div>
<div class="container">
<h1 id="genText">Typed correct +3 pt, incorrect -1 pt</h1><br>
<button id="startBtn" onclick="typeWriter()">Click to Start</button>
<span>Score: </span><span id="scoreBoard">10</span>
</div>
</body>
</html>
The simple code above is a typewriter web game, it generates an alphabet randomly every 400ms, and removes the last character if a user types correctly. However, the issue is, that when the user types the space bar, the countdown of the interval restart and generate more and more alphabet at one time. I tried to check if the user types the space bar and inserts the alert function, it can prevent the exception occur, but somehow it became a pause button. Can anyone explain to me how and why this exception happens? Thank you so much!
Your click to start button has focus after it is pressed, so spacebar will act to click the button again.
The alert caused focus to move away from the button, which is why spacebar no longer fired the event.
If you want to remove focus, you can add a blur event (on the button) to remove focus so spacebar won't function to click the button
e.target.blur();
In the event listener, e.target is the button that was clicked, so we can programmatically fire the blur event
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function typeWriter() {
function genOutput() {
function genText() {
//generate random alphabet via ASCII char code
return String.fromCharCode(0|Math.random()*26+97);
}
const text = document.getElementById("genText");
text.textContent = genText() + text.textContent;
}
const text = document.getElementById("genText");
const score = document.getElementById("scoreBoard");
text.textContent = "";
window.setInterval(genOutput, 400); //automatically generate one charracter per 0.4 sec
document.addEventListener('keypress', (e) => {
e.target.blur(); // remove focus from the button so spacebar won't continue game
const input = String.fromCharCode(e.charCode);
const lastCharacter = text.textContent.charAt(text.textContent.length-1);
if (input == lastCharacter) {
const newText = text.textContent.slice(0, -1);
text.textContent = newText;
score.innerText = "" + (parseInt(score.innerText)+3);
}
else if (input == " ") {
//check if user type space bar
// alert("Click to continue"); //if remove this alert will occur exception
}
else {
score.innerText = "" + (parseInt(score.innerText)-1);
}
})
}
</script>
<div class="container">
<p id="title">Typewriter 2.0</p>
</div>
<div class="container">
<h1 id="genText">Typed correct +3 pt, incorrect -1 pt</h1><br>
<button id="startBtn" onclick="typeWriter()">Click to Start</button>
<span>Score: </span><span id="scoreBoard">10</span>
</div>
</body>
</html>
Hope someone can help. Bit difficult to explain but I have just finished and submitted my code for a challenge and although I met the basic requirements for the challenge, I decided to add an animation as a little extra.
We were given some code that randomly generated a new set of numbers within arrays every-time the browser window was refreshed. My job was to total up the numbers in the array and build an app which used a next and previous button to iterate through the arrays. The buttons triggered a condition, if the total amount of money was > than the given price of something (true) then a message should display something like "you can afford" else (false) "you can't afford.
If you clicked previous or next it iterated back and forth through the random generated array. eg if I clicked next it would generate a new set of random numbers and as a result a new total and either true or false against the condition.
I added an animation into the mix to be triggered by the above condition so if it displayed "you can afford" the animation is added and run and removed "if you can't afford".
The code works if I hit next and have a true condition preceding a false condition and vice vera.
However if I have a true condition following another true condition after clicking next then the animation only runs on the first true condition.
I hope that makes sense and here is my code. Apologies for the amount of code but I think it explains it a bit better. Much appreciated.
function roll(min, max, floatFlag) {
let r = Math.random() * (max - min) + min;
return floatFlag ? r : Math.floor(r);
}
let testPurses = Array(5)
.fill(0)
.map((a) => {
return {
quarters: roll(0, 15),
dimes: roll(0, 30),
nickels: roll(0, 40),
pennies: roll(0, 50),
price: Number(roll(0, 10, 1).toFixed(2))
};
});
/*
Write a function enoughChange
Given an object representing a coin purse, and a price
it should return true/false depending on whether
or not you have enough change to complete a
purchase at the given price
The function should also update the "counters"
such that they reflect the quantities in
the test case
You should then use this function to update the
purchaseConfirmation div to display whether
or not you can afford the purchase with the
coin quantities provided
Finally, create nextCase and previousCase
buttons to cycle through the test cases
Refresh the mini-browser or save this file to
load new test cases!
*/
const purchaseConfirmation = document.getElementById("purchase-confirmation");
const quarterCounter = document.getElementById("quarter-count");
const dimeCounter = document.getElementById("dime-count");
const nickelCounter = document.getElementById("nickel-count");
const pennyCounter = document.getElementById("penny-count");
const nextBtn = document.getElementById("next-case");
const prevBtn = document.getElementById("previous-case");
const reload = document.getElementById("reloadBTN");
const purchaseConfirm = document.getElementById("purchase-confirmation");
const plane = document.querySelector(".plane");
let index = 0;
const handleChanges = () => {
let { quarters, dimes, nickels, pennies } = testPurses[index];
const coinCount = Object.values(testPurses[index]);
let Moneytotal = (
coinCount[0] * 1 +
coinCount[1] * 5 +
coinCount[2] * 10 +
coinCount[3] * 20
).toFixed(2);
let itemPrice = (testPurses[index].price * 100).toFixed(2);
let leftover = (Moneytotal - itemPrice).toFixed(2);
quarterCounter.innerHTML = quarters;
dimeCounter.innerHTML = dimes;
nickelCounter.innerHTML = nickels;
pennyCounter.innerHTML = pennies;
let enough = `Yeeesssss... you did it.You have saved £${Moneytotal} and can afford a post lock-down holiday worth £${itemPrice} with £${leftover} left over, for going crazy with `;
let notEnough = `Sorry you can't afford a holiday any time soon.. keep your chin up and keep saving`;
if (Moneytotal >= itemPrice) {
purchaseConfirm.innerHTML = enough;
plane.classList.add("animation");
} else {
purchaseConfirm.innerHTML = notEnough;
plane.classList.remove("animation");
}
};
nextBtn.addEventListener("click", () => {
if (index >= 0 && index < testPurses.length - 1) {
index++;
} else {
index = 0;
}
handleChanges();
});
reload.addEventListener("click", () => {
history.go(0);
});
prevBtn.addEventListener("click", (event) => {
if (index >= 1) {
index--;
} else {
index = testPurses.length - 1;
}
handleChanges();
});
handleChanges();
CSS below:
.animation{
animation-name: slidein;
animation-duration: 4s;
animation-direction: reverse;
/* animation-play-state: paused; */
}
#keyframes slidein {
from {
margin-left: 100%;
}
to {
margin-bottom: 0%;
}
}
HTML
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="container">
<div id="coins">
<div class="coin quarter">£1</div>
<div class="coin dime">£5</div>
<div class="coin nickel">£10</div>
<div class="coin penny">£20</div>
</div>
<div id="coin-counts">
<div id="quarter-count"></div>
<div id="dime-count"></div>
<div id="nickel-count"></div>
<div id="penny-count"></div>
</div>
<div id="purchase-confirmation"></div>
<div id="fly"><img class="plane" src="https://epixieme.github.io/images-repo/planesmall.png" alt="" /></div>
<div id="case-switcher">
<button id="previous-case">Previous</button>
<button id="reloadBTN">Reload Sequence</button>
<button id="next-case">Next</button>
</div>
</div>
<!-- PNGs by Vecteezy -->
<script src="index.pack.js"></script>
</body>
</html>
It would be good to see your CSS
But my initial thought is that you need to remove the 'animation' class before you add it to get the animation to play again. The class is already added on a 'true' case so you just add it again. As the animation has already played it won't play it again. This is why when the conditions aren't the same, it works as you are adding and removing the class as necessary
plane.classList.remove("animation");
Full example of the if condition:
plane.classList.remove("animation");
if (Moneytotal >= itemPrice) {
purchaseConfirm.innerHTML = enough;
plane.classList.add("animation");
} else {
purchaseConfirm.innerHTML = notEnough;
}
The remove and add of the class is happening to quickly so try wrapping your callback in a timeout as follows
nextBtn.addEventListener("click", () => {
if (index >= 0 && index < testPurses.length - 1) {
index++;
} else {
index = 0;
}
plane.classList.remove("animation");
window.setTimeout(()=>{handleChanges();}, 500)
//handleChanges();
});
Alternatively, you could actually just add an eventlistener for the animationend event and remove the class there:
e.g
plane.addEventListener('animationend', () => {
plane.classList.remove('animation')
})
i am trying to close let´s say Dropdown A automatically, when Dropdown B gets classList.toggle("active) (in this case i toggle the ClassList with a Click)
I can open (classList.toggle("active)) and close (classList.toggle("inactive)) it manually, but i want to close it automatically.
Right now i got this:
function dropdown() {
let employerBranding = document.querySelector(".employer-branding");
let marketing = document.querySelector(".marketing");
let corporateOverall = document.querySelector(".corporate-overall");
let technicalData = document.querySelector(".technical-data");
let categoryModules = [employerBranding, marketing, corporateOverall, technicalData];
let categoryDropdown = $(".category-dropdown");
for (let i = 0; i < categoryModules.length; i++) {
categoryModules[i].addEventListener("click", function () {
categoryDropdown.slideDown();
});
}
}
dropdown();
The Problem is now: when i click on one of the 4 Modules of course it opens all of the Dropdowns.
How can i trigger the correct Dropdown to the correct Module, so only one (the one below the clicked Module) opens up
&&
How can i add with another click a .slideUp() to slide it up again?
Here is a very basic example of what you want to achieve:
const one = document.querySelector('#one');
const two = document.querySelector('#two');
const toggle = (e) => {
if (e.target.id === 'one') {
one.classList.toggle('active');
two.classList.remove('active');
} else {
two.classList.toggle('active');
one.classList.remove('active');
}
}
one.addEventListener('click', (e) => toggle(e));
two.addEventListener('click', (e) => toggle(e));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
div {
display: inline;
margin: 20px;
padding: 100px;
background-color: #444;
}
.active {
padding: 200px 100px;
}
</style>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
</body>
</html>
Generally (and especially if creating more dropdowns), I would suggest a more sophisticated approach involving looping through all of them, such as Rounin mentioned.
Whenever a dropdown is activated with a click:
Close all the dropdowns (ie. loop through the dropdowns and set each to .inactive)
Open the activated dropdown
After a little while a came up with this solution
function closeDropdown() {
// let employerBrandingDropdown = document.querySelector(".employer-branding-dropdown");
let employerBrandingDropdown = $('.employer-branding-dropdown');
let marketingDropdown = $(".marketing-dropdown");
let corporateOverallDropdown = $(".corporate-overall-dropdown");
let technicalDataDropdown = $(".technical-data-dropdown");
let dropdownArray = [employerBrandingDropdown, marketingDropdown, corporateOverallDropdown, technicalDataDropdown];
window.addEventListener('mouseup', function (event) {
for (let i = 0; i < dropdownArray.length; i++) {
let categoryDropdown = dropdownArray[i];
if ($(event.target !== categoryDropdown) && $(event.target).parent() !== categoryDropdown) {
$(categoryDropdown).stop().slideUp();
}
}
})
}
I'm making a webpage and I want to make "type" effect on form. After user waits for a while, it starts typing some text as an example, if possible - with cursor. I don't really know where to start though. I'm using jQuery.
Thanks in advance!
Animate the Placeholder
You might use the placeholder attribute to display example input. Static text is usually enough for most users. Yet, you could add an animation loop to simulate typing. Using the placeholder also allows you to display text without altering the form input value.
The example below uses a loop to simulate typing and stops with the user enters information. No jQuery required.
Run the snippet to demo
var timerId, placeholder = fullname.placeholder, n =0;
id = setInterval(function() {
if (fullname.value) {
// stop as user has typed something
clearInterval(id);
fullname.placeholder = placeholder;
}
else {
// show next character
fullname.placeholder = placeholder.substr(0,n);
n = (n+1) % (placeholder.length+1);
}
}, 400);
input {font-family: 'Special Elite', cursive; font-size:36px; border:1px solid steelblue;color:black; font-weight:bold;}
<link href='https://fonts.googleapis.com/css?family=Special+Elite' rel='stylesheet' type='text/css'>
<input id="fullname" placeholder="Berlin, Germany">
You can register a timeout function at form load using settimeout function.
If user presses a key you can cancel it.
The timeout function callback could set the placeholder of your input using jQuery.
Consider the inserted snippet to have an idea on how to start a proper implementation.
(function() {
"use strict";
var exampleText = "my example text";
var inactivityDelay = 2000;
var typeDelay = 200;
var interval;
var appendExample = function() {
var index = 0;
interval = setInterval(function() {
if (index >= exampleText.length) {
clearInterval(interval);
return;
}
var myinput = $("#myinput");
myinput.attr("placeholder", myinput.attr("placeholder") + exampleText.charAt(index++));
}, typeDelay);
};
var timeout = setTimeout(appendExample, inactivityDelay);
$("#myinput").on("change paste keyup focus", function() {
clearTimeout(timeout);
clearInterval(interval);
$("#myinput").attr("placeholder", "");
});
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="myinput" maxlength="100" placeholder="" />
</form>