Make each textarea unique to its own button - javascript

I'm trying to create an online commenting system where each user can comment on a post and I want a popup text area to be unique to its own button.
Each element is meant to open a text field where a user is to input text to be posted (say in reply to a preceding post or comment).
There are three buttons (representing each user) which when clicked is intended to display a text field specific to the button (or user).
The problem:
After clicking a button, a modal will popup, try typing some text into the field and close the field, without clearing the text in the field, then open another field by clicking on another button. You'll notice that the text typed into one textarea will also be visible in another instance when you click on another button.
What I'm trying to achieve is to make a textarea unique to its direct button instead of a text constantly showing for all buttons clicked.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./style.css" />
<title>multi textarea</title>
</head>
<body>
<button>Open a textarea</button>
<button>Open a textarea</button>
<button>Open a textarea</button>
<div class="textarea_modal_backdrop">
<textarea name="" id="" cols="80" rows="20"></textarea>
</div>
</body>
</html>
<script src="./script.js"></script>
CSS:
.textarea_modal_backdrop{
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: #444c;
display: grid;
place-items: center;
visibility: hidden;
opacity: 0;
}
.textarea_modal_backdrop.textarea_modal_backdrop_active{
visibility: visible;
opacity: 1;
}
JS:
const allButtonElms = document.getElementsByTagName('button');
const modalBackdrop = document.querySelector('.textarea_modal_backdrop');
for (var i = 0; i < allButtonElms.length; i+=1) {
allButtonElms[i].onclick = () => {
modalBackdrop.classList.add('textarea_modal_backdrop_active')
}
}
document.addEventListener('click', (event) => {
if (event.target.matches('.textarea_modal_backdrop')) {
modalBackdrop.classList.remove('textarea_modal_backdrop_active')
}
})
I'll be grateful if everyone can join in sharing their ideas on how this issue can be solved.
Thank you all!

one way can be to
stored textarea values in an array of value
add a dataset on button to identify value link to textarea
when textarea is closed save data in values array
const values = [];
var currentButton = 0;
const allButtonElms = document.getElementsByTagName('button');
const modalBackdrop = document.querySelector('.textarea_modal_backdrop');
const textarea = document.querySelector('textarea');
for (var i = 0; i < allButtonElms.length; i+=1) {
allButtonElms[i].onclick = (e) => {
var target = e.target || e.srcElement;
currentButton = target.dataset.number;
if (!values[currentButton]) {
values[currentButton] = "";
}
textarea.value = values[currentButton];
modalBackdrop.classList.add('textarea_modal_backdrop_active')
}
}
document.addEventListener('click', (event) => {
if (event.target.matches('.textarea_modal_backdrop')) {
values[currentButton] = textarea.value;
modalBackdrop.classList.remove('textarea_modal_backdrop_active')
}
})
.textarea_modal_backdrop{
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: #444c;
display: grid;
place-items: center;
visibility: hidden;
opacity: 0;
}
.textarea_modal_backdrop.textarea_modal_backdrop_active{
visibility: visible;
opacity: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./style.css" />
<title>multi textarea</title>
</head>
<body>
<button data-number="0">Open a textarea</button>
<button data-number="1">Open a textarea</button>
<button data-number="2">Open a textarea</button>
<div class="textarea_modal_backdrop">
<textarea name="" id="" cols="80" rows="20"></textarea>
</div>
</body>
</html>
<script src="./script.js"></script>

Related

How to make a tooltip with the same look and feel as when we add "title" attribute to an element?

I am trying to replicate the look and feel of the tooltip when we add the "title" attribute to an element.
Tooltip should be hovarable
Tooltip should be dismissable by pressing the Esc key
Currently, my custom tooltip is not hoverable. Also the look and feel is not matched with - https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_global_title
Any help is really appreciated and thanks in advance
const tooltipTrigger = document.querySelector(".tooltip-trigger");
const tooltipText = document.querySelector(".tooltip-text");
tooltipTrigger.addEventListener("mouseenter", showTooltip);
tooltipTrigger.addEventListener("mouseleave", hideTooltip);
tooltipText.addEventListener("keydown", dismissTooltip);
function showTooltip() {
tooltipText.style.visibility = "visible";
}
function hideTooltip() {
tooltipText.style.visibility = "hidden";
}
function dismissTooltip(event) {
if (event.keyCode === 27) {
tooltipText.style.visibility = "hidden";
}
}
.tooltip-text {
visibility: hidden;
position: absolute;
background-color: #000;
color: #fff;
padding: 4px;
z-index: 1;
}
.tooltip-trigger{
cursor: pointer;
}
.tooltip-trigger:hover .tooltip-text {
visibility: visible;
}
<!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" />
<title>Tooltip</title>
</head>
<body>
<span class="tooltip-trigger" aria-describedby="tooltip-text"
>Hover over me</span
>
<div id="tooltip-text" class="tooltip-text" role="tooltip">
This is the tooltip text
</div>
<script src="script.js"></script>
</body>
</html>
const tooltipTrigger = document.querySelector(".tooltip-trigger");
const tooltipText = document.querySelector(".tooltip-text");
let timeout = null;
tooltipTrigger.addEventListener("mouseenter", showTooltip);
tooltipTrigger.addEventListener("mouseleave", hideTooltip);
window.addEventListener("keydown", dismissTooltip);
function showTooltip(event) {
timeout = setTimeout(() => {
tooltipText.style.visibility = "visible";
tooltipText.style.left = `${event.clientX}px`
tooltipText.style.top = `${event.clientY}px`
}, 1000)
}
function hideTooltip() {
clearTimeout(timeout);
timeout = null;
tooltipText.style.visibility = "hidden";
}
function dismissTooltip(event) {
if (event.key === 'Escape') {
tooltipText.style.visibility = "hidden";
}
}
.tooltip-text {
visibility: hidden;
position: absolute;
background-color: #000;
color: #fff;
padding: 4px;
z-index: 1;
}
.tooltip-trigger {
cursor: pointer;
}
<!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" />
<title>Tooltip</title>
</head>
<body>
<span class="tooltip-trigger" aria-describedby="tooltip-text">Hover over me</span
>
<div id="tooltip-text" class="tooltip-text" role="tooltip">
This is the tooltip text
</div>
<script src="script.js"></script>
</body>
</html>
The ultimate answer is in fact, you can't.
You can't replicate the exact behavior of a tooltip generated by a title attribute, simply because their appearance and behavior can be dramatically different across browsers, devices and OS.
You can certainly try to approach very close what it looks like on a particular browser/device/OS, but won't probably be able to replicate exactly everything everywhere. Note that doing user agent detection to finetune is most often a bad idea.

Hiding classes by clicking outside

I made a script that when I click on the container it hides a list. However, what I have been trying to do is that the list should hide when clicking outside the container and not inside. I have been looking for answers but nothing really worked for me as I use classes. Does someone know a solution?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width" />
<title>Hiding the list</title>
</head>
<body>
<h1>Hiding the list</h1>
<div class="list">Hide the list by clicking outside
<li>Text1</li>
<li>Text2</li>
<li>Text3</li>
</div>
<div class="list">Hide the list by clicking outside
<li>Text1</li>
<li>Text2</li>
<li>Text3</li>
</div>
</body>
</html>
<style>
.list {
width: 50%;
height: 100%;
background-color: #f2f2f2;
}
li {
}
</style>
<script>
function hide_list() {
var children = this.children;
for (let i = 0; i < children.length; i++) {
children[i].style.display = "none";
}
}
document.querySelectorAll(".list").forEach(function (elem) {
elem.addEventListener("click", hide_list);
});
</script>

Cycle Through Web Pages with Start and Stop Buttons

I have a few URLs that each show the status of some industrial equipment. I'm trying to create an HTML/Javascript solution that, on load, cycles through each of the websites at a set interval, with two buttons to stop the cycle (to take a closer look at something) and restart the cycle (either from the beginning or where it left off, I'm not picky). I'm REALLY rusty, but I got what I think is a good start. Unfortunately, it doesn't work. Here are the CSS and HTML:
html,
body {
height: 100vh;
width: 100vw;
}
#btStart {
position: absolute;
width: 50px;
height: 40px;
left: 20px;
top: 50px;
}
#btStop {
position: absolute;
width: 50px;
height: 40px;
left: 20px;
top: 120px;
}
#infoFrame {
width: 100%;
height: 100%;
}
.holder {
width: 100%;
height: 100%;
position: relative;
}
<!DOCTYPE HTML>
<html>
<head>
<title>Info Cycle</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="main.css" rel="stylesheet">
</head>
<body>
<div class="holder">
<iframe src="" id="infoFrame" frameborder="0" allowfullscreen>
<script type="text/javascript">
var urlArray = ['url1.com',
'url2.com',
'url3.com',
'url4.com',
'url5.com'];
var count = 0;
var i = document.getElementById('infoFrame');
var u = document.getElementById('url');
var timer = setInterval(cycleTimer, 5000);
function nextUrl() {
url = urlArray[++count];
count = (count >= urlArray.length - 1)? -1 : count;
return url;
}
function cycleTimer() {
u.innerHTML = '';
i.src = nextUrl();
i.onload = function(){
u.innerHTML = i.src;
}
}
</script>
</iframe>
<button type="button" id="btStart" onclick="var timer = setInterval(cycleTimer, 5000);">Start</button>
<button type="button" id="btStop" onclick="clearInterval(timer)";>Stop</button>
</div>
</body>
<footer>
</footer>
</html>
Before I added the buttons it would load, then 5 seconds later it would cycle correctly, and so on. Now it only shows the buttons. Looking at the requests, I believe what's happening in my CSS and structure is trash, and it's loading the appropriate URL, but not displaying. I should add, prior to the buttons I only had the iframe with the script in it as a proof of concept. I div'd it, added the stylesheet, and added the buttons, and now here we are.
This may be a rookie mistake, or something more complicated. I haven't done development in a long time, and I'm just trying to solve a little problem at work. If you could spare a minute, I'd be happy to know how to fix this, and also any feedback on what I could be doing better. I'd love to get back into doing more of this, so I'm interested to learn anything the community can share. I've searched the site and the internet, and I've found a couple of related solutions but nothing for this in particular.
Thanks!
EDIT:
In case it helps, below is the HTML before the buttons and stylesheet, which worked (it rotated between webpages every 7 seconds):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Info Cycle</title>
</head>
<body>
<iframe id="frame" src=""
style="
position: fixed;
top: 0px;
bottom: 0px;
right: 0px;
width: 100%;
border: none;
margin: 0;
padding: 0;
overflow: hidden;
z-index: 999999;
height: 100%;
"></iframe>
<script type="text/javascript">
var urlArray = ['url1.com',
'url2.com',
'url3.com',
'url4.com',
'url5.com'];
var count = 0;
var i = document.getElementById('frame');
var u = document.getElementById('url');
var timer = setInterval(cycleTimer, 7000);
function nextUrl() {
url = urlArray[++count];
count = (count >= urlArray.length - 1)? -1 : count;
return url;
}
function cycleTimer() {
u.innerHTML = '';
i.src = nextUrl();
i.onload = function(){
u.innerHTML = i.src;
}
}
</script>
</body>
</html>
The iframe style was something I found in an old file I'd written (probably copied and pasted from Stack Overflow to just get a thing to work).
The problem here is having the script inside the iframe. If you move your script out of the iframe and put it under body or head then it will work.
<!DOCTYPE HTML>
<html>
<head>
<title>Info Cycle</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="main.css" rel="stylesheet">
<script type="text/javascript">
var urlArray = ['url1.com',
'url2.com',
'url3.com',
'url4.com',
'url5.com'];
var count = 0;
var timer = setInterval(cycleTimer, 5000);
function nextUrl() {
url = urlArray[++count];
count = (count >= urlArray.length - 1) ? -1 : count;
return url;
}
function cycleTimer() {
var i = document.getElementById('infoFrame');
var u = document.getElementById('url');
u.innerHTML = '';
i.src = nextUrl();
i.onload = function () {
u.innerHTML = i.src;
}
}
</script>
</head>
<body>
<div class="holder">
<iframe src="" id="infoFrame" frameborder="0" allowfullscreen>
</iframe>
<button type="button" id="btStart" onclick="var timer = setInterval(cycleTimer, 5000);">Start</button>
<button type="button" id="btStop" onclick="clearInterval(timer)" ;>Stop</button>
</div>
</body>
<footer>
</footer>
</html>

How can I have 2 actions within one form, one button?

I have a html form and one 'submit' button. I have two tabs that I want to do different things. One tab when submitting should go to one link, whereas the other tab should take the form to another link.
Here is my fiddle to show what I am working with :
https://jsfiddle.net/4s8qevz7/
I have tried putting in actions to go to for, (as of right now) generic links. But no luck.
<form style="margin-top:40px;" id="search-box" action="">
<div class="search-tab" data-search-type="catalog" action="http://catalog.com/" onClick="changePlaceholder(this)">Catalog </div>
<div class="search-tab selected" data-search-type="website" action="https://www.google.com/"onClick="changePlaceholder(this)">Website </div>
My expected results would be depending on the active tab, the form would respect that when the go button is clicked.
1) call preventDefault() in the form submit method
2) get active tab from event.target
3) call form.submit with the correct options based on the active tab.
<!DOCTYPE html>
<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">
<title>Document</title>
<style>
.tab {
overflow: hidden;
/* Style the buttons that are used to open the tab content */
.tab button {
background-color: #f1f1f1;
float: left;
border: solid 1px #ccc;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current tablink class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
#search-text-form{
margin-top: 2rem;
}
#current-action-section{
margin-top: 2rem;
}
</style>
<script>
function openTab(evt, tabName) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the button that opened the tab
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
</script>
</head>
<body>
<section id="search-bar">
<div class="tab">
<button id="openByDefault" class="tablinks" onclick="openTab(event, 'Catalog')" data-action="http://catalog.com">Catalog</button>
<button class="tablinks" onclick="openTab(event, 'Website')" data-action="https://www.google.com">Website</button>
</div>
<div id="Catalog" class="tabcontent">
<h3>Catalog</h3>
<p>Catalog</p>
</div>
<div id="Website" class="tabcontent">
<h3>Website</h3>
<p>Website</p>
</div>
<form id="search-text-form">
<input type="text" id="search-text" placeholder="Search Website"><button id="go">Submit</button>
</form>
<script>
const form = document.getElementById('search-text-form');
form.onsubmit = e => {
e.preventDefault();
const activeTab = document.getElementsByClassName('tablinks active')[0];
const {action } = activeTab.dataset;
console.log(action);
document.getElementById('current-action').innerHTML = `Current Action: ${action}`;
// when you're ready, call whatever api is usually called in the submit function
}
document.getElementById("openByDefault").click();
</script>
</section>
<section id="current-action-section">
<h3 id="current-action"></h3>
</section>
<script>
var emailAddress = "jimmyleespann#outlook.com";
//email;
var text = "https://docs.google.com/forms/d/e/1FAIpQLSdFDFGDFVDGGjdfgdfgdx8P4DOw/viewform?usp=pp_url&entry.745541291="+room+"&entry.1045781291="+rr+"&entry.1065046570=4&entry.1166974658="+hr+"&entry.839337160="+spO2+"&entry.103735076=&entry.515842896="+e1Name+"&entry.631828469="+e1Reps+"&entry.1814472044="+e2Name+"&entry.905508655="+e2Reps+"&entry.1234390406="+isVol+"&entry.197252120="+education+"&entry.1748983288="+notes; var message = 'Dear ' + patientName + '\n\n' + "Thank you for submitting.\n\nHere is an autofill link: " + text; var subject = 'Submission Confirmation'; GmailApp.sendEmail(emailAddress, subject, message);
</script>
</body>
</html>
Updated JSFiddle code that I couldn't get to show up for OP:
<!DOCTYPE html>
<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">
<title>Document</title>
<script>
const state = {
targetUrl: 'https://www.google.com' // because this is the default selected tab
}
function setTargetUrl(url){
state.targetUrl = url;
}
function changePlaceholder(div) {
const searchTextEl = document.getElementById("search-text")
searchTextEl.placeholder = `Search ${div.innerHTML.trim()}`;
setTargetUrl(div.dataset.action);
}
function doSubmit(){
console.log('submitForm', state);
}
</script>
</head>
<body>
<form style="margin-top:40px;" id="search-box" onsubmit="submitForm">
<div
class="search-tab"
data-search-type="catalog"
data-action="http://catalog.com/"
onclick="changePlaceholder(this)">
Catalog
</div>
<div
class="search-tab selected"
data-search-type="website"
data-action="https://www.google.com/"
onclick="changePlaceholder(this)">
Website
</div>
<script>
</script>
<a href="t$003f/" target="_blank" style="text-decoration:none">
<div class="search-tab-link"> Login </div>
</a>
<div class="search-tab-content">
<div class="search-bar">
<input type="text" id="search-text" placeholder="Search Website" name="q">
<span id="search-text-icon" onclick="doSubmit()" style="cursor:pointer;">
<img
alt="go"
title="Search"
src="img/search.png"
style="height:1.2rem;"
>
</span>
</div>
<div id="search-old-catalog">
<a href="http://.com/" target="_blank">
Old Catalog
</a>
</div>
</form>
</body>
</html>
I couldn't get your jsfiddle to work, but here's an example of "2 actions within one form, one button." If the checkbox is checked, the action goes to bing.com, otherwise it goes to Wikipedia. Your if statement can use currentTarget as Dov Rine suggested, instead of a checkbox to dynamically change the form action.
function ActionSelect() {
if (document.getElementById('bing').checked) {
document.getElementsByTagName('form')[0]['action'] = 'https://bing.com';
}
}
<form style="margin:40px 50px;" action="https://www.wikipedia.org">
Choose your form action:<br/>
<input type="checkbox" id="bing"> Bing
<p>
<button type="submit" onclick="ActionSelect()">Submit</button>
</p>
</form>

Trying to learn JavaScript and nothing is working on my page

The Goal:
A button which displays an alert with "Hello world!" and some radio buttons which display a warning when the third one is selected.
The HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>hello world</title>
<link rel="stylesheet" href="style.css">
<meta name="description" content="">
</head>
<body>
<div id="main">
<p>text</p>
link
<button>button</button>
<form>
<fieldset>
<legend>Legend</legend>
<label for="radio1">Option 1</label>
<input type="radio" name="radio-buttons" value="option-1" id="radio1"/>
<label for="radio2">Option 2</label>
<input type="radio" name="radio-buttons" value="option-2" id="radio2"/>
<label for="radio3">Option 3</label>
<input type="radio" name="radio-buttons" value="option-3" id="radio3"/>
<p id="warn">No, pick another one.</p>
</fieldset>
</form>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
The CSS:
Most of this really doesn't matter. The important thing is #warn which is supposed to only show when the third option is selected.
a,
button {
display: block;
margin-bottom: 1em;
}
fieldset {
width: 245px;
height: 75px;
background: #dfe;
position: relative;
}
legend {
background: white;
}
#warn {
display: none;
background: #d33;
color: #fff;
font-family: helvetica;
padding: 10px 15px 10px;
margin: 0 -12px;
position: absolute;
top: 52px;
width: 239px;
}
The JavaScript:
I think the problem is in my event handlers, but I don't know for sure. BTW yes I know there's some extraneous stuff here; like I said I'm just screwing around.
// variables
var p = document.getElementsByTagName("p");
var a = document.getElementsByTagName("a");
var button = document.getElementsByTagName("button");
var fieldset = document.getElementsByTagName("fieldset");
var radio1 = document.getElementById("radio1");
var radio2 = document.getElementById("radio2");
var radio3 = document.getElementById("radio3");
var warn = document.getElementById("warn");
// functions
function prepareEventHandlers() {
button.onclick = function() {
alert("Hello world!")
};
radio3.onfocus = function() {
warn.setAttribute("display","inherit")
}
}
// window onload
window.onload = function() {
prepareEventHandlers();
}
Notice the name of the function:
document.getElementsByTagName()
// ^ That's an "s", so the function
// returns an array of elements.
button.onclick won't work because button is an array of buttons (I would name it buttons), so you have to iterate:
for (var i = 0; i < button.length; i++) {
button[i].onclick = ...
}
Since you have only one button, I would just give it an id and use document.getElementById() to fetch the single button and attach the onclick handler.
First, go fo button like this,
var button = document.getElementsByTagName("button")[0];
getElementsByTagName returns the array of matched elements...
For radio button
Try this
display is a CSS property. Using display as an HTML attribute will not hide or show content. You have to access CSS properties using style attribute. like,
radio3.onclick = function() {
warn.style.display = "inherit";
}

Categories

Resources