Dropdown menu with result js - javascript

I am writing a search menu that searches for and shows on the page all matching substrings in a string on pure js. I made the search on page, but I don't know how to display the results in the search drop-down menu with the number of results like on picture use only js. My code and picture below:
const input = document.querySelector('input')
const paragraphs = document.querySelectorAll('p')
input.addEventListener('input', e => {
const searchTerm = e.target.value
const regex = new RegExp(searchTerm, 'g')
const replacement = `<span class="highlighted">${ searchTerm }</span>`
for (const p of paragraphs) {
p.innerHTML = p.innerText.replace(regex, replacement)
}
})
:root {
--primary-color: crimson;
--dark-color: #013;
--light-color: whitesmoke;
}
body {
color: var(--dark-color);
background-color: var(--light-color);
padding: 1rem;
}
header {
text-align: center;
}
main {
max-width: 567px;
margin: 0 auto;
}
.search__container {
text-align: center;
padding: 1rem;
margin: 0 auto;
}
.search__input {
border: 2px solid var(--dark-color);
padding: 1rem;
text-align: center;
}
.search__input:hover,
.search__input:focus {
outline: none;
border-color: var(--primary-color);
-webkit-box-shadow: 0 0 5px 0.1px var(--primary-color);
box-shadow: 0 0 5px 0.1px var(--primary-color);
}
.highlighted {
text-shadow: 0 0 6px var(--primary-color);
color: var(--primary-color);
}
<section class="search__container">
<input class="search__input" type="text" spellcheck="false" placeholder="search..." />
</section>
<section>
<div class="paragraphs">
<div id="p"><p>Buffalofish sawtooth </p>
<p>eel tigerperch, john dory sleeper,</p>
<p>Spanish mackerel </p>
<p>sockeye salmon sturgeon </p>
<p>gray mullet bottlenose. </p>
<p>Banjo catfish wallago; deep </p>
<p>sea smelt titan triggerfish </p>
<p>Australian grayling threadfin </p>
<p>bighead carp longnose lancetfish </p>
<p>pineconefish. Pipefish mojarra </p>
<p>northern pearleye cutthroat trout </p>
<p>sand diver; freshwater shark wrasse. </p></div>
</div>
</section>

I wrote this code, which allows you to count the number of words in your text that have your search term. AND you get a dynamic list of words that contain your search term. (I touch only HTML and JS files)
Hint: If you want to have the dynamic list more "beautiful" change the <div id="listFound"></div> with list tags, like <ul> and <li> but keep the id="listFound"
const input = document.querySelector('input')
const paragraphs = document.querySelectorAll('p')
input.addEventListener('input', e => {
document.getElementById('listFound').textContent = "" //init after each additional letter
const searchTerm = e.target.value
const regex = new RegExp(searchTerm, 'g')
const replacement = `<span class="highlighted">${ searchTerm }</span>`
for (const p of paragraphs) {
p.innerHTML = p.innerText.replace(regex, replacement)
}
/*ADD*/
string_to_array(document.getElementById('p').textContent)
checkWords(searchTerm)
let text = document.getElementById('p').textContent
let separator = searchTerm
let number = WordCount(text, separator)
document.getElementById('result').textContent = number
if(searchTerm === ""){
document.getElementById('listFound').textContent = ""
document.getElementById('result').textContent = 0
}
})
/*ADD 3 functions*/
var arrayFromWords = []
function string_to_array(str) {
arrayFromWords = str.trim().split(" ");
}
function checkWords(searchTerm){
arrayFromWords.forEach(element => {
if(element.includes(searchTerm)){
document.getElementById('listFound').textContent += element
}
})
}
function WordCount(str, separator) {
return (str.split(separator).length -1);
}
:root {
--primary-color: crimson;
--dark-color: #013;
--light-color: whitesmoke;
}
body {
color: var(--dark-color);
background-color: var(--light-color);
padding: 1rem;
}
header {
text-align: center;
}
main {
max-width: 567px;
margin: 0 auto;
}
.search__container {
text-align: center;
padding: 1rem;
margin: 0 auto;
}
.search__input {
border: 2px solid var(--dark-color);
padding: 1rem;
text-align: center;
}
.search__input:hover,
.search__input:focus {
outline: none;
border-color: var(--primary-color);
-webkit-box-shadow: 0 0 5px 0.1px var(--primary-color);
box-shadow: 0 0 5px 0.1px var(--primary-color);
}
.highlighted {
text-shadow: 0 0 6px var(--primary-color);
color: var(--primary-color);
}
<section class="search__container">
<input class="search__input" type="text" spellcheck="false" placeholder="search..." />
<div id="result"></div> <!--ADD-->
<div id="listFound"></div>
</section>
<section>
<div class="paragraphs">
<section>
<div class="paragraphs">
<div id="p"><p>Buffalofish sawtooth </p>
<p>eel tigerperch, john dory sleeper,</p>
<p>Spanish mackerel </p>
<p>sockeye salmon sturgeon </p>
<p>gray mullet bottlenose. </p>
<p>Banjo catfish wallago; deep </p>
<p>sea smelt titan triggerfish </p>
<p>Australian grayling threadfin </p>
<p>bighead carp longnose lancetfish </p>
<p>pineconefish. Pipefish mojarra </p>
<p>northern pearleye cutthroat trout </p>
<p>sand diver; freshwater shark wrasse. </p></div>
</div>
</section>
</div>
</section>

Maybe like this:
var input = document.querySelector('input');
var p = document.querySelectorAll('p');
input.addEventListener('input', e => {
var value = input.value;
p.forEach(p => {
if (!p.innerText.includes(value)) {
p.style.display = 'none';
} else {
p.style.display = 'block';
}
p.innerHTML = p.innerText.replace(value, '<span>'+value+'</span>')
})
})
:root {
--primary-color: crimson;
--dark-color: #013;
--light-color: whitesmoke;
}
body {
color: var(--dark-color);
background-color: var(--light-color);
padding: 1rem;
}
header {
text-align: center;
}
main {
max-width: 567px;
margin: 0 auto;
}
.search__container {
text-align: center;
padding: 1rem;
margin: 0 auto;
}
.search__input {
border: 2px solid var(--dark-color);
padding: 1rem;
text-align: center;
}
.search__input:hover,
.search__input:focus {
outline: none;
border-color: var(--primary-color);
-webkit-box-shadow: 0 0 5px 0.1px var(--primary-color);
box-shadow: 0 0 5px 0.1px var(--primary-color);
}
.paragraphs span {
text-shadow: 0 0 6px var(--primary-color);
color: var(--primary-color);
}
<section class="search__container">
<input class="search__input" type="text" spellcheck="false" placeholder="search..." />
</section>
<section>
<div class="paragraphs">
<p>Google Maps</p>
<p>Google Photos</p>
<p>Google Translate</p>
<p>Google Earth</p>
<p>Google Lens</p>
</div>
</section>

Related

Vanilla JS budget app delete dynamically rendered income or expense

I've made a budgeting app that has expenses and Income tabs. Every time you add an expense or income, the app pushes the information inside of an array of objects and dynamically renders an <li> component and places it inside of a <ul>. I'm having trouble with the edit and delete features. Each individual <li> comes with a delete and edit button. The <li>, delete button, and edit button all have the same id of Date.now(). Date.now() is used because it produces a number based on milliseconds and won't produce the same id twice unless someone types an expense or income twice within one millisecond I want to click on the delete button inside of the <li> and have my app remove that individual object from my entry_list[] array and also remove the <li> from the DOM.
'use strict'
const balanceElement = document.querySelector(".balance .value");
const totalIncome = document.querySelector(".income-total");
const totalOutcome = document.querySelector(".outcome-total");
const incomeElement = document.querySelector(".income-tab");
const expense = document.querySelector(".expense-tab");
const all = document.querySelector(".all-tab");
const incomeList = document.querySelector(".income-tab .list");
const expenseList = document.querySelector(".expense-tab .list");
const allList = document.querySelector(".all-tab .list");
const expensesButton = document.querySelector(".tab1");
const incomeButton = document.querySelector(".tab2");
const allButton = document.querySelector(".tab3");
const addExpense = document.querySelector(".add-expense")
const expenseTitle = document.querySelector(".expense-title-input")
const expenseAmount = document.querySelector(".expense-amount-input")
const addIncome = document.querySelector(".add-income")
const incomeTitle = document.querySelector(".income-title-input")
const incomeAmount = document.querySelector(".income-amount-input")
const list = document.querySelector('.list')
//SWITCHING BETWEEN TABS
expensesButton.addEventListener('click', () => {
expense.classList.remove('hidden');
incomeElement.classList.add('hidden');
expensesButton.classList.add('clicked');
incomeButton.classList.remove('clicked');
})
incomeButton.addEventListener('click', () => {
incomeElement.classList.remove('hidden');
expense.classList.add('hidden');
expensesButton.classList.remove('clicked');
incomeButton.classList.add('clicked');
})
incomeList.addEventListener('click', deleteOrEdit)
expenseList.addEventListener('click', deleteOrEdit)
let entry_list = []
addExpense.addEventListener('click', () =>{
if(expenseTitle.value == '' || expenseAmount.value == ''){
return;
}
let expense = {
type: 'expense',
title: expenseTitle.value,
amount: expenseAmount.value,
id: Date.now()
}
entry_list.push(expense)
clearExpense()
changeLists()
})
addIncome.addEventListener('click', () =>{
if(incomeTitle.value == '' || incomeAmount.value == ''){
return;
}
let income = {
type: 'income',
title: incomeTitle.value,
amount: incomeAmount.value,
id: Date.now()
}
entry_list.push(income)
clearIncome()
changeLists()
})
const clearExpense = () =>{
expenseTitle.value = '';
expenseAmount.value = '';
}
const clearIncome = () =>{
incomeTitle.value = ''
incomeAmount.value = ''
}
const changeLists = () =>{
expenseList.innerHTML = ''
incomeList.innerHTML = ''
entry_list.map((entry) =>{
if(entry.type == 'expense'){
return expenseList.innerHTML += `<li id = "${entry.id}" class= "${entry.type}">
<div class = "entry">${entry.title}: $${entry.amount}</div>
<div class="icon-container">
<div class = "edit" id="${entry.id}"></div>
<div class ="delete" id="${entry.id}"></div>
</div>
</li>`
}
else if(entry.type == 'income'){
return incomeList.innerHTML += `<li id = "${entry.id}" class= "${entry.type}">
<div class = "entry">${entry.title}: $${entry.amount}</div>
<div class="icon-container">
<div class = "edit" id="${entry.id}"></div>
<div class ="delete" id="${entry.id}"></div>
</div>
</li>`
}
})
addIncomes()
}
const addIncomes = () =>{
let sum = 0;
let income = 0;
let outcome = 0;
balanceElement.innerHTML = 0
totalIncome.innerHTML = 0
totalOutcome.innerHTML = 0
entry_list.forEach(list =>{
if(list.type == 'expense'){
sum -= list.amount
outcome -= list.amount
}else if(list.type == 'income'){
sum += Number(list.amount)
income += Number(list.amount)
}
balanceElement.innerHTML = '$' + sum
totalIncome.innerHTML = '$' + income
totalOutcome.innerHTML = '$' + outcome
})
}
// // DETERMINE IF BUTTON IS EDIT OR DELETE
function deleteOrEdit(e){
const targetButton = e.target;
const entry = targetButton.parentNode.parentNode;
if(targetButton.classList == ('delete')){
deleteEntry(entry)
}else if(targetButton.classList == ('edit')){
editEntry(entry);
}
}
// //DELETE FUNCTION
const deleteEntry = (entry) =>{
console.log(entry.id)
entry_list.splice(entry.id, 1)
// entry.innerHTML = ''
console.log(entry.id)
addIncomes()
}
// EDIT FUNCTION
const editEntry = (entry) =>{
let Entry = entry_list[entry.id]
if(entry.type == "income"){
incomeAmount.value = Entry.amount;
incomeTitle.value = Entry.title;
}else if(entry.type == "expense"){
expenseAmount.value = Entry.amount;
expenseTitle.value = Entry.title;
}
deleteEntry(entry);
}
#import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght#400;700&family=Raleway:wght#400;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Open Sans', sans-serif;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
.budget-container{
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
width: 100%;
background-color: #4F98CA;
}
.balance-container{
width: 360px;
height: 470px;
background-color: #50D890;
border-radius: 30px;
margin-right: 100px;
}
.app-title{
color: white;
margin-top: 1rem;
margin-left: 1rem;
}
.month{
color: white;
margin-top: 1rem;
text-align: center;
}
.budget-header{
display: flex;
flex-direction:column;
justify-content: center;
}
.balance{
margin-top: 1rem;
margin-left: 1rem;
}
.title{
color: white;
font-size: 1.25rem;
opacity: .75;
}
.value{
font-size: 1.75rem;
color: white;
font-weight: bold;
margin-left: 1rem;
}
.account{
margin-top: 2.5rem;
margin: 2.5rem 1.5rem 2.5rem 1.5rem;
display: flex;
justify-content: space-between
}
.income-total{
color: white;
text-align: center;
font-size: 1.5rem;
}
.outcome-total{
color: #4F98CA;
text-align: center;
font-size: 1.5rem;
}
/* DASHBOARD */
.budget-dashboard{
display: block;
width: 360px;
height: 470px;
position: relative;
border-radius: 30px;
background-color: white;
}
.dash-title{
margin-top: 2rem;
margin-left: 1rem;
font-size: 1.5rem;
}
.toggle{
margin: 1rem;
display: flex;
cursor: pointer;
}
.toggle .tab2, .tab3{
margin-left: 1rem;
cursor: pointer;
}
.clicked{
font-weight: bold !important;
}
.hidden{
display: none !important;
}
/* EXPENSES TAB */
.expense-tab{
display: flex;
justify-content: center;
}
.expense-input-container{
position: absolute;
top: 400px;
border-top: solid 1px gray;
width: 100%;
}
.expense-amount-input{
width: 125px;
border: none;
outline: none;
font-size: 1.25rem;
}
.expense-title-input{
width: 125px;
border: none;
outline: none;
font-size: 1.25rem;
}
.add-expense{
color: none;
background-color: none;
border: none;
outline: none;
color: inherit;
}
/* INCOME TAB */
.income-tab{
display: flex;
justify-content: center;
}
.income-input-container{
position: absolute;
top: 400px;
border-top: solid 1px gray;
width: 100%;
}
.input{
display: flex;
justify-content: space-between;
align-items: center;
margin: 1rem;
}
.income-amount-input{
width: 125px;
border: none;
outline: none;
font-size: 1.25rem;
}
.income-title-input{
width: 125px;
border: none;
outline: none;
font-size: 1.25rem;
}
.add-income{
color: none;
background-color: none;
border: none;
outline: none;
}
.plus-img{
width: 40px;
}
/* li */
ul{
width: 360px;
height: 255px;
list-style: none;
margin-top:20px;
overflow-x: auto;
}
/* BUTTON ICONS */
.edit{
background-image: url('media/Icons/icons8-edit-48.png');
background-size: contain;
width: 25px;
height: 25px;
background-repeat: no-repeat;
margin-right: 10px;
}
.delete{
background-image: url('media/Icons/icons8-trash-can-48 (2).png');
background-size: contain;
width:25px;
height: 25px;
background-repeat: no-repeat;
}
.income{
width:250px;
height: auto;
padding-left: 20px;
margin-bottom: 10px;;
word-wrap: break-word;
color: black
}
.expense{
width:250px;
height: auto;
padding-left: 20px;
margin-bottom: 10px;;
word-wrap: break-word;
font-family: 'Gilroy Bold';
color: #4F98CA;
}
li{
display: flex;
justify-content: space-between;
width: 100% !important;
padding-right: 20px;
}
.icon-container{
display: flex;
}
#media (max-width:900px){
.budget-container{
display: inline-block;
position: relative
}
.balance-container{
position: absolute;
top: 10%;
left: 25%;
}
.budget-dashboard{
position: absolute;
left: 25%;
top: 40%;
}
}
<!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="style.css">
<title>Budgetrr</title>
</head>
<body>
<main class="budget-container">
<section class="balance-container">
<div class="app-title">
<p>Budgetrr</p>
</div>
<h1 class="month">OCTOBER</h1>
<section class="budget-header">
<div class="balance">
<div class="title">
Balance
</div>
<div class="value">
<small>$</small>0
</div>
</div>
<div class="account">
<div class="budget-income">
<div class="title">
Income
</div>
<div class="income-total">
<small>$</small>0
</div>
</div>
<div class="chart"></div>
<div class="budgetoutcome">
<div class="title">
Expenses
</div>
<div class="outcome-total">
<small>$</small>0
</div>
</div>
</div>
</section>
</section>
<section class="budget-dashboard">
<div class="dash-title">Dashboard</div>
<div class="toggle">
<div class="tab1 clicked">Expenses</div>
<div class="tab2">Income</div>
<!-- <div class="tab3 clicked">All</div> -->
</div>
<div class="income-tab hidden">
<ul class="list"></ul>
<div class="income-input-container">
<form class="input">
<input type="text" class="income-title-input" name="title" placeholder="Title">
<input type="number" class="income-amount-input" name="amount" placeholder="$0">
<button type = "button" class="add-income"><img class= "plus-img"src="media/Icons/icons8-add-new-48.png" alt=""></button>
</form>
</div>
</div>
<div class = "expense-tab">
<ul class="list"></ul>
<div class="expense-input-container">
<div class="input">
<input type="text" class="expense-title-input" name="title" placeholder="Title">
<input type="number" class="expense-amount-input" name="amount" placeholder="$0">
<button type="button" class="add-expense"><img class= "plus-img" src="media/Icons/icons8-add-new-48.png" alt=""></button>
</div>
</div>
</div>
</section>
</main>
<script src="JavaScript/budget.js"></script>
</body>
</html>
I've tried to use .splice() but I can't seem to get it to work.
Your entry is an object. And entry has an id property with Date type.
Your delete function calls this:
entry_list.splice(entry.id, 1)
Javascript splice function
function takes number as argument(s).
You should find the id of element you want to delete and get its index. After that you can delete the element with splice method.
Here is how to delete:
// Find the index of object at the given list
const index = entry_list.findIndex(x => x.id === entry.id);
// Starting from index of element to delete, remove 1 element.
entry_list.splice(index, 1);

If using javascript to get information on click, put it in another field

I just learned javascript and encountered a problem, do not know how to write!
I hope that after clicking one of the options, the information on the selected option, such as the food name and price, can be brought to the blue area to display!
But I don't know how to proceed, I hope everyone can help, thank you.
let plan = document.querySelector('.paln');
let price = document.querySelector('.price');
let item = document.querySelectorAll('.item');
for (var i = 0; i < item.length; i++) {
item[i].addEventListener('click', showplan, false);
}
function showplan() {
console.log('hello')
}
.product_list {
display: flex;
}
.product_list .item {
border: 1px solid #ccc;
border-radius: 6px;
text-align: center;
padding: 20px;
margin: 20px;
}
.product_list .item h2 {
margin-bottom: 16px;
}
.product_list .item:hover {
border: 1px solid #222;
}
.product_list .bold {
border: 3px solid;
}
.show {
border: 2px solid blue;
padding: 20px;
}
<ul class="product_list">
<li class="item">
<h2>coke</h2>
<p>$100</p>
</li>
<li class="item">
<h2>fries</h2>
<p>$600</p>
</li>
</ul>
<h2 class="show">Your food of choice is<span class="plan"></span>price is<span class="price"></span></h2>
If you click on either of the buttons it activates a function that changes the contents of .show
document.getElementById("item1").addEventListener('click', () => {document.querySelector(".show").innerText = "Your food of choice is Coke Price is $100";})
document.getElementById("item2").addEventListener('click', () => {document.querySelector(".show").innerText = "Your food of choice is Fries Price is $600";})
.product_list {
display: flex;
}
.product_list .item {
border: 1px solid #ccc;
border-radius: 6px;
text-align: center;
padding: 20px;
margin: 20px;
}
.product_list .item h2 {
margin-bottom: 16px;
}
.product_list .item:hover {
border: 1px solid #222;
}
.product_list .bold {
border: 3px solid;
}
.show {
border: 2px solid blue;
padding: 20px;
}
<ul class="product_list">
<li class="item" id="item1">
<h2>coke</h2>
<p>$100</p>
</li>
<li class="item" id="item2">
<h2>fries</h2>
<p>$600</p>
</li>
</ul>
<h2 class="show">Your food of choice is<span class="plan"></span> price is<span class="price"></span></h2>
you needs get the object clicked, so if you click at any where of <li> your target goings to be the h2 or <p> so you need search the closest <li> tag.
let plan = document.querySelector('.plan');
let price = document.querySelector('.price');
let item = document.querySelectorAll('.item');
for (var i = 0; i < item.length; i++) {
item[i].addEventListener('click', showplan, false);
}
function showplan(e) {
const planSelected = e.target.closest('li').querySelector('h2');
const priceSelected = e.target.closest('li').querySelector('p');
plan.innerHTML = planSelected.innerHTML;
price.innerHTML = priceSelected.innerHTML;
}

i am create Game tic tac toe but when Start game it's direct show winners name First Time after Run Game Completely

Code Link : https://github.com/henil11d/TicTacToi
Output : https://henil11d.github.io/TicTacToi/
You Check My Javascript Code On github page Solve My Problem
Problem is -:When Start Game Show Winner Name First Time after Program Run Completely
i am already Provided my code and output link please help.
You can update my code in GitHub page and help me
Source Code
Output
Please Help.
var c = 1;
function fil(elem) {
if (c <= 9) {
if (c % 2 != 0) {
document.getElementById(elem.id).innerHTML = "X";
d = 0;
}
else {
document.getElementById(elem.id).innerHTML = "O";
d = 1;
}
c++;
if (CkeckWin()) {
if (d == 0) {
alert("win X");
}else{
alert("win O");
}
reset();
}
} else {
alert("Match is Draw");
reset();
}
}
function reset() {
for (var i = 1; i <= 9; i++) {
document.getElementById("d" + i).innerHTML = "";
}
c = 1;
}
function CkeckWin() {
if (didvalue('d1', 'd2', 'd3') || didvalue('d1', 'd5', 'd9') || didvalue('d7', 'd8', 'd9') || didvalue('d1', 'd4', 'd7') ||
didvalue('d3', 'd6', 'd9') || didvalue('d3', 'd5', 'd7') || didvalue('d4', 'd5', 'd6') || didvalue('d2', 'd5', 'd8')) {
return true;
}
}
function didvalue(id1, id2, id3) {
if (getData(id1) != "" && getData(id2) != "" && getData(id3) != "" &&
getData(id1) == getData(id2) && getData(id2) == getData(id3)) {
return true;
}
}
function getData(Did) {
return document.getElementById(Did).innerHTML.trim();
}
*{
margin: 0;
padding: 0;
}
body{
background-color: rgb(44, 43, 43);
text-align: center;
user-select: none;
}
h1{
color: aqua;
font-size: 100px;
font-family: 'Courier New', Courier, monospace;
text-shadow: 0 0 6px rgb(234, 236, 122);
margin-top: 60px;
}
a{
font-family: sans-serif;
padding: 15px;
margin-right: 40px;
color: rgb(252, 252, 252);
background-color: rgb(84, 24, 224);
border-radius: 25px;
font-size: 28px;
box-shadow: 0 0 15px 0 rgb(19, 18, 18);
border-bottom-left-radius: 5px;
border-top-right-radius: 5px ;
text-decoration: none;
font-weight: bold;
}
a:hover{
color: black;
background-color: rgb(1, 198, 247);
border-radius: 28px;
box-shadow: 0 0 10px 0 rgb(13, 3, 160);
border-top-left-radius: 5px;
border-bottom-right-radius: 5px ;
}
a:active{
color: red;
}
.box{
border: 3px solid rgb(101, 250, 87);
height: 170px;
font-size: 140px;
width: 170px;
cursor: pointer;
color: rgb(3, 176, 182);
float: left;
}
.box:hover{
background-color: rgb(106, 109, 109);
}
.box:active{
background-color: antiquewhite;
}
.main{
position: relative;
top: 60px;
left: 140px;
width: 800px;
margin: auto;
/* display: none; */
}
#d1,#d4,#d7{
clear: left;
border-left: none;
}
#d1,#d2,#d3{
border-top: none;
}
#d3,#d6,#d9{
border-right: none;
}
#d7,#d8,#d9{
border-bottom: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title> Henil Code </title>
<link rel="stylesheet" href="Tecto.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"> </script>
<script src="te.js"> </script>
</head>
<body>
<!-- Henil Code -->
<h1> tic tac toe </h1>
<div class="main">
<div id="d1" class="box" onclick="fil(this)"> </div>
<div id="d2" class="box" onclick="fil(this)"> </div>
<div id="d3" class="box" onclick="fil(this)"> </div>
<div id="d4" class="box" onclick="fil(this)"> </div>
<div id="d5" class="box" onclick="fil(this)"> </div>
<div id="d6" class="box" onclick="fil(this)"> </div>
<div id="d7" class="box" onclick="fil(this)"> </div>
<div id="d8" class="box" onclick="fil(this)"> </div>
<div id="d9" class="box" onclick="fil(this)"> </div>
</div>
</body>
</html>
trim() function return like " " to ""
you need to add trim()
Change Code
function getData(Did) {
return document.getElementById(Did).innerHTML.trim();// trim() data
}

How to change color of div element depending on color of the block with JavaScript?

I have 2 blocks for user to choose from and they should be interactive. The block changes the color and the vertical line color should be changed to opposite. I wonder if I could make it right in the same code snippet which does the color change of the code block, because previously I made it, but with another for loop and it's not the fastest way.
let vanOption = document.getElementsByClassName("van-quote-option");
let quoteVl = document.getElementById("option-vl");
// Van option selection
for (var x = 0; x < vanOption.length; x++) {
vanOption[x].addEventListener("click", function() {
var currentOption = document.getElementsByClassName("option-active");
if (currentOption.length > 0) {
currentOption[0].className = currentOption[0].className.replace(" option-active", "");
}
this.className += " option-active";
});
}
.van-quote-option {
display: flex;
justify-content: space-evenly;
margin: 25px 165px 20px 165px;
border: 1px solid grey;
cursor: pointer;
transition: 0.5s;
}
.option-active {
background-color: #18A063;
color: #fff;
}
.quote-vl {
border-left: 2px solid #13985C;
height: 116px;
}
.quote-vl-active {
border-left: 2px solid #fff;
height: 116px;
}
.quote-icon {
margin: 25px 0 0 35px;
}
.quote-van-icon {
font-size: 49px;
padding: 8px;
border-radius: 50%;
height: 60px;
background-color: rgb(245, 245, 245);
color: #18A063;
}
.quote-car-icon {
font-size: 49px;
padding: 9px;
height: 52px;
background-color: rgb(245, 245, 245);
color: #18A063;
border-radius: 50%;
}
.quote-bicycle-icon {
font-size: 49px;
padding: 10px;
height: 55px;
background-color: rgb(245, 245, 245);
color: #18A063;
border-radius: 50%;
}
.quote-p {
text-align: left;
}
.quote-p-van {
text-align: left;
margin-top: 5px;
}
.bicycle-quote-vl,
.car-quote-vl {
height: 124px;
}
.quote-price {
display: flex;
flex-direction: column;
justify-content: center;
}
.quote-price-van {
margin-top: 10px;
}
.van-send-price,
.car-send-price,
.bicycle-send-price {
font-size: 25px;
font-weight: 700;
}
.van-send-price::before,
.car-send-price::before,
.bicycle-send-price::before {
content: "\00A3";
}
<div class="quote-options">
<div class="van-quote-option option-active">
<div class="quote-icon quote-icon-1">
<i class="fas fa-truck quote-van-icon"></i>
</div>
<div class="quote-p-van">
<div class="quote-p-1">Sending 1 or 2 items (with van)</div>
<br />
<div class="quote-p-2">
We'll take a maximum of 2 items for you<br />
to deliver immediately at any location.
</div>
</div>
<div class="quote-vl quote-vl-active"></div>
<div class="quote-price-van">
<span class="van-send-price" id="van-deliver-price">14</span><br />
For a max.<br />
of 2 items.
</div>
</div>
<div class="van-quote-option">
<div class="quote-icon quote-icon-1">
<i class="fas fa-truck quote-van-icon"></i>
</div>
<div class="quote-p-van">
<div class="quote-p-1">Hire a van</div>
<br />
<div class="quote-p-2">
We'll take a maximum of 2 items for you<br />
to deliver immediately at any location.
</div>
</div>
<div class="quote-vl"></div>
<div class="quote-price-van">
<span class="van-send-price" id="van-deliver-price">38</span><br />
Hire a van,<br />
∞ items
</div>
</div>
</div>
You can fix this with css.
You don't really need the quote-vl-active class. Remove it.
You can refer to the vertical line when it's active using option-active since it's the child of that element.
.option-active > .quote-vl {
border-left: 2px solid white;
height: 116px;
}
See this fiddle: https://jsfiddle.net/29r1v0Lo/
might want to use onclick vs. adding listeners as well.
Here is a jsfiddle of it a bit cleaner and with the vert bar having the opposite color: https://jsfiddle.net/7L0uzkxj/
You can just have the CSS control the vert bar:
.quote-vl {
border-left: 2px solid green;
height: 116px;
}
.option-active .quote-vl {
border-left: 2px solid white;
height: 116px;
}
You can then clean up the JS to look like this:
function triggerMe(evt) {
let vanOption = document.getElementsByClassName("van-quote-option");
[...vanOption].forEach(x => {
if (x.classList.contains('option-active')) {
x.classList.remove('option-active');
}
})
evt.classList.toggle('option-active');
}

Javascript - When I click on an input, the associated object deletes itself

I'm trying to create a GPA calculator (just to practice html, css, javascript) and am having an issue I can't seem to solve. Here's what's happening.
TL;DR: When I click on an input field, the corresponding object is erased.
For each course, there is a form with input fields for course name (text input), grade (select input), and credits earned (number input). When you want to add another course, you're adding another form. When a form is created, so is an object that's associated with it. I create this association by adding an id to the form with a unique number and also adding that id number to the object.
When I console.log the various steps of creating an object and setting its values and saving it to the local storage, everything works fine. However, when I was trying to create functionality to update the values of the objects, I started having troubles. I've pinpointed when they happen. Whenever I click on an input field, the object is erased. Specifically, only the object that's tied to that input field is erased. So if I create 5 forms and I click on the text input of the 3rd one, the 3rd object is erased. I can click on that same field multiple times and nothing else will happen. Then, if I click, say, the number input of the 5th form, then the 5th object is erased. I know it's not the delete function at work because that function would also remove the form from view.
If anyone could help me pinpoint what I can do to fix this, I would greatly appreciate it.
Javascript
// Theme
let lightMode = document.getElementById('light-mode');
let darkMode = document.getElementById('dark-mode');
lightMode.addEventListener('click', () => {themeTransition(); document.documentElement.setAttribute('data-theme', 'light');});
darkMode.addEventListener('click', () => {themeTransition(); document.documentElement.setAttribute('data-theme', 'dark');});
function themeTransition()
{
document.documentElement.classList.add('transition');
window.setTimeout(() => document.documentElement.classList.remove('transition'), 1000);
}
// GPA CALCULATION
// Object ID
var objId = 0;
// Grades class
class Grades
{
constructor(id, course, grade, credits)
{
this.id = id;
this.course = course;
this.grade = grade;
this.credits = credits;
}
}
// Storage class
class Store
{
static getGrades()
{
let grades;
if (localStorage.getItem('grades') == null)
{
grades = [];
}
else
{
grades = JSON.parse(localStorage.getItem('grades'));
objId = localStorage.getItem('objId');
}
return grades;
}
static addGrade(grade, newObjId)
{
const grades = Store.getGrades();
grades.push(grade);
localStorage.setItem('grades', JSON.stringify(grades));
localStorage.setItem('objId', JSON.stringify(newObjId));
console.log(grades);
}
static updateGrade(id, course, grade, credits)
{
const grades = Store.getGrades();
grades.forEach((oldGrade, index) =>
{
if (oldGrade.id == id)
{
oldGrade[index].course = course;
oldGrade[index].grade = grade;
oldGrade[index].credits = credits;
}
});
localStorage.setItem('grades', JSON.stringify(grades));
}
static removeGrade(id)
{
const grades = Store.getGrades();
grades.forEach((grade, index) =>
{
if (grade.id == id)
{
grades.splice(index, 1);
}
});
localStorage.setItem('grades', JSON.stringify(grades));
}
}
// UI class
class UI
{
static displayGrades()
{
const grades = Store.getGrades();
grades.forEach((grade) => UI.addCurrentGrade(grade));
}
static addCurrentGrade(grade)
{
const list = document.querySelector('.add-grades');
const row = document.createElement('form');
const addBefore = document.querySelector('.add');
row.classList.add('add-item');
row.setAttribute('id', `${grade.id}`)
row.innerHTML =
`
<div class="input-node course">
<label for="course">Course</label>
<input type="text" id="course">
</div>
<div class="input-node grade">
<label for="grade">Grade</label>
<select id="grade">
<option value="none"></option>
<option value="A">A</option>
<option value="A-">A-</option>
<option value="B+">B+</option>
<option value="B">B</option>
<option value="B-">B-</option>
<option value="C+">C+</option>
<option value="C">C</option>
<option value="C-">C-</option>
<option value="D+">D+</option>
<option value="D">D</option>
<option value="D-">D-</option>
<option value="F">F</option>
<option value="W">W</option>
<option value="I">I</option>
<option value="P">P</option>
<option value="NP">NP</option>
</select>
</div>
<div class="input-node credits">
<label for="credits">Credits</label>
<input type="number" id="credits">
</div>
<div class="input-node delete">
<i class="fas fa-times-circle"></i>
</div>
`;
list.insertBefore(row, addBefore);
document.querySelector('.delete').addEventListener('click', delGrade);
document.querySelector('.add-grades').addEventListener('input', updateGrades);
}
static addNewGrade(e)
{
if (e.parentElement.classList.contains('add-grade'))
{
objId++;
const currentId = objId;
const list = document.querySelector('.add-grades');
const row = document.createElement('form');
const addBefore = document.querySelector('.add');
row.classList.add('add-item');
row.setAttribute('id', `${currentId}`)
row.innerHTML =
`
<div class="input-node course">
<label for="course">Course</label>
<input type="text" id="course">
</div>
<div class="input-node grade">
<label for="grade">Grade</label>
<select id="grade">
<option value="none"></option>
<option value="A">A</option>
<option value="A-">A-</option>
<option value="B+">B+</option>
<option value="B">B</option>
<option value="B-">B-</option>
<option value="C+">C+</option>
<option value="C">C</option>
<option value="C-">C-</option>
<option value="D+">D+</option>
<option value="D">D</option>
<option value="D-">D-</option>
<option value="F">F</option>
<option value="W">W</option>
<option value="I">I</option>
<option value="P">P</option>
<option value="NP">NP</option>
</select>
</div>
<div class="input-node credits">
<label for="credits">Credits</label>
<input type="number" id="credits">
</div>
<div class="input-node delete">
<i class="fas fa-times-circle"></i>
</div>
`;
list.insertBefore(row, addBefore);
document.querySelector('.delete').addEventListener('click', delGrade);
document.querySelector('.add-grades').addEventListener('input', updateGrades);
const course = e.parentElement.parentElement.querySelector('#course').value;
const grade = e.parentElement.parentElement.querySelector('#grade').value;
const credits = e.parentElement.parentElement.querySelector('#course').value;
const grades = new Grades(currentId, course, grade, credits);
Store.addGrade(grades, currentId);
}
}
static deleteGrade(del)
{
if (del.parentElement.classList.contains('delete'))
{
del.parentElement.parentElement.remove();
}
}
}
// EVENTS
// Display Existing Grades
document.addEventListener('DOMContentLoaded', UI.displayGrades);
// Add Grade
document.querySelector('.add-grade').addEventListener('click', (e) =>
{
UI.addNewGrade(e.target);
});
// Update Grade
document.querySelector('.add-grades').addEventListener('input', updateGrades);
function updateGrades(e)
{
const id = e.target.parentElement.parentElement.getAttribute('id');
const course = e.target.parentElement.parentElement.querySelector('#course').value;
const grade = e.target.parentElement.parentElement.querySelector('#grade').value;
const credits = e.target.parentElement.parentElement.querySelector('#course').value;
Store.updateGrade(id, course, grade, credits);
}
// Remove Grade
document.querySelector('.add-grades').addEventListener('click', delGrade);
function delGrade(e)
{
UI.deleteGrade(e.target);
Store.removeGrade(e.target.parentElement.parentElement.getAttribute('id'));
}
document.body.addEventListener('click', testFun);
function testFun()
{
const grades = Store.getGrades();
console.log(grades);
}
note: function testFun() is to log the objects in the Grades class whenever I click on anything
HTML
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.1/css/all.css" integrity="sha384-xxzQGERXS00kBmZW/6qxqJPyxW3UR0BPsL4c8ILaIWXva5kFi7TxkIIaMiKtqV1Q" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>GPA Calculator</title>
</head>
<body>
<div class="container">
<div id="view-mode">
<button id="light-mode">Light</button> | <button id="dark-mode">Dark</button>
</div>
<header class="header">
<h1>GPA</h1>
<h2>Calculator</h2>
</header>
<section class="add-grades">
<div class="table-header">
<h1>Semester <span class="semester">–</span></h1>
<h2>Semester GPA: <span class="gpa-semester">–</span></h2>
</div>
<div class="add add-grade">
<i class="fas fa-plus-circle"></i>
</div>
</section>
<div class="add add-semester">
<i class="fas fa-plus-circle"></i>
</div>
<aside class="gpa-total">
<h2>GPA</h2>
<h1><span class="gpa-total">–</span></h1>
</aside>
</div>
<script src="main.js"></script>
</body>
</html>
If you want the full effect, here's the CSS as well
/* Global */
html[data-theme="light"]
{
--background: rgb(235, 235, 235);
--panel: rgb(245, 245, 245);
--panel-head: rgb(0, 80, 190);
--text: rgb(20, 20, 20);
--text-secondary: rgb(60, 60, 60);
--text-panel: rgb(20, 20, 20);
--text-panel-head: rgb(245, 245, 245);
--add: rgb(58, 180, 34);
--delete: rgb(255, 55, 55);
}
html[data-theme="dark"]
{
--background: rgb(40, 40, 40);
--panel: rgb(70, 70, 70);
--panel-head: rgb(0, 106, 255);
--text: rgb(245, 245, 245);
--text-secondary: rgb(120, 120, 120);
--text-panel: rgb(245, 245, 245);
--text-panel-head: rgb(245, 245, 245);
--add: rgb(58, 180, 34);
--delete: rgb(255, 55, 55);
}
*
{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body
{
background: var(--background);
font-family: Cochin, Georgia, Times, 'Times New Roman', serif;
font-size: 16px;
color: var(--text);
}
.container
{
width: 80%;
margin: auto;
}
button
{
background: none;
border: none;
outline: none;
}
/* Header */
#view-mode
{
text-align: right;
margin-top: 20px;
}
#view-mode button
{
font-size: 16px;
color: var(--text);
}
#view-mode button:hover
{
color: var(--panel-head);
text-decoration: underline;
cursor: pointer;
}
.header
{
margin: 20px 0 50px 0;
text-align: center;
text-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
text-transform: uppercase;
}
.header h1
{
font-size: 6em;
}
.header h2
{
font-size: 1.77em;
color: var(--text-secondary);
}
/* User Input */
.add-grades
{
min-width: 400px;
max-width: 500px;
margin: auto;
margin-top: 20px;
background: var(--panel);
color: var(--text-panel);
border-radius: 20px;
display: flex;
flex-direction: column;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
.table-header
{
padding: 10px 15px;
display: flex;
justify-content: space-between;
align-items: baseline;
border-top-right-radius: 20px;
border-top-left-radius: 20px;
background: var(--panel-head);
color: var(--text-panel-head);
}
.table-header h1
{
font-size: 2em;
}
.table-header h2
{
font-size: 1.2em;
}
.add-item
{
padding: 10px;
display: flex;
justify-content: space-between;
align-items: center;
}
.add-item .input-node
{
display: flex;
justify-content: space-between;
align-items: center;
}
.add-item .input-node *
{
margin: 0 3px;
}
.input-node #course
{
width: 75px;
padding: 5px;
border: none;
border-radius: 5px;
outline: none;
box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);
}
.input-node #grade
{
font-size: 1em;
outline: none;
}
.input-node #credits
{
width: 40px;
padding: 5px;
border: none;
border-radius: 5px;
outline: none;
box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);
}
.delete i
{
font-size: 1.4em;
padding: 0;
color: var(--text-panel);
}
.delete i:hover
{
color: var(--delete);
cursor: pointer;
}
.add-grades .add
{
margin: 13px;
margin-top: 10;
display: flex;
justify-content: flex-end;
}
.add i
{
font-size: 1.4em;
color: var(--text-panel);
}
.add i:hover
{
color: var(--panel-head);
cursor: pointer;
}
.container > .add
{
min-width: 400px;
max-width: 500px;
margin: auto;
margin-top: 20px;
}
/* GPA Calculation */
.gpa-total
{
margin-top: 50px;
text-align: center;
}
.gpa-total h2
{
font-size: 3em;
text-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
.gpa-total h1
{
width: 250px;
margin: auto;
margin-top: 10px;
padding: 60px 0;
font-size: 6em;
border-radius: 100%;
background: var(--panel-head);
color: var(--text-panel-head);
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
/* Transition */
html.transition,
html.transition body,
html.transition body:before,
html.transition body:after,
html.transition section,
html.transition section:before,
html.transition section:after
{
transition: all 750ms !important;
transition-delay: 0 !important;
}

Categories