How to make an element NOT to steal focus from an input? - javascript

I have a simple input and an SVG-pic that sends the input-text to a server and instantly adds the text into a document.createElement('div')...etc
Is there a way to make my SVG-pic non-focusable so it doesn't steal focus from others (in my case - my input)
upd.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="wrapper">
<div>1</div>
<div>2</div>
<div>3</div>
<div>
<input id="senderInput" type="text">
<img src="../../img/Calendar.svg" alt="" onclick="imgClick(event)">
</div>
</div>
</body>
</html>
.wrapper {
max-width: 300px;
margin: 0 auto;
}
.wrapper > div {
width: 250px;
height: 150px;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
background-color: var(--divBG);
margin: 20px;
}
arr = ['#f00', '#aaa004', '#b70808', '#0855b7', '#681a73', '#d56e00']
document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll('.wrapper > div').forEach(d => {
d.style.backgroundColor = arr[getRandomInt(6)]
})
});
function j(arg) {
return document.querySelector(arg)
}
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function imgClick(e) {
j('.wrapper > div').innerText = j('#senderInput').value
setTimeout(() => {
var dd = document.createElement('div')
dd.style.backgroundColor = arr[getRandomInt(6)]
dd.innerText = '234'
j('.wrapper').appendChild(dd)
}, 100);
j('#senderInput').focus()
}

Actually, the simple
event.preventDefault()
msgInput.focus()
worked fine, the problem solved

Related

js function stops acting

![Text](https://stackoverfl
var obj = {
count: 1
}
function elementSet()
{
if(obj.count=1){
document.getElementById("text").textContent = "graa";}
if(obj.count=2){
document.getElementById("text").textContent = "graa";}
if(obj.count=3){
document.getElementById("text").textContent = "graa";}
}
function back()
{
if(obj.count>1)
{
obj.count = obj.count -1;
document.getElementById("back").style.display = "block";
document.getElementById("page_num").textContent = obj.count;
}
}
function forth()
{
if(obj.count<3){
obj.count = obj.count +1;
document.getElementById("page_num").textContent = obj.count;
document.getElementById("forth").style.display = "block";
if (obj.count>3){
document.getElementById("forth").style.display = "none";}
}
}
.colx1 {
color: #e1992e;
/* height: 3px; */
font-size: 2.1ch;
margin-right: 80%;
inline-size: auto;
border-color: #e1992e;
border-radius: 11ch;
}
.colx2 {
color: #e1992e;
font-size: 2.1ch;
inline-size: auto;
margin-top: -3%;
margin-left: 80%;
border-color: #e1992e;
border-radius: 11ch;
}
.colabount
{
width: 170px;
}
.row {
display: inline;
}
.body
{
text-align: center;
max-height: 100%;
}
.button {
border-color: #e1992e;
}
.page_num
{
color: black;
size: 13ch;
text-align: center;
}
.text
{
color: blanchedalmond;
size: 12ch;
}
<!DOCTYPE html>
<html>
<head>
<title>films</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body class="body">
<div class="container external internal" id="content">
<h2 id="text" class="text" type="textContent"> its the f</h2>
<div class="row">
<button class="colx1" id="back" type="button" onclick="back(),elementSet()"><b>back</d></button>
<button class="colx2" id="forth" type="button" onclick="forth(),elementSet()"><b>forth</d></button>
</div>
<div class="page_num"><b id ="page_num">1</b></div>
</div>
</body>
</html>
ow.com/image.jpg)
i tried to create external obj that contain count its working.
the page content will change acording to the count number.
the proble starts when im calling 'elementSet' = {checking abount obj.count and
changing the page acordingly}
THE PROBLEM : when elementSet runs back() and forth() not working anymore!
your mistake is that:
in java script = is assignment. for example: let a = 0;
we assignment 0 to a. now a is 0.
and we have == and ===. these are use for comparison in logics and Condition. for example:
let a = 0;
a == 0 && console.log("yes");
there are some different between == and ===. you can read that in a link!

looking for why list does not display when adding task to the to do

Good day folks,
I am creating a to-do app, and so far when I enter the task in via the input the console shows my object firing but does not display it on the screen. Please look at my code and help me point out the issue, I have been debugging this for some time today.
HTML:
<!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">
<link rel="stylesheet" href="css/to-doStylesheet.css">
<title>To-Do App</title>
</head>
<body>
<div class=container>
<div class= base>
<div class = screen>
<img src="images/WarGreymon_Render.png" alt="Wargreymon">
<div id ="speach-bubble"> What is on your
agenda for today?
</div>
<div class = "dateTime">
</div>
</div>
<div class = "nameInput" id = "inputContainer">
<form class ="form">
<input type="text" class ="userInput" placeholder="Add Agenda and press enter">
<input type="submit" value ="Add">
</form>
</div>
</div>
<ul class="list"></ul>
<script src="js/add-task.js"></script>
</body>
</html>
CSS
.form
{
margin-left: 400px;
}
.userInput
{
width: 394px;
height: 30px;
background-color: #B62626;
font-family: Digimon Basic;
color: #33D61A;
margin-left: -359px;
}
.userInput ::placeholder
{
color: #33D61A;
font-family: Digimon Basic;
}
.list:empty
{
display: none;
}
.list
{
list-style: none;
margin-bottom: 20px;
}
.input[type="checkbox"] {
display: none;
}
.tick {
width: 30px;
height: 30px;
border: 3px solid #333;
border-radius: 50%;
display: inline-flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.todo-item {
margin-bottom: 10px;
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
}
.todo-item span {
flex-grow: 1;
margin-left: 10px;
margin-right: 10px;
font-size: 22px;
}
JS
let tasks = [];
const currentdt = new Date()
function todo(text) {
const todo = {
text,
checked: false,
id: Date.now(),
timestamp: currentdt
};
tasks.push(todo);
console.log(tasks);
}
// Select the form element
const form = document.querySelector('.form');
// Add a submit event listener
form.addEventListener('submit', event => {
// prevent page refresh on form submission
event.preventDefault();
// select the text input
const input = document.querySelector('.userInput');
// Get the value of the input and remove whitespace
const text = input.value.trim();
if (text !== '') {
todo(text);
input.value = '';
input.focus();
}
});
//This function is to display new to do on the screen
function displaytasks(todo)
{
const list = document.querySelector('list');
const isChecked = todo.checked ? 'done': '';
const addedList = document.createElement("li");
addedList.setAttribute('class', `todo-item ${isChecked}`);
addedList.setAttribute('data-key', todo.timestamp);
addedList.innerHTML = `<input id="${todo.timestamp}" type="checkbox"/>
<label for="${todo.timestamp}" class="tick js-tick"></label>
<span>${todo.text}</span>
<button class="delete-todo js-delete-todo">
<img class = "delete" src="images/delete.png" alt="delete icon">
</button>`;
list.append(addedList);
}
So I am busy with the js file at the moment, I think it has to do something with the innerHTML, but I am not sure what exactly is wrong there, because when I look in the console on the HTML side I do not see the <ul class="list"></ul> firing at all to bring the new HTML elements.
Your help will be much appreciated
It looks like the code to display the todos is not being called, so I would recommend you add in a function call after reading in a new todo.
...
const text = input.value.trim();
if (text !== '') {
todo(text);
input.value = '';
input.focus();
displaytasks(tasks); // Show tasks after submission
}
});
//This function is to display new to do on the screen
function displaytasks(todo)
{
const list = document.querySelector('.list');
...

Is there a better way to assign ID's for a large number of elements and buttons in HTML and JavaScript?

$(document).ready(function() {
var persist = false;
var persist1=false;
$(".hover_btn").click(function(e) {
e.stopPropagation();
persist = !persist;
})
$(".hover_btn").mouseenter(function(e) {
e.preventDefault();
$("#tab1default").removeClass("collapse").addClass("fade").addClass("in").addClass("active");
});
$(".hover_btn").mouseleave(function(e) {
e.preventDefault();
if (!persist)
{
$("#tab1default").addClass("collapse").removeClass("fade").removeClass("in").removeClass("active");
}
});
$(".hover_btn1").click(function(e) {
e.stopPropagation();
persist1 = !persist1;
})
$(".hover_btn1").mouseenter(function(e) {
e.preventDefault();
$("#tab2default").removeClass("collapse").addClass("fade").addClass("in").addClass("active");
});
$(".hover_btn1").mouseleave(function(e) {
e.preventDefault();
if (!persist1)
{
$("#tab2default").addClass("collapse").removeClass("fade").removeClass("in").removeClass("active");
}
});
});
#customTab a {
padding: 0;
}
.flex {
display: flex;
justify-content: space-between;
align-items: baseline;
flex-wrap: wrap;
}
#media (max-width: 576px) {
.container {
padding: 0;
}
.btn {
padding: 3px 6px;
font-size: 12px;
}
.flex .panel-default {
margin-right: 4px;
}
.flex .panel-default>.panel-heading {
padding: 0;
}
.flex .panel-default>.panel-body .btn:last-child {
margin-top: 4px;
}
}
.btn-dark {
background-color: #343a40;
color: #fff;
}
.btn-dark:hover,
.btn.focus,
.btn:focus {
color: #fff;
}
.btn.focus,
.btn:focus,
.btn:active,
.btn:hover,
.active>a .btn {
color: #fff;
background: blue;
}
.nav-tabs {
border: none;
}
.hover_btn {
background-image: url(air.jfif);
background-size: cover;
color: #000;
height: 200px;
width: 200px;
display: flex;
justify-content: center;
align-items: center;
}
.hover_btn:hover {
background-image: url(air.jfif);
background-size: cover;
color: #000;
height: 200px;
width: 200px;
display: flex;
justify-content: center;
align-items: center;
opacity: 0.9;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<main>
<div class="container" id="customTab">
<ul class="nav " style="display: flex; justify-content: space-around; border: none;">
<li><span class="hover_btn">Water</span>
</li>
<li><span class="hover_btn1">soil</span></li>
</ul>
</div>
<div class="tab-content">
<div class="hover_btn2">
<div class="tab-pane fade" id="tab1default">
<div class="flex ">
<ul class="nav nav-tabs">
<li data-toggle="tab"><span class="btn btn-info">1</span></li>
</ul>
</div>
</div>
</div>
</div>
<div class="tab-pane fade hover_btn3" id="tab2default">
<div class="flex">
<div class="panel with-nav-tabs panel-default">
<div class="panel-heading">
<ul class="nav nav-tabs">
<li><span class="btn btn-info">6</span></li>
</ul>
</div>
</div>
</div>
</div>
</main>
</body>
</html>
I have multiple buttons and hovering functionality on those buttons and I have manually assigned ID's for both like "hover_btn", "hover_btn1" and the list goes on. Similarly for the button, the id is assigned like "tabl1default","tab2default" and so on. How can I implement it with a loop or some random generator so that I don't have to manually increment numbers all the time in both my html and JS code. Here is my code:
https://jsfiddle.net/ptaej51d/
EDIT: I've posted my answer before you have updated your code, so it doesn't really refer to the code you have currently.
I don't think there is any way to loop in HTML, but you can always loop and create HTML elements from JavaScript.
You could create a template function that would create all your HTML elements to which you would pass your hover_btn<n> and tab<n>default attribute values from a for loop. Another function would set all event listeners. Since the HTML elements are created using JavaScript, all their data would also have to be stored in JavaScript (e.g. their innerHTML).
HTML:
<ul
id="navigation"
class="nav"
style="display: flex; justify-content: space-around; border: none;">
</ul>
JavaScript:
$(document).ready(() => {
const
// How many elements will be created
count = 5,
// Attribute value placeholders, where `~` is the placeholder for a number
elements = [
'hover_btn~',
'tab~default',
'persist~'
],
// HTML for span elements in the order they appear in the DOM
html = [
'Wasser',
'Sedimente',
'Biologische<br>Proben</br>',
'Luft',
'Lebensmittel'
];
// Functions
const
addHtmlElement = i => {
// Create all elements
var
li = document.createElement('LI'),
a = document.createElement('A'),
span = document.createElement('SPAN');
// Create an HTML structure
document.getElementById('navigation').appendChild(li);
li.appendChild(a);
a.appendChild(span);
// Add all attributes
a.setAttribute('href',`#${elements[1].replace(/\~/g,i + 1)}`);
a.setAttribute('data-toggle','tab');
// Replace value for `hover_btn~` number
var hoverNum = (i > 0) ? i : '';
span.setAttribute('class',elements[0].replace(/\~/g,hoverNum));
// Set innerHTML for span
span.innerHTML = html[i];
// Add event listeners
addEventListeners(hoverNum);
},
addEventListeners = hoverNum => {
$(`.${elements[1]}${hoverNum}`).click(e => {
e.stopPropagation();
eval(`persist${hoverNum} = !persist${hoverNum}`);
});
$(`.${elements[1]}${hoverNum}`).mouseenter(e => {
e.preventDefault();
$(`#tab${hoverNum ? 2 : 1}default`).removeClass('collapse').addClass('fade').addClass('in').addClass('active');
});
$(`.${elements[1]}${hoverNum}`).mouseleave(e => {
e.preventDefault();
if (!persist) {
$(`#tab${hoverNum ? 2 : 1}default`).addClass('collapse').removeClass('fade').removeClass('in').removeClass('active');
}
});
};
// Add event listeners once
$('#create_btn').on('click',() => {
$('#create_tab').tab('show');
});
$('#create_btn').on('click',() => {
$('#create1_tab').tab('show');
});
$('#login_btn').on('click',() => {
$('#login_tab').tab('show');
});
// For loop
for (var i = 0; i < count; i++) addHtmlElement(i);
});
Creating HTML DOM elements using JavaScript:
https://www.w3schools.com/jsref/met_document_createelement.asp
Setting attributes using JavaScript:
https://www.w3schools.com/jsref/met_element_setattribute.asp
This answer is based on your original code:
Original HTML:
<ul class="nav " style="display: flex; justify-content: space-around; border: none;">
<li><span class="hover_btn" >Wasser</span>
</li>
<li><a href="#tab2default" data-toggle="tab"><span
class="hover_btn1">Sedimente</span></a></li>
<li><a href="#tab3default" data-toggle="tab"><span
class="hover_btn2">Biologische<br>Proben</br>
</span></a>
</li>
<li><span class="hover_btn3">Luft</span>
</li>
<li><span class="hover_btn4">Lebensmittel</span>
</li>
Original JavaScript:
$( document ).ready(function() {
var persist = false;
var persist1=false;
var persist2=false;
var persist3=false;
var persist4=false;
$('#create_btn').on('click', function(){
$('#create_tab').tab('show')
})
$('#login_btn').on('click', function(){
$('#login_tab').tab('show')
})
$('#create_btn').on('click', function(){
$('#create1_tab').tab('show')
})
$(".hover_btn").click(function(e) {
e.stopPropagation();
persist = !persist;
})
$(".hover_btn").mouseenter(function(e) {
e.preventDefault();
$("#tab1default").removeClass("collapse").addClass("fade").addClass("in").addClass("active");
});
$(".hover_btn").mouseleave(function(e) {
e.preventDefault();
if (!persist)
{
$("#tab1default").addClass("collapse").removeClass("fade").removeClass("in").removeClass("active");
}
});
$(".hover_btn1").click(function(e) {
e.stopPropagation();
persist1 = !persist1;
})
$(".hover_btn1").mouseenter(function(e) {
e.preventDefault();
$("#tab2default").removeClass("collapse").addClass("fade").addClass("in").addClass("active");
});
$(".hover_btn1").mouseleave(function(e) {
e.preventDefault();
if (!persist1)
{
$("#tab2default").addClass("collapse").removeClass("fade").removeClass("in").removeClass("active");
}
});
$(".hover_btn2").click(function(e) {
e.stopPropagation();
persist2 = !persist2;
})
$(".hover_btn2").mouseenter(function(e) {
e.preventDefault();
$("#tab2default").removeClass("collapse").addClass("fade").addClass("in").addClass("active");
});
$(".hover_btn2").mouseleave(function(e) {
e.preventDefault();
if (!persist2)
{
$("#tab2default").addClass("collapse").removeClass("fade").removeClass("in").removeClass("active");
}
});
$(".hover_btn3").click(function(e) {
e.stopPropagation();
persist3 = !persist3;
})
$(".hover_btn3").mouseenter(function(e) {
e.preventDefault();
$("#tab2default").removeClass("collapse").addClass("fade").addClass("in").addClass("active");
});
$(".hover_btn3").mouseleave(function(e) {
e.preventDefault();
if (!persist3)
{
$("#tab2default").addClass("collapse").removeClass("fade").removeClass("in").removeClass("active");
}
});
$(".hover_btn4").click(function(e) {
e.stopPropagation();
persist4 = !persist4;
})
$(".hover_btn4").mouseenter(function(e) {
e.preventDefault();
$("#tab2default").removeClass("collapse").addClass("fade").addClass("in").addClass("active");
});
$(".hover_btn4").mouseleave(function(e) {
e.preventDefault();
if (!persist4)
{
$("#tab2default").addClass("collapse").removeClass("fade").removeClass("in").removeClass("active");
}
});
});
Note to your original code:In programming, if you are copy/pasting, you are probably doing it wrong.

addEventListenner on js : the bubble does not want to be canceled

I coded a game for 2 people:
Initialization is done with player1 ()
with the displayScore () function I can reiterate the score as much as I want (here everything is fine)
but when I switch to the other player with the changePlayer (player) function, the event goes well with player2 I can also reiterate but the concern is that the first player continues to play while my functions and variables are well partitioned
the problem comes from the event of the first which continues despite my stopPropagation () which I did not forget to report.
Where's the problem I've been on for a day and a half.
I join the two files html and js and also css
Thank you in advance,
cordially.
jeu de dés
<body>
<div id="launchGame">
<h1>NEW GAME</h1>
</div>
<div id="players">
<div id="player_1"><h2>PLAYER 1</h2><span id="score_player_1">Score :</span></div>
<picture><img id="dice">img</picture>
<div id="player_2"><h2>PLAYER 2</h2><span id="score_player_2">Score :</span></div>
</div>
<div id="current_score">
<div id="current_score_1"><p>current<span id="round_player_1"></span></p></div>
<div id="controls_game">
<h3 id="roll_dice"><img src="images/re_game.png">ROLL DICE</h3>
<h3 id="hold"><img src="images/charge_score.png">HOLD</h3>
</div>
<div id="current_score_2"><p>current<span id="round_player_2"></span></p></div>
</div>
</body>
(function(){
window.addEventListener("DOMContentLoaded", function() {
const launch = document.getElementById("launchGame");
const rollDice = document.getElementById("roll_dice");
function currentPlayer(player) {
const hold = document.getElementById("hold");
if (player.getElementsByTagName("img").length < 1) {
player.firstChild.style.position = "relative";
var currentPlayer = new Image();
currentPlayer.src = "images/current_player.png";
currentPlayer.setAttribute("class", player.getAttribute("id"));
currentPlayer.style.position = "absolute";
player.firstChild.appendChild(currentPlayer);
} else {
player.getElementsByTagName("img")[0].style.visibility = "visible";
}
changePlayer(player);
rollDice.addEventListener("click", function(e) {
e.stopPropagation();
displayScore(player);
}, {capture:false, once: false, useCapture: true});
}
function player1() {
let player1 = document.getElementById("player_1");
currentPlayer(player1);
}
function player2() {
let player2 = document.getElementById("player_2");
currentPlayer(player2);
}
function changePlayer(player) {
hold.addEventListener("click", function(e) {
e.stopPropagation();
player.getElementsByTagName("img")[0].style.visibility = "hidden";
if (player.getAttribute("id") === "player_1") {
console.log(player.getAttribute("id"));
player2();
} else if (player.getAttribute("id") === "player_2") {
console.log(player.getAttribute("id"));
player1();
}
}, {capture:false, once:true, useCapture: true});
}
function displayScore(player) {
let scoreDice = getScoreDice();
let scorePlayer = document.getElementById("round_" +
player.getAttribute("id"));
scorePlayer.textContent = scoreDice();
}
function getScoreDice() {
var result = 0;
var faceDice = Math.floor(Math.random()*7);
if ((faceDice > 0) && (faceDice < 7)) {
result = faceDice;
} else {
result = faceDice+1;
}
function innerGetScoreDice() {
return result;
}
return innerGetScoreDice;
}
launch.addEventListener("click", player1(), {capture:false, once:true});
});
})()
body {
margin: 0;
padding: 0;
background-color: silver;
background: linear-gradient(to left, white, white 50%, rgb(228, 227, 227) 50%, rgb(228, 227, 227));
text-align: center;
color: gray;
}
h1 {
width: 40%;
margin: 1% auto 5%;
font-size: 1.5rem;
}
h1::before {
content: "⊕ ";
font-size: 2rem;
align-items: center;
color: tomato;
}
h2 {
height: 30px;
line-height: 30px;
}
h3 {
margin: 7% 0;
}
span {
display: block;
margin-top: 50%;
}
img {
max-width: 10%;
vertical-align: middle;
margin-right: 3%;
}
#players, #final_score, #current_score, #current_score_1, #current_score_2, #controls_game {
display: flex;
}
#players, #final_score, #current_score {
flex-direction: row;
justify-content:space-evenly;
align-items: center;
}
#players {
justify-content:space-around;
margin: 1% 1% 10%;
}
#current_score_1, #current_score_2 {
border-radius: 20%;
padding: 2% 4%;
background-color: tomato;
color: white;
}
#controls_game {
flex-direction: column;
max-width: 33%;
}
In function changePlayer(player), isn't variable 'hold' undefined ?
No
The variable hold is defined and ok
All variables are ok
Problems is in event of first players
Bubble or capture
I don't now whats this

some javascript functions isn't working in cordova android app

I'm new to Cordova, and I'm trying to build an android app
I copied my files into www file and replaced its files with mine
and build apk but when running it on my phone the first two buttons only are working (Equal weight / Unequal weight) while the (add more/ reset/ result buttons ) are not, but when I'm trying to check my code as a web page it works perfectly, as you might see in the snippet
I also tried to keep the cordova.js file and the index.js with my app.js but it didn't work
I tried to add cordova.js and index.js (the files that created automatically when creating a project with Cordova) but it didn't work
//declare the main buttons and divs
const btn1 = document.querySelector('.eqbtn'),
btn2 = document.querySelector('.uneqbtn'),
div1 = document.querySelector('.eqdiv'),
div2 = document.querySelector('.wrap-sub')
div_2 = document.querySelector('.uneqdiv');
//add event listeners to the main buttons
btn1.addEventListener('click', equalFunc);
btn2.addEventListener('click', unequalFunc);
//switch between two keys
function equalFunc() {
togFunc(div1, div_2, btn1, btn2);
resetFunc('.eqdiv', div1);
}
function unequalFunc() {
togFunc(div_2, div1, btn2, btn1);
resetFunc('.wrap-sub', div2);
}
function togFunc(one, two, a, b) {
a.classList.add('active');
b.classList.remove('active');
one.style.display = 'block';
two.style.display = 'none';
}
//declare the equal addmore button
const btnplus = document.querySelector('.eqmore');
const unbtnplus = document.querySelector('.un-eqmore');
//fire when addmore button get fired
btnplus.addEventListener('click', () => {
if (checkIn('.eqdiv') === false) {
errIn();
} else {
creatIn(div1);
}
});
//fire when uneqaddmore get clicked
unbtnplus.addEventListener('click', () => {
if (checkIn('.wrap-sub') === false) {
errIn();
} else {
creatIn(div2);
}
})
//check the value of the inputs
function checkIn(nav) {
let bool;
document.querySelectorAll(`${nav} input`).forEach((elem) => {
if (elem.value === '' || elem.value < 0) {
elem.style.borderColor = '#f86868';
bool = false;
} else {
elem.style.borderColor = '#D1D1D1';
}
});
return bool;
}
//create the input and assign it's value
function creatIn(dnav) {
if (dnav === div1) {
const dive = document.createElement('div');
dive.innerHTML = `<input type ='number'/>`;
dnav.insertBefore(dive, btnplus);
} else {
const sp1 = document.createElement('div'),
sp2 = document.createElement('div');
sp1.innerHTML = `<input type ='number'>`;
sp2.innerHTML = `<input type ='number'>`;
document.querySelector('.div2-1').appendChild(sp2);
document.querySelector('.div2-2').appendChild(sp1);
}
}
//fire an error if the user insert wrong value
function errIn() {
const errdiv = document.createElement('div');
errdiv.innerHTML = `Please fill inputs with positive values`;
errdiv.classList.add('errdiv');
document.querySelector('.wrap').insertAdjacentElement('beforeend', errdiv);
setTimeout(() => errdiv.remove(), 1800);
}
//fire when the reset button get clicked
function resetFunc(x, y) {
document.querySelectorAll(`${x} input`).forEach(reset => {
reset.remove();
});
document.querySelector('#output').innerHTML = '';
creatIn(y);
}
//reset all the inputs
document.querySelector('.reset').addEventListener('click', () => resetFunc('.eqdiv', div1));
document.querySelector('.un-reset').addEventListener('click', () => resetFunc('.wrap-sub', div2));
//fire when result button get fired
document.querySelector('.result').addEventListener('click', resFunc);
document.querySelector('.un-result').addEventListener('click', unresFunc);
//declare result function when result button get clicked
function resFunc() {
if (checkIn('.eqdiv') === false) {
errIn();
} else {
let arr = [];
document.querySelectorAll('.eqdiv input').forEach(res => arr.push(Number(res.value)));
const num = arr.length;
const newarr = arr.reduce((a, b) => a + b);
const mean = newarr / num;
const resarr = [];
arr.forEach(re => resarr.push((re - mean) * (re - mean)));
const newresarr = resarr.reduce((c, v) => c + v);
const norDev = Math.sqrt(newresarr / (num - 1));
const dev = norDev / Math.sqrt(num);
let mpv;
if (!isNaN(dev)) {
mpv = `${mean.toFixed(3)} ± ${dev.toFixed(3)}`;
} else {
mpv = `${mean.toFixed(3)}`;
}
displayResult(mpv);
}
}
function unresFunc() {
if (checkIn('.wrap-sub') === false) {
errIn();
} else {
let allweight = [],
allValues = [],
subMeanArray = [],
sub = [],
semiFinal = [];
document.querySelectorAll('.div2-2 input').forEach(w => allweight.push(Number(w.value)));
const sumWeight = allweight.reduce((n, m) => n + m);
document.querySelectorAll('.div2-1 input').forEach(s => allValues.push(Number(s.value)));
for (i = 0; i < allweight.length; i++) {
subMeanArray.push(allweight[i] * allValues[i]);
}
const sumMean = subMeanArray.reduce((a, b) => a + b);
const mean = sumMean / sumWeight;
allValues.forEach(s => sub.push(s - mean));
for (i = 0; i < allweight.length; i++) {
semiFinal.push(allweight[i] * sub[i] * sub[i]);
}
const alFinal = semiFinal.reduce((a, b) => a + b);
const nDev = Math.sqrt(alFinal / allweight.length);
const Dev = nDev / Math.sqrt(sumWeight);
let mpv;
if (isNaN(Dev)) {
mpv = ` : No choice but the only value you gave which is ${allValues[0].toFixed(3)}`;
} else {
mpv = `${mean.toFixed(3)} ± ${Dev.toFixed(3)}`;
}
displayResult(mpv);
}
}
function displayResult(wow) {
document.querySelector('#output').innerHTML = `The Result is ${wow}`;
}
.wrap>div {
display: none;
}
/* .uneqdiv{
display: none;
} */
.container {
padding-top: 100px;
width: max-content;
padding-bottom: 50px;
}
.wrap {
margin-top: 50px;
}
.wrap-sub {
display: flex;
}
.div2-1 {
margin-right: 5px;
}
button {
outline: none;
transition: border .3s;
}
.active,
.active:focus {
border-color: #46d84d;
}
button.reset:hover,
button.un-reset:hover {
border-color: #f86868;
}
button.eqmore:hover,
button.un-eqmore:hover {
border-color: #46d84d;
}
.errdiv {
height: 40px;
width: 100%;
background-color: #df4f4f;
color: #ffffff;
display: flex !important;
justify-content: center;
align-items: center;
}
#output {
padding-top: 20px;
}
h6 {
margin: 0;
}
.tes {
display: inline-block;
}
#media(max-width: 700px) {
.container {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.container>h2 {
font-size: 2rem;
}
button {
width: 75%;
max-width: 20rem;
}
.wrap {
display: flex;
flex-direction: column;
align-items: center;
width: 90%;
}
.eqdiv {
text-align: center;
}
.eqdiv input {
max-width: 20rem;
width: 75%;
}
.eqdiv button {
display: block;
margin-left: auto;
margin-right: auto;
}
.uneqdiv {
text-align: center;
width: 100%;
}
.wrap-sub input {
max-width: 25rem;
width: 100%;
}
.uneqdiv .wrap-sub {
width: 100%;
margin-top: 40px;
margin-bottom: 15px;
display: flex;
flex-direction: column;
align-items: center;
}
.wrap-sub h6 {
font-size: 1.4rem;
}
.tes button {
width: 100%;
}
}
<html>
<head>
<meta content="utf-8">
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/skeleton.css">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>survey</title>
</head>
<body>
<div class="container">
<h2 class="jui">Please select the wanted method</h2>
<button class="eqbtn">equal weight</button>
<button class="uneqbtn">unequal weight</button>
<div class="wrap">
<div class="eqdiv">
<h4>Enter the equal values</h4>
<div>
<input type="number" class="init">
</div>
<button class="eqmore">add more +</button>
<button class="reset">reset</button>
<button class="result button-primary">result</button>
</div>
<div class="uneqdiv">
<h4>Enter the unequal values</h4>
<div class="wrap-sub">
<div class="div2-1">
<h6>The Measurements</h6>
<input type="number" class="un-init">
</div>
<div class="div2-2">
<h6>The Weights</h6>
<input type="number" class="un-weight">
</div>
</div>
<div class="tes">
<button class="un-eqmore">add more +</button>
<button class="un-reset">reset</button>
<button class="un-result button-primary">result</button>
</div>
</div>
</div>
<div id="output"></div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>

Categories

Resources