How to clear div output when input field is empty? - javascript

I have simple weight converter and I would like to clear the output when input field is empty.
I've tried to use reset, clear or empty method, but no one of them worked
const form = document.querySelector('.input');
form.addEventListener('keyup', e => {
e.preventDefault();
const getValue = form.add.value.trim();
const convert = weight => {
document.querySelector('.pounds').innerText = "Pounds: " + Math.round(weight * 2.20462262);
};
if (getValue.length) {
convert(getValue);
}
});
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<title>Todo List</title>
</head>
<body>
<div class="container">
<h1>Weight converter</h1>
<form class="input">
<input type="number" name="add">
</form>
<div class="pounds green "></div>
<div class="ounces red "></div>
<div class="grams blue "></div>
</div>
<script src="app.js"></script>
</body>
</html>

A ternary is useful
Also input handles paste
note I only preventDefault on the submit
const form = document.querySelector('.input');
const output = document.querySelector('.pounds');
const convert = weight => {
return "Pounds: " + Math.round(weight * 2.20462262);
};
form.addEventListener('submit', e => { // handles enter in the field
e.preventDefault();
});
form.addEventListener('input', () => {
const getValue = form.add.value.trim();
output.innerText = getValue.length ? convert(getValue) : "";
});
<div class="container">
<h1>Weight converter</h1>
<form class="input">
<input type="number" name="add" id="add">
</form>
<div class="pounds green "></div>
<div class="ounces red "></div>
<div class="grams blue "></div>
</div>
Full code
const form = document.querySelector('.input');
const convert = weight => {
return {
"pounds": Math.round(weight * 2.20462262),
"ounces": Math.round(weight * 35.274),
"grams": weight * 1000
}
};
form.addEventListener('submit', e => {
e.preventDefault();
})
form.addEventListener('input', () => {
const getValue = form.add.value.trim();
if (getValue.length) {
const weights = convert(getValue);
for (w in weights) {
document.querySelector("." + w).innerText = weights[w]
}
}
});
<div class="container">
<h1>Weight converter</h1>
<form class="input">
<input type="number" name="add" id="add">
</form>
<div class="pounds green "></div>
<div class="ounces red "></div>
<div class="grams blue "></div>
</div>

Try setting the innerText to '' like so :
if (getValue.length) {
convert(getValue);
} else {
document.querySelector('.pounds').innerText = '';
}
This should work

Related

e.target.style.backgroundColor is not a function TypeError

New to JS. For my etch-a-sketch project i cant seem to set a style on my grid divs when the color mode is active and the mouse goes over them. Been trying to fuck around with the scopes but im still getting used to it. TypeError e.target.style.backgroundColor is not a function.
const colorBtn = document.getElementById('color')
const shadeBtn = document.getElementById('shade')
const eraseBtn = document.getElementById('erase')
const clearBtn = document.getElementById('clear')
const gridCont = document.getElementById('grid')
let currentMode = ''
let gridSquare = document.createElement('div')
// creates grid on pageload
function makeGrid() {
for (i=0; i<200; i++) {
gridSquare
gridCont.appendChild(gridSquare)
gridSquare.classList.add('gridSquare')
}
}
window.onload = makeGrid()
//
colorBtn.addEventListener('click', () => {
currentMode = 'color'
})
shadeBtn.addEventListener('click', () => {
currentMode = 'shade'
})
eraseBtn.addEventListener('click', () => {
currentMode = 'erase'
})
clearBtn.addEventListener('click', () => {
gridSquare.style.backgroundColor('white')
})
function play() {
if ( currentMode === 'color' || currentMode === '') {
gridSquare.addEventListener('mouseover', (e) => {
e.target.style.backgroundColor('#050505')
})
}
}
window.onload = play()
<!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>scribblyscrabblydoo</title>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<div class="titlebox">
<h1>sribblyscrabblydoo</h1>
<p>Draw or something idk bro</p>
</div>
<div class="mainbod">
<div class="options">
<div class="buttons">
<h2>Options</h2>
</div>
<div class="buttons">
<button id="color">Color</button>
</div>
<div class="buttons">
<button id="shade">Shade</button>
</div>
<div class="buttons">
<button id="erase">Erase</button></div>
<div class="buttons">
<button id="clear">Clear</button>
</div>
<div class="buttons">
<button id="github">Duskope Github</button>
</div>
</div>
<div id="grid"></div>
</div>
</body>
<script type="text/javascript" src = "index.js"></script>
</html>
blah blah blah too much code not enough details to post
Because it's not a function.
You should use:
e.target.style.backgroundColor = '#050505'
The error description is telling you the exact issue, you are calling backgroundColor as a function when it is a property.

The cursor is not moving from one input to the next by pressing an Enter button in JavaScript

I want the cursor to move from one input to the next only when the enter button is pressed. And when it reaches the last input, I want it to move it to the first input again (like a loop). The problem is with this JavaScript code. I have generated it using OpenAI Playground.
Is adding event listeners to buttons necessary in this case? If so, how to call this code in input fields?
var inputs = document.querySelectorAll("input");
inputs.forEach(input => {
input.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
var nextInput = inputs[inputs.indexOf(e.target) + 1];
if (nextInput) {
nextInput.focus();
}
}
})
});
The complete html is here:
<!DOCTYPE html>
<html>
<head>
<title>
Inserting meaning
</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
#one
{
margin-left:auto;
margin-right:auto;
width:90%;
}
</style>
</head>
<body>
<script>
var inputs = document.querySelectorAll("input");
inputs.forEach(input => {
input.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
var nextInput = inputs[inputs.indexOf(e.target) + 1];
if (nextInput) {
nextInput.focus();
}
}
})
});
</script>
<div align ="center">
<h1>
Meaning In Sentence
</h1>
<div>
<h3>
Sentence:
</h3>
<input type="text" id="sentence" class="form-control" style="width:80%" placeholder="Enter the sentence">
</div>
<br>
<h3>
Difficult Word:
</h3>
<input type="text" id="word" class="form-control" style="width:80%" placeholder="Enter the difficult word">
<br>
<h3>
Meaning:
</h3>
<input type="text" id="meaning" class="form-control" style="width:80%" onchange="func()" placeholder="Enter the meaning">
<br>
</div>
<br>
<div class="h5" align = "center" id="modifiedsentence" onchange="func()">
<div>
<script>
function func()
{
var s=document.getElementById("sentence").value.replace(/['"]+/g, '');
var w=document.getElementById("word").value;
var m=document.getElementById("meaning").value;
s=s[0].toUpperCase()+s.slice(1);
var f=s.replace(w,w+" ("+m+") ")+"<br>"+
document.getElementById("modifiedsentence").innerHTML;
document.getElementById("modifiedsentence").innerHTML = f.toString();
document.getElementById("sentence").value = " ";
document.getElementById("word").value = " ";
document.getElementById("meaning").value = " ";
mvCursor();
// console.log(f);
}
</script>
</div>
</body>
</html>
Adding to bee zero's answer above:
You can check for the last input element and when return key is pressed reaches the last input element, you can focus to in zeroth index.
const nextinputIndex = index < (inputs.length - 1) ? (index + 1) : 0;
Test snippet:
<html>
<head>
<title>
Inserting meaning
</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
#one
{
margin-left:auto;
margin-right:auto;
width:90%;
}
</style>
</head>
<body>
<div align ="center">
<h1>
Meaning In Sentence
</h1>
<div>
<h3>
Sentence:
</h3>
<input type="text" id="sentence" class="form-control" style="width:80%" placeholder="Enter the sentence">
</div>
<br>
<h3>
Difficult Word:
</h3>
<input type="text" id="word" class="form-control" style="width:80%" placeholder="Enter the difficult word">
<br>
<h3>
Meaning:
</h3>
<input type="text" id="meaning" class="form-control" style="width:80%" onchange="func()" placeholder="Enter the meaning">
<br>
</div>
<br>
<div class="h5" align = "center" id="modifiedsentence" onchange="func()">
<div>
</div>
<script>
function func()
{
var s=document.getElementById("sentence").value.replace(/['"]+/g, '');
var w=document.getElementById("word").value;
var m=document.getElementById("meaning").value;
s=s[0].toUpperCase()+s.slice(1);
var f=s.replace(w,w+" ("+m+") ")+"<br>"+
document.getElementById("modifiedsentence").innerHTML;
document.getElementById("modifiedsentence").innerHTML = f.toString();
document.getElementById("sentence").value = " ";
document.getElementById("word").value = " ";
document.getElementById("meaning").value = " ";
// mvCursor(); REMOVING AS THIS IS NOT DEFINED
// console.log(f);
}
var inputs = document.querySelectorAll("input");
inputs.forEach((input, index) => {
input.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
const nextinputIndex = index < (inputs.length - 1) ? (index + 1) : 0;
var nextInput = inputs[nextinputIndex];
if (nextInput) {
nextInput.focus();
}
}
})
});
</script>
</body>
</html>
You can use the index param in forEach to grasp the index.
inputs.forEach((input, index) => { // HERE grab the index
input.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
var nextInput = inputs[index + 1]; // // HERE use the index
if (nextInput) {
nextInput.focus();
}
}
})
});
Complete snippet to test:
<html>
<head>
<title>
Inserting meaning
</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
#one
{
margin-left:auto;
margin-right:auto;
width:90%;
}
</style>
</head>
<body>
<div align ="center">
<h1>
Meaning In Sentence
</h1>
<div>
<h3>
Sentence:
</h3>
<input type="text" id="sentence" class="form-control" style="width:80%" placeholder="Enter the sentence">
</div>
<br>
<h3>
Difficult Word:
</h3>
<input type="text" id="word" class="form-control" style="width:80%" placeholder="Enter the difficult word">
<br>
<h3>
Meaning:
</h3>
<input type="text" id="meaning" class="form-control" style="width:80%" onchange="func()" placeholder="Enter the meaning">
<br>
</div>
<br>
<div class="h5" align = "center" id="modifiedsentence" onchange="func()">
<div>
</div>
<script>
function func()
{
var s=document.getElementById("sentence").value.replace(/['"]+/g, '');
var w=document.getElementById("word").value;
var m=document.getElementById("meaning").value;
s=s[0].toUpperCase()+s.slice(1);
var f=s.replace(w,w+" ("+m+") ")+"<br>"+
document.getElementById("modifiedsentence").innerHTML;
document.getElementById("modifiedsentence").innerHTML = f.toString();
document.getElementById("sentence").value = " ";
document.getElementById("word").value = " ";
document.getElementById("meaning").value = " ";
// mvCursor(); REMOVING AS THIS IS NOT DEFINED
// console.log(f);
}
var inputs = document.querySelectorAll("input");
inputs.forEach((input, index) => {
input.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
var nextInput = inputs[index + 1];
if (nextInput) {
nextInput.focus();
}
}
})
});
</script>
</body>
</html>
Probably need to make a little loop to find the next input.
var nextInput = e.target.nextElementSibling;
var found = false;
while (nextInput) {
if (nextInput.classList.contains("form-control")) {
found = true;
break;
}
nextInput = nextInput.nextElementSibling
}

EventHandler is not working.It gives No output when I click the button

I am using API for my website.My handleGetDetailsOrAddToFavorites event handler is working but handleRemoveFavorites EventHandler which has been implemented the same way is not working.But why???It gives no Error.Also console.log(e.target.value) in handleRemoveFavorites console logs Nothing.I want my handleRemoveFavorites to give out (e.target.value) so that i can fetch indivisual items Id and delete them from localstorage.
var url = 'https://www.themealdb.com/api/json/v1/1/search.php?s=';
var urlId = 'https://www.themealdb.com/api/json/v1/1/lookup.php?i='; //search by id
const mealList = document.getElementById('list-Items-container');
var input = document.getElementById('inputText');
const mealListFavorites = document.getElementById(
'list-Items-container-favorites'
);
window.onload = renderFavorites;
document.querySelector('form').addEventListener('submit', handleSubmitForm);
// .getElementById('get-details')
mealList.addEventListener('click', handleGetDetailsOrAddToFavorites);
mealListFavorites.addEventListener('click', handleRemoveFavorites);
function handleRemoveFavorites(e) {
e.preventDefault();
console.log(e.target.value);
}
function handleGetDetailsOrAddToFavorites(e) {
e.preventDefault();
console.log('clicked');
if (e.target.value == 'details') {
let mealItem = e.target.parentElement.parentElement;
fetch(
`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${mealItem.dataset.id}`
)
.then(function(res) {
return res.json();
})
.then((data) => {
mealRecipeModal(data.meals);
});
} else if (e.target.value == 'favour') {
let mealItem = e.target.parentElement.parentElement;
fetch(
`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${mealItem.dataset.id}`
)
.then(function(res) {
return res.json();
})
.then((data) => {
window.localStorage.setItem(
mealItem.dataset.id,
JSON.stringify(data.meals)
);
});
}
console.log(Object.entries(localStorage));
}
function mealRecipeModal(meal) {
console.log(meal[0]);
const destination = meal[0].strSource;
console.log(destination);
window.open(`${meal[0].strSource}`);
}
function handleSubmitForm(e) {
e.preventDefault();
let input = document.querySelector('input');
findFood(url + input.value);
input.value = '';
}
function findFood(address) {
fetch(address)
.then(function(res) {
//console.log(res);
return res.json();
})
.then((data) => {
console.log(data);
let html = '';
if (data.meals) {
data.meals.forEach((meal) => {
html += `<div class="food-card" data-id="${meal.idMeal}">
<div class="food-card-image">
<img src="${meal.strMealThumb}" alt="${meal.strMeal}" >
</div>
<div class="food-card-info">
<h3>${meal.strMeal}</h3>
</div>
<div class="food-card-features">
<button id="favorites" value="favour">Add</button>
<button id="get-details" value="details" >Details</button>
</div>
</div>`;
});
}
console.log(html);
mealList.innerHTML = html;
});
}
var html1 = '';
function findFoodFavorite(address) {
fetch(address)
.then(function(res) {
//console.log(res);
return res.json();
})
.then((data) => {
console.log(data);
if (data.meals) {
data.meals.forEach((meal) => {
html1 += `<div class="food-card" data-id="${meal.idMeal}">
<div class="food-card-image">
<img src="${meal.strMealThumb}" alt="${meal.strMeal}" >
</div>
<div class="food-card-info">
<h3>${meal.strMeal}</h3>
</div>
<div class="food-card-features">
<button id="favorites" value="defavour" >Remove</button>
<button id="get-details" value="details" >Details</button>
</div>
</div>`;
});
}
console.log(html1);
mealListFavorites.innerHTML = html1;
});
}
function renderFavorites() {
const urlArray = [];
console.log(Object.entries(localStorage));
for (var i = 0; i < localStorage.length; i++) {
console.log(Object.entries(localStorage)[i][0]);
urlArray.push(Object.entries(localStorage)[i][0]);
}
console.log(urlArray);
urlArray.forEach((id) => findFoodFavorite(urlId + id));
}
This is Index.html(homepage)
<!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="styles.css">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=M+PLUS+2:wght#200&family=Poppins:ital,wght#0,100;1,200&display=swap" rel="stylesheet">
<title>Meals App | HomePage</title>
</head>
<body>
<header>
<div class="topnav">
<a class="active" href="index.html">Home</a>
Favorites
Details
About
</div>
</header>
<div class="Heading">
<h1>The FoodAPP</h1>
</div>
<div class="form-container">
<form action="submit" method="get">
<input type="text" id="inputText" placeholder="Enter dish...">
<button id="btn" type="submit">Find</button>
</form>
</div>
<div id="list-Items-container">
<!-- <div class="food-card">
<div class="food-card-image">
<img src="http://placehold.it/120x120&text=image3" alt="food">
</div>
<div class="food-card-info">
<h3>Foood namae</h3>
</div>
</div> -->
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
This is favorites page
<!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="styles.css">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=M+PLUS+2:wght#200&family=Poppins:ital,wght#0,100;1,200&display=swap" rel="stylesheet">
<title>Meals App | Favaorites</title>
</head>
<body>
<header>
<div class="topnav">
<a class="active" href="index.html">Home</a>
Favorites
Details
About
</div>
</header>
<div id="list-Items-container-favorites">
<!-- <div class="food-card">
<div class="food-card-image">
<img src="http://placehold.it/120x120&text=image3" alt="food">
</div>
<div class="food-card-info">
<h3>Foood namae</h3>
</div>
</div> -->
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
I have separated your js file into two parts, one for home and one for favorite and put all of your code in window on load event :
index.js
var url = "https://www.themealdb.com/api/json/v1/1/search.php?s=";
function findFood(address, mealListEl) {
fetch(address)
.then(function (res) {
return res.json();
})
.then((data) => {
let html = "";
if (data.meals) {
data.meals.forEach((meal) => {
html += `<div class="food-card" data-id="${meal.idMeal}">
<div class="food-card-image">
<img src="${meal.strMealThumb}" alt="${meal.strMeal}" >
</div>
<div class="food-card-info">
<h3>${meal.strMeal}</h3>
</div>
<div class="food-card-features">
<button id="favorites" value="favour">Add</button>
<button id="get-details" value="details" >Details</button>
</div>
</div>`;
});
}
mealListEl.innerHTML = html;
});
}
function handleGetDetailsOrAddToFavorites(e) {
e.preventDefault();
if (e.target.value == "details") {
let mealItem = e.target.parentElement.parentElement;
fetch(
`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${mealItem.dataset.id}`
)
.then((res) => res.json())
.then((data) => {
mealRecipeModal(data.meals);
});
} else if (e.target.value == "favour") {
let mealItem = e.target.parentElement.parentElement;
fetch(
`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${mealItem.dataset.id}`
)
.then(function (res) {
return res.json();
})
.then((data) => {
window.localStorage.setItem(
mealItem.dataset.id,
JSON.stringify(data.meals)
);
});
}
}
function mealRecipeModal(meal) {
const destination = meal[0].strSource;
window.open(`${destination}`);
}
window.onload = function () {
const mealListEl = document.getElementById("list-Items-container");
function handleSubmitForm(e) {
e.preventDefault();
let input = document.querySelector("input");
findFood(url + input.value, mealListEl);
input.value = "";
}
document.querySelector("form").addEventListener("submit", handleSubmitForm);
mealList.addEventListener("click", handleGetDetailsOrAddToFavorites);
};
favorite.js:
var urlId = "https://www.themealdb.com/api/json/v1/1/lookup.php?i="; //search by id
function handleRemoveFavorites(e) {
e.preventDefault();
console.log(e.target.value);
}
function findFoodFavorite(address, mealListFavoritesEl) {
var html1 = "";
fetch(address)
.then((res) => res.json())
.then((data) => {
if (data.meals) {
data.meals.forEach((meal) => {
html1 += `<div class="food-card" data-id="${meal.idMeal}">
<div class="food-card-image">
<img src="${meal.strMealThumb}" alt="${meal.strMeal}" >
</div>
<div class="food-card-info">
<h3>${meal.strMeal}</h3>
</div>
<div class="food-card-features">
<button id="favorites" value="defavour" >Remove</button>
<button id="get-details" value="details" >Details</button>
</div>
</div>`;
});
}
mealListFavoritesEl.innerHTML += html1;
});
}
window.onload = function () {
const mealListFavoritesEl = document.getElementById(
"list-Items-container-favorites"
);
function renderFavorites() {
const urlArray = [];
for (var i = 0; i < localStorage.length; i++) {
urlArray.push(Object.entries(localStorage)[i][0]);
}
urlArray.forEach((id) => findFoodFavorite(urlId + id, mealListFavoritesEl));
}
mealListFavoritesEl.addEventListener("click", handleRemoveFavorites);
renderFavorites();
};
home.html:
</head>
<body>
<header>
<div class="topnav">
<a class="active" href="home.html">Home</a>
Favorites
Details
About
</div>
</header>
<div class="Heading">
<h1>The FoodAPP</h1>
</div>
<div class="form-container">
<form action="submit" method="get">
<input type="text" id="inputText" placeholder="Enter dish...">
<button id="btn" type="submit">Find</button>
</form>
</div>
<div id="list-Items-container">
</div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
favorite.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="styles.css" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=M+PLUS+2:wght#200&family=Poppins:ital,wght#0,100;1,200&display=swap"
rel="stylesheet"
/>
<title>Meals App | Favaorites</title>
</head>
<body>
<header>
<div class="topnav">
<a class="active" href="home.html">Home</a>
Favorites
Details
About
</div>
</header>
<div id="list-Items-container-favorites">
</div>
<script type="text/javascript" src="favorite.js"></script>
</body>
</html>

Making a pop up on text highlight

I've been looking around this morning and nothing seems to be working I am trying to make something like notion has where when you highlight text in a text area a pop-up will show where you can edit text. I can sort out the functionality of the buttons in the box but I don't know what I should use to trigger a sort of on highlight event to pop up this box in a position relative to the highlight. I linked the notion reference my site and my HTML code so far.
Notion Refrence
My Current Site
<!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>Study App</title>
<link rel="stylesheet" href="study.css" />
<link href="https://unpkg.com/boxicons#2.0.7/css/boxicons.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" charset="utf-8"></script>
</head>
<body>
<script src="study.js"></script>
<div class="dropdown">
<nav><label for="touch"><span>Settings</span></label>
<input type="checkbox" id="touch"/>
<ul class="slide">
<li><a><div class="dark"><button onclick="myFunction()">
<input class="toggle" type="checkbox"/></button></div></a></li>
<li></li>
</ul>
</nav>
</div>
</div>
<div class="arrowdown">
<input type="checkbox" id="myCheckbox" onchange="rotateElem()" checked><i class="fas fa-angle-right dropdown"></i></button>
<div class="pages">
Add Page</div>
</div>
</div>
<script type="text/javascript">
var checkBox = document.getElementById("myCheckbox");
function rotateElem() {
if (checkBox.checked == false)
{
document.querySelector('.fas.fa-angle-right.dropdown').style.transform = 'rotate(90deg)';
}
else {
document.querySelector('.fas.fa-angle-right.dropdown').style.transform= 'rotate(0deg)';
}
}
</script>
<div class="tabs"></div>
<div class="sidebar">
<div class="sidebar-top">
<h1><span class="study">Study</span><span class="app">App</span></h1>
</div>
<div class="side-title">
<textarea class="longInput" spellcheck="true" placeholder="Untitled" cols="5" rows="1"></textarea>
</div>
<div class="title">
<textarea class="longInput" spellcheck="true" placeholder="Untitled" cols="30" rows="1"></textarea>
</div>
<div class="textbox">
<textarea class="shortInput" spellcheck="true" placeholder="Start typing..." cols="30" rows="10"></textarea>
</div>
<script>
let value = ''
const elements = document.querySelectorAll('.longInput')
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('change', handleChange)
elements[i].addEventListener('keyup', handleChange)
}
function handleChange(e) {
value = e.target.value
for (let i = 0; i < elements.length; i++) {
elements[i].value = value
}
}
</script>
<script type="text/javascript">
$('.pages').hide();
$(document).ready(function(){
$('#myCheckbox').click(function(){
$('.pages').slideToggle();
});
});
</script>
<script src="study.js"></script>
</body>
</html>
Have a look at this code
if (!window.x) {
x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
var pageX;
var pageY;
$(document).ready(function() {
$(document).bind("mouseup", function() {
var selectedText = x.Selector.getSelected();
if(selectedText != ''){
$('ul.tools').css({
'left': pageX + 5,
'top' : pageY - 55
}).fadeIn(200);
} else {
$('ul.tools').fadeOut(200);
}
});
$(document).on("mousedown", function(e){
pageX = e.pageX;
pageY = e.pageY;
});
});
Find here a working demo!
Codepen.io

How can I change the display a message depending on which number the user has selected?

I want when somebody input a number lower than 4.2, my app shows message as result, but i can't make it happen.
I already tried with return.
JS code
let resultEl = document.getElementById("results")
let numberEl = document.getElementById("number__select")
let message = "mAs: 0.5 y kV: 1.0"
function calculate() {
if (numberEl <= 4.2) {
resultEl.textContent = message;
} else {
resultEl.textContent = "error"
}
}
HTML code
<!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="styleRx.css"/>
<script src="Rxappjs.js"></script>
<title>HVDN Rx app</title>
</head>
<body>
<div class="container">
<header>
<h1>Valoraciones de Rx</h1>
</header>
<div class="box">
<form action="">
<div class="values">
<label for="peso" id="peso__label">Peso</label>
<input class="text__input" type="number" step="0.1" id="number__select" placeholder="Peso"
min="0" required>
</div>
<button id="calcular" onclick="calculate()">Calcular</button>
</form>
<p id="results"></p>
</div>
</div>
</body>
</html>
You have the variable numberEl set to an html element and therefor it will never be less than or equal too 4.2. Try to get the value of that element instead:
let resultEl = document.getElementById("results")
let numberEl = document.getElementById("number__select")
let message = "mAs: 0.5 y kV: 1.0"
function calculate() {
if (numberEl.value <= 4.2) {
resultEl.textContent = message;
} else {
resultEl.textContent = "error"
}
}

Categories

Resources