Connect generated divs by a dynamic line - javascript

I have a button that generates a div, and inside of that div, there is another button to generate another div, either a "method" div, or an "instance variable" div.
When one of those is generated from that main div, I want a line to be pointing between them. The divs are draggable, so I want the line to move when the divs move also.
I attempted to use leaderline.js to generate a line when they are created using the div ids, but it did not show up, and I tried to read more about it, but the documentation didn't fix my issue, as I tried what it said by using this:
new LeaderLine(
document.getElementById('start'),
document.getElementById('end')
);
Replacing the ids with my actual ids when the div was generated, but it didn't work. Any help would be appreciated.
Code:
var generatedCode = "";
var classNameCode = {};
var classVariables = {};
var variableName = "";
var amtVars = 0;
document.getElementById("create-box").addEventListener("click", function() {
amtVars = 0;
var methodCount = 0;
let box = document.createElement("div");
box.classList.add("box");
let title = document.createElement("h2");
title.innerHTML = "Class";
box.appendChild(title);
let classTitle = document.createElement('input');
classTitle.classList.add('class-name-form');
let classTitleBtn = document.createElement('button');
classTitleBtn.innerText = "Set Class Name";
classTitleBtn.classList.add('class-name-btn');
box.appendChild(classTitle);
box.appendChild(classTitleBtn);
document.getElementById("box-container").appendChild(box);
let createSubclassButton = document.createElement("button");
createSubclassButton.innerHTML = "Add Method";
box.appendChild(createSubclassButton);
let createInstanceVariable = document.createElement('button');
createInstanceVariable.classList.add('add-variable');
createInstanceVariable.innerHTML = "Add instance variable";
box.appendChild(createInstanceVariable);
// Enable resizing and dragging
box.addEventListener("mousedown", startDrag);
box.addEventListener("mousemove", drag);
box.addEventListener("mouseup", endDrag);
box.addEventListener("mouseleave", endDrag);
let offset = [0, 0];
let isDown = false;
function startDrag(e) {
isDown = true;
offset = [
this.offsetLeft - e.clientX,
this.offsetTop - e.clientY
];
}
function drag(e) {
if (!isDown) return;
e.preventDefault();
this.style.left = (e.clientX + offset[0]) + 'px';
this.style.top = (e.clientY + offset[1]) + 'px';
}
function endDrag(e) {
isDown = false;
}
createInstanceVariable.addEventListener('click', function() {
let instanceVar = document.createElement('div');
instanceVar.classList.add('instance-var');
let instanceTitle = document.createElement('h2');
instanceTitle.innerText = `Variable`;
instanceVar.append(instanceTitle);
let varName = document.createElement('input');
varName.classList.add('varName-form');
varName.placeholder = "Set variable name";
instanceVar.append(varName);
let varNameBtn = document.createElement('button');
varNameBtn.innerText = "Set Variable Name";
varNameBtn.classList.add('var-name-btn');
instanceVar.append(varNameBtn);
let varType = document.createElement('input');
varType.placeholder = 'Specify variable type';
varType.classList.add('variable-type-form');
let varTypeBtn = document.createElement('button');
varTypeBtn.innerText = "Set variable type";
varTypeBtn.classList.add('method-type-btn');
instanceVar.appendChild(varType);
instanceVar.appendChild(varTypeBtn);
document.getElementById("box-container").appendChild(instanceVar);
instanceVar.style.left = box.offsetLeft + box.offsetWidth + 10 + 'px';
instanceVar.style.top = box.offsetTop + 'px';
instanceVar.addEventListener("mousedown", startDrag);
instanceVar.addEventListener("mousemove", drag);
instanceVar.addEventListener("mouseup", endDrag);
instanceVar.addEventListener("mouseleave", endDrag);
varNameBtn.addEventListener('click', function() {
variableName = varName.value;
instanceTitle.innerText = `Variable ${variableName}`;
});
varTypeBtn.addEventListener('click', function() {
if(amtVars === 0){
classNameCode[classTitle.value] += `\n\tprivate: \n\t\t${varType.value} ${variableName};\n`;
amtVars++;
} else{
classNameCode[classTitle.value] += `\n\t\t${varType.value} ${variableName};\n`;
}
});
});
createSubclassButton.addEventListener("click", function() {
let subBox = document.createElement("div");
subBox.classList.add("subbox");
let subTitle = document.createElement("h2");
subTitle.innerText = `Method`;
subBox.append(subTitle);
let methodTitle = document.createElement('input');
methodTitle.classList.add('method-name-form');
methodTitle.placeholder = 'Set method name'
let methodTitleBtn = document.createElement('button');
methodTitleBtn.innerText = "Set Method Name";
methodTitleBtn.classList.add('method-name-btn');
subBox.appendChild(methodTitle);
subBox.appendChild(methodTitleBtn);
let returnType = document.createElement('input');
returnType.placeholder = 'Specify return type';
returnType.classList.add('method-return-type-form');
let returnTypeBtn = document.createElement('button');
returnTypeBtn.innerText = "Set return type";
returnTypeBtn.classList.add('method-return-type-btn');
subBox.appendChild(returnType);
subBox.appendChild(returnTypeBtn);
document.getElementById("box-container").appendChild(subBox);
subBox.style.left = box.offsetLeft + box.offsetWidth + 10 + 'px';
subBox.style.top = box.offsetTop + 'px';
subBox.addEventListener("mousedown", startDrag);
subBox.addEventListener("mousemove", drag);
subBox.addEventListener("mouseup", endDrag);
subBox.addEventListener("mouseleave", endDrag);
methodTitleBtn.addEventListener('click', function() {
console.log(methodTitle.value);
subTitle.innerText = `Method ${methodTitle.value}`;
});
returnTypeBtn.addEventListener('click', function() {
console.log(returnType.value);
if (methodCount === 0) {
classNameCode[classTitle.value] += `\tpublic:\n\t\t${returnType.value} ${methodTitle.value}() {\n\n\t\t}`;
methodCount++;
amtVars = 0;
} else {
classNameCode[classTitle.value] += `\n\t\t${returnType.value} ${methodTitle.value}() {\n\n\t\t}`;
amtVars = 0;
}
});
});
classTitleBtn.addEventListener("click", function() {
console.log(classTitle.value);
// generatedCode = `class ${classTitle.value} {\n\t`
title.innerHTML = `Class ${classTitle.value}`;
classNameCode[classTitle.value] = `\nclass ${classTitle.value} {\n`
});
});
// MODAL FOR CODE GENERATION
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var modalContent = document.querySelector('.modal-content');
btn.onclick = function() {
modal.style.display = "block";
modalContent.innerText = "";
console.log(classNameCode);
if (Object.keys(classNameCode).length === 0) {
modalContent.innerText = "No Code Yet";
}
for (var key in classNameCode) {
var codeToAppend = `${classNameCode[key]} \n}`;
console.log(codeToAppend);
modalContent.innerText += codeToAppend;
}
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
body {
background-size: 40px 40px;
background-image: radial-gradient(circle, #000000 1px, rgba(0, 0, 0, 0) 1px);
background-color: darkgray;
}
#create-box {
padding: 10px 20px;
background-color: #4CAF50;
border-radius: 5px;
border: none;
color: white;
}
#create-box:hover{
background-color: #5dc861;
cursor: pointer;
}
#create-box:active{
cursor:pointer
}
.box {
position: absolute;
width: 250px;
height: 250px;
background-color: #f1f1f1;
border: 1px solid #d3d3d3;
border-radius: 5px;
resize: both;
overflow: auto;
z-index: 1;
text-align: center;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.box h2 {
margin: 0;
padding: 10px;
}
.subbox {
width: 200px;
height: 200px;
background-color: #f1f1f1;
border: 1px solid #d3d3d3;
position: absolute;
z-index: 1;
border-radius: 5px;
text-align: center;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
white-space: pre;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
#myBtn{
padding: 10px 20px;
background-color: #4CAF50;
border-radius: 5px;
border: none;
color: white;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
#myBtn:hover{
background-color: #5dc861;
cursor: pointer;
}
#myBtn:active{
cursor:pointer
}
#buttons{
text-align: center;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.class-name-form{
border-radius: 5px;
border: 1px solid black;
}
button{
border-radius: 5px;
border: none;
background-color: rgb(170, 207, 207);
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
button:hover{
cursor: pointer;
background-color: rgb(198, 224, 224);
}
button:active{
cursor: pointer;
}
.instance-var{
width: 200px;
height: 200px;
background-color: #f1f1f1;
border: 1px solid #d3d3d3;
position: absolute;
z-index: 1;
border-radius: 5px;
text-align: center;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
<!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="./static/styles.css">
<title>Program Visualizer And Generator</title>
</head>
<body>
<div id="buttons">
<button id="create-box">Create Class</button>
<button id="myBtn">View Code (C++)</button>
</div>
<div id="box-container"></div>
<div id="myModal" class="modal">
<div class="modal-content">
<code></code>
</div>
</div>
<script src="./functionality/main.js"></script>
</body>
</html>

Related

I have a button and I only want it to be pressed with a left click not enter key

I have a button in my site which is a simple aim trainer and you should click the button with left click. Everything works like a charm but if you click the button and hold it, then you hold enter, you can click 303 times in 10secs and that is cheating. I want it to only be pressed with left click. Explain your answer please.
Link to the site: https://mfa-aim-trainer.netlify.app
var b = document.querySelector("button");
var score = document.getElementById('score');
var counter = 0;
var btn = document.getElementById("button");
var tensec = document.getElementById("10sec");
var pxs = document.getElementsByClassName('div');
var scr = document.getElementById("scr");
var mis = document.getElementById("mis");
var htm = document.getElementById("htm");
var missc = 0;
var height1 = 100;
var width1 = 100;
var theLeftSide = document.getElementById("theLeftSide");
var resetbtn = document.getElementById("reset");
var vr = document.getElementById("vr");
var hit = 1080;
var fontsize = 25;
var ulcls = document.getElementsByClassName("theul");
var ul = document.getElementById('10sec');
var best = document.getElementById("best");
var cntrspn = document.getElementsByClassName("cntrspn");
var lists = document.getElementsByClassName("lists");
b.addEventListener("click", change);
b.addEventListener("click", plus);
htm.addEventListener("click", miss);
pxs[0].addEventListener("click", plussize);
pxs[1].addEventListener("click", minesize);
theLeftSide.addEventListener("click", leftsclick);
b.addEventListener("click", misscmines);
resetbtn.addEventListener("click", resetall);
function plussize() {
height1 += 10;
width1 += 10;
missc++
missc + 1
missc--
fontsize += 3;
b.style.fontSize = fontsize + "px";
b.style.height = height1 + "px";
b.style.width = width1 + "px";
missc - 1;
}
function minesize() {
height1 -= 10;
width1 -= 10;
missc++
missc + 1
missc--
fontsize -= 3;
b.style.fontSize = fontsize + "px";
b.style.height = height1 + "px";
b.style.width = width1 + "px";
missc - 1;
}
function miss() {
missc++
mis.innerHTML = missc - counter;
}
setInterval(function() {
var misc = missc - counter;
ul.style.height = window.offsetheight;
var currscr = counter;
for (var i = 0; i < cntrspn.length; i += 1) {
if (parseInt(scr.textContent) > parseInt(best.textContent)) {
best.textContent = scr.textContent;
} else {
console.log("no new best");
}
}
mis.textContent = missc - counter;
ul.innerHTML += '<li class="lists">' + '<span class="cntrspn">' + counter + '</span>' + "-" + misc + '</li>';
missc = 0;
misc = 0;
counter = 0;
scr.textContent = counter;
mis.textContent = missc;
}, 10000);
function change() {
var i = Math.floor(Math.random() * 1500) + 1;
var j = Math.floor(Math.random() * 250) + 1;
var r = Math.floor(Math.random() * -1100) + 1;
b.style.padding = 0 + "px";
b.style.left = i + "px";
b.style.top = j + "px";
b.style.right = r + "px";
}
function plus() {
missc--
missc - 1
counter++;
scr.textContent = counter;
}
function leftsclick() {
missc--
missc - 1
}
function misscmines() {
missc++
missc + 1
}
function resetall() {
window.location.reload(true);
}
body {
margin: 0px;
padding: 0px;
}
.btn {
position: relative;
height: 125px;
width: 125px;
border-radius: 10px;
display: block;
background-color: whitesmoke;
font-size: 20px;
text-align: center;
user-select: none;
font-family: 'Roboto Mono', monospace;
}
.btn:hover {
background-color: #dcdcdc;
border-color: #dcdcdc;
}
.btndiv {
display: grid;
gap: 10px;
top: 5px;
left: 200px;
width: 1724px;
position: fixed;
user-select: none;
}
.sizes {
width: 80px;
height: auto;
color: white;
background-color: #2f2f2f;
cursor: pointer;
font-family: 'Roboto Mono', monospace;
font-size: 20px;
padding-left: 5px;
user-select: none;
}
.score {
font-family: 'Roboto Mono', monospace;
color: white;
font-size: 30px;
white-space: nowrap;
user-select: none
}
.shr7 {
font-size: 20px;
font-family: 'Roboto Mono', monospace;
left: 100px;
color: white;
left: 49%;
padding-left: 5px;
user-select: none
}
.allcont {
display: grid;
grid-template-columns: repeat(25, 1fr);
gap: 10px;
padding-left: 5px;
}
.theLeftSide {
width: 190px;
display: block;
height: 100vh;
background-color: #2f2f2f;
border-right: 6px solid #464646;
overflow-y: auto;
overflow-x: hidden;
}
.theul {
background-color: #2f2f2f;
color: white;
width: 150px;
margin-bottom: 0px;
font-family: 'Roboto Mono', monospace;
border-right: solid 6px #464646;
display: block;
}
li {
font-family: 'Roboto Mono', monospace;
font-size: 15px;
color: white;
user-select: none;
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-thumb {
border-radius: 10px;
background-color: #2a2a2a;
}
::-webkit-scrollbar-thumb:hover {
background-color: #252525;
}
<!DOCTYPE html>
<html id="htm" style="font-family: 'Roboto Mono', monospace; user-select: none;">
<head>
<meta charset="utf-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300&display=swap" rel="stylesheet">
<link rel="shortcut icon" type="image/png" href="icons\icon.png">
<link rel="stylesheet" type="text/css" href="aimcss.css">
<div class="btndiv"><button id="btn" class="btn"><b>Click me</b></button></div>
<div id="theLeftSide" class="theLeftSide">
<div id="pxs" class="sizes div">+ 10px</div>
<div id="pxs" class="sizes div">- 10px</div>
<div class="allcont">
<p id="score" class="score">score:
<p id="scr" class="score">0</p>
</p>
<title>Aim trainer</title>
</div>
<div class="allcont">
<p id="misses" class="score">misses:
<p id="mis" class="score">0</p>
</p>
</div>
<br onscroll="func()">
<div class="allcont" id="bestdiv">
<p class="score">Best:
<p class="score" id="best">0</p>
</p>
</div>
<br>
<div style=" padding-left: 5px;"><button style="height: 30px; width: 70px; font-size: 15px; font-family: 'Roboto Mono', monospace;" id="reset"><b>RESET</b></button></div>
<br><br>
<p type="inherit" class="shr7">• Score-Misses</p>
<ol start="1" id='10sec' class='theul'>
<li style="display: none;" class="lists"><span class="cntrspn">0</span>-0</li>
</ol>
</div>
</head>
<body id="bod" style="background-color: #181818;">
<script type="text/javascript" src="aimscript.js">
</script>
</body>
</html>
I recommend checking the event.pointerId variable when the click occurs.
b.addEventListener('click', change);
const change = (event) => {
if(event.pointerId === -1) {
// this is a "keyboard click" that you want to avoid
}
else {
// actual click
}
};
When the mouse is used, the pointerId should be non-negative. When the keyboard is used to "click," the ID will be -1.
If I understand correctly, you want to stop an edge case where users can hold down enter and the left mouse button as they will keep scoring.
I would recommend listening for the enter key using the keydown and keyup events to track when enter is pressed then using the state to disable any logic while it is pressed.
let isEnterPressed = false
window.addEventListener("keydown", e => {
if(e.keyCode === 13)
isEnterPressed = true // 13 is keycode for enter
})
window.addEventListener("keyup", e => {
if(e.keyCode === 13)
isEnterPressed = false // 13 is keycode for enter
})
then just use isEnterPressed to block any logic triggered by clicking.
This is just a simple example, you could generalize this to track any keyboard input
You can use keypress listener on the button and preventDefault() when the enter triggers on the button priventDefault() will stop that
var b = document.querySelector("button");
var score = document.getElementById('score');
var counter = 0;
var btn = document.getElementById("button");
var tensec = document.getElementById("10sec");
var pxs = document.getElementsByClassName('div');
var scr = document.getElementById("scr");
var mis = document.getElementById("mis");
var htm = document.getElementById("htm");
var missc = 0;
var height1 = 100;
var width1 = 100;
var theLeftSide = document.getElementById("theLeftSide");
var resetbtn = document.getElementById("reset");
var vr = document.getElementById("vr");
var hit = 1080;
var fontsize = 25;
var ulcls = document.getElementsByClassName("theul");
var ul = document.getElementById('10sec');
var best = document.getElementById("best");
var cntrspn = document.getElementsByClassName("cntrspn");
var lists = document.getElementsByClassName("lists");
b.addEventListener("click", change);
b.addEventListener("click", plus);
htm.addEventListener("click", miss);
pxs[0].addEventListener("click", plussize);
pxs[1].addEventListener("click", minesize);
theLeftSide.addEventListener("click", leftsclick);
b.addEventListener("click", misscmines);
resetbtn.addEventListener("click", resetall);
function plussize() {
height1 += 10;
width1 += 10;
missc++
missc + 1
missc--
fontsize += 3;
b.style.fontSize = fontsize + "px";
b.style.height = height1 + "px";
b.style.width = width1 + "px";
missc - 1;
}
function minesize() {
height1 -= 10;
width1 -= 10;
missc++
missc + 1
missc--
fontsize -= 3;
b.style.fontSize = fontsize + "px";
b.style.height = height1 + "px";
b.style.width = width1 + "px";
missc - 1;
}
function miss() {
missc++
mis.innerHTML = missc - counter;
}
setInterval(function() {
var misc = missc - counter;
ul.style.height = window.offsetheight;
var currscr = counter;
for (var i = 0; i < cntrspn.length; i += 1) {
if (parseInt(scr.textContent) > parseInt(best.textContent)) {
best.textContent = scr.textContent;
} else {
console.log("no new best");
}
}
mis.textContent = missc - counter;
ul.innerHTML += '<li class="lists">' + '<span class="cntrspn">' + counter + '</span>' + "-" + misc + '</li>';
missc = 0;
misc = 0;
counter = 0;
scr.textContent = counter;
mis.textContent = missc;
}, 10000);
function change(e) {
var i = Math.floor(Math.random() * 1500) + 1;
var j = Math.floor(Math.random() * 250) + 1;
var r = Math.floor(Math.random() * -1100) + 1;
b.style.padding = 0 + "px";
b.style.left = i + "px";
b.style.top = j + "px";
b.style.right = r + "px";
}
function plus() {
missc--
missc - 1
counter++;
scr.textContent = counter;
}
function leftsclick() {
missc--
missc - 1
}
function misscmines() {
missc++
missc + 1
}
function resetall() {
window.location.reload(true);
}
b.addEventListener("keypress", e => {
let key = e.keyCode || e.charCode;
if (key == 13) {
e.stopPropagation();
e.preventDefault();
}
})
body {
margin: 0px;
padding: 0px;
}
button{
outline: none;
}
.btn {
position: relative;
height: 125px;
width: 125px;
border-radius: 10px;
display: block;
background-color: whitesmoke;
font-size: 20px;
text-align: center;
user-select: none;
font-family: 'Roboto Mono', monospace;
}
.btn:hover {
background-color: #dcdcdc;
border-color: #dcdcdc;
}
.btndiv {
display: grid;
gap: 10px;
top: 5px;
left: 200px;
width: 1724px;
position: fixed;
user-select: none;
}
.sizes {
width: 80px;
height: auto;
color: white;
background-color: #2f2f2f;
cursor: pointer;
font-family: 'Roboto Mono', monospace;
font-size: 20px;
padding-left: 5px;
user-select: none;
}
.score {
font-family: 'Roboto Mono', monospace;
color: white;
font-size: 30px;
white-space: nowrap;
user-select: none
}
.shr7 {
font-size: 20px;
font-family: 'Roboto Mono', monospace;
left: 100px;
color: white;
left: 49%;
padding-left: 5px;
user-select: none
}
.allcont {
display: grid;
grid-template-columns: repeat(25, 1fr);
gap: 10px;
padding-left: 5px;
}
.theLeftSide {
width: 190px;
display: block;
height: 100vh;
background-color: #2f2f2f;
border-right: 6px solid #464646;
overflow-y: auto;
overflow-x: hidden;
}
.theul {
background-color: #2f2f2f;
color: white;
width: 150px;
margin-bottom: 0px;
font-family: 'Roboto Mono', monospace;
border-right: solid 6px #464646;
display: block;
}
li {
font-family: 'Roboto Mono', monospace;
font-size: 15px;
color: white;
user-select: none;
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-thumb {
border-radius: 10px;
background-color: #2a2a2a;
}
::-webkit-scrollbar-thumb:hover {
background-color: #252525;
}
<!DOCTYPE html>
<html id="htm" style="font-family: 'Roboto Mono', monospace; user-select: none;">
<head>
<meta charset="utf-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300&display=swap" rel="stylesheet">
<link rel="shortcut icon" type="image/png" href="icons\icon.png">
<link rel="stylesheet" type="text/css" href="aimcss.css">
<div class="btndiv"><button id="btn" class="btn"><b>Click me</b></button></div>
<div id="theLeftSide" class="theLeftSide">
<div id="pxs" class="sizes div">+ 10px</div>
<div id="pxs" class="sizes div">- 10px</div>
<div class="allcont">
<p id="score" class="score">score:
<p id="scr" class="score">0</p>
</p>
<title>Aim trainer</title>
</div>
<div class="allcont">
<p id="misses" class="score">misses:
<p id="mis" class="score">0</p>
</p>
</div>
<br onscroll="func()">
<div class="allcont" id="bestdiv">
<p class="score">Best:
<p class="score" id="best">0</p>
</p>
</div>
<br>
<div style=" padding-left: 5px;"><button style="height: 30px; width: 70px; font-size: 15px; font-family: 'Roboto Mono', monospace;" id="reset"><b>RESET</b></button></div>
<br><br>
<p type="inherit" class="shr7">• Score-Misses</p>
<ol start="1" id='10sec' class='theul'>
<li style="display: none;" class="lists"><span class="cntrspn">0</span>-0</li>
</ol>
</div>
</head>
<body id="bod" style="background-color: #181818;">
<script type="text/javascript" src="aimscript.js">
</script>
</body>
</html>

I can't convert .duration or .currentTime to MM:SS in java script

since I don't know JavaScript I downloaded an audio player and changed the html and CSS but the audio player shows audio duration in seconds and; I tried to look for results in google but that did not work as well, I even tried to copy code from other audio players but it did not work. I would be happy if anyone help me.
thanks...
$(document).ready(function() {
var timeDrag = false; /* Drag status */
var isPlaying = false;
var theSound = $("#firstTrack");
var allIcons = $("i");
var isLoaded = false;
theSound.on("timeupdate", function() {
var currentPos = theSound[0].currentTime; //Get currenttime
var maxduration = theSound[0].duration; //Get video duration
var percentage = 100 * currentPos / maxduration; //in %
$('.timeBar').css('width', percentage + '%');
$("#getTime").html(Math.floor(theSound[0].duration));
$('#goTime').html(Math.floor(theSound[0].currentTime));
});
$("#playIt").click(function(event) {
// run once.
if (!isLoaded) {
theSound.trigger('load');
setTimeout(startBuffer, 500);
isLoaded = true;
}
// toggle play/pause
if (!isPlaying) {
theSound.trigger('play');
$("#playIt").find(allIcons).removeClass("fa-play");
$("#playIt").find(allIcons).addClass("fa-pause");
isPlaying = true;
} else {
theSound.trigger('pause');
$("#playIt").find(allIcons).removeClass("fa-pause");
$("#playIt").find(allIcons).addClass("fa-play");
isPlaying = false;
}
});
$("#stepFive").click(function() {
var currentPos = theSound[0].currentTime + 5;
theSound[0].currentTime = currentPos;
});
$("#stepFiveback").click(function() {
var currentPos = theSound[0].currentTime - 5;
theSound[0].currentTime = currentPos;
});
$('.progressBar').mousedown(function(e) {
timeDrag = true;
updatebar(e.pageX);
});
$(document).mouseup(function(e) {
if (timeDrag) {
timeDrag = false;
updatebar(e.pageX);
}
});
$(document).mousemove(function(e) {
if (timeDrag) {
updatebar(e.pageX);
}
});
//update Progress Bar control
var updatebar = function(x) {
var progress = $('.progressBar');
var maxduration = theSound[0].duration; //Video duraiton
var position = x - progress.offset().left; //Click pos
var percentage = 100 * position / progress.width();
//Check within range
if (percentage > 100) {
percentage = 100;
}
if (percentage < 0) {
percentage = 0;
}
//Update progress bar and video currenttime
$('.timeBar').css('width', percentage + '%');
theSound[0].currentTime = maxduration * percentage / 100;
};
//loop to get HTML5 video buffered data
var startBuffer = function() {
var maxduration = $("#firstTrack")[0].duration;
var currentBuffer = $("#firstTrack")[0].buffered.end(0);
var percentage = 100 * currentBuffer / maxduration;
$('.bufferBar').css('width', percentage + '%');
//re-loop if not entierely buffered
if (currentBuffer < maxduration) {
setTimeout(startBuffer, 500);
}
};
});
#charset "utf-8";
/*head*/
html,
html * {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #1e1f1f;
max-height: 100vh;
/* change here */
}
/* -- */
.noPad {
padding: 0;
}
.playBar {
transition: all 0.5s ease;
height: 10px;
background-color: rgba(186, 44, 44, 0.59);
/*border: 1.5px;*/
/*border-color: black;*/
/*border-style: inset;*/
opacity: 0.85;
width: 0;
}
#audioCtrl>div {
margin: 0;
padding: 0;
}
.progressBar {
position: relative;
width: 100%;
height: .4em;
backgroud-color: #474848;
color: #474848;
scroll-behavior: smooth;
border: solid;
border-color: #474848;
border-width: 1px;
border-radius: 5px;
}
.timeBar {
transition: all 0.5s ease;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #8c8d8e;
border-radius: 5px;
}
.bufferBar {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #474949;
opacity: 0.5;
border-radius: 5px;
}
/* -- */
.row {
/* background-color: #535252; */
border-radius: 10px;
}
.img-container img {
margin-top: 10em;
border-radius: 15px;
height: 22em;
}
.navigation {
display: flex;
align-items: center;
justify-content: center;
}
.info1 {}
.title {
font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, "sans-serif";
font-size: 1.7em;
margin: 0;
padding-bottom: .4em;
margin-left: .2em;
color: #f1f1f1;
}
.time-btn {
float: right;
margin-top: .3em;
background-color: #1E1F1F;
color: aliceblue;
border: 0;
font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
font-size: 1em;
margin-right: .3em;
}
.time-btn2 {
margin-top: .3em;
background-color: #1E1F1F;
color: aliceblue;
border: 0;
font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
font-size: 1em;
margin-left: .2em;
}
.btn {
background-color: #1e1f1f;
color: #D7D7D7;
border: 0;
font-size: 2.2em;
padding: .3em .7em;
}
.btn-big {
color: #FFFFFF;
font-size: 2.4em;
}
.btn:focus {
border: 0;
}
.scrollformore {
color: #FFFFFF;
font-family: "Gill Sans", "Gill Sans MT", "Myriad Pro", "DejaVu Sans Condensed", Helvetica, Arial, "sans-serif";
font-size: 1em;
margin-top: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>audio_player_2</title>
<link rel="stylesheet" href="assets/css/styles.css">
<link rel="stylesheet" href="assets/css/aistyles.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.min.css" />
</head>
<body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="simple_player.js"></script>
<div class="container-fluid"><audio id="firstTrack" width="100%" preload="none">
<source src="https://www.bensound.com/bensound-music/bensound-ukulele.mp3" type="audio/mpeg" />
</audio>
<div class="img-container"><img src="https://www.bensound.com/bensound-img/ukulele.jpg" alt="cover"></div>
<h2 class="title info1">Ukulele</h2>
<div class="row" id="audioCtrl">
<div class="col-xs-3 progressBar">
<div class="bufferBar"></div>
<div class="timeBar"></div>
</div>
<div class="col-xs-3"><button class="time-btn info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="getTime"><div class="durationTime">00</div></span></i></button></div>
<div class="col-xs-3"><button class="time-btn2 info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="goTime"><div class="currentTime">00</div></span></i></button></div>
<div class="navigation">
<div class="col-xs-3"><button class="btn btn-default blackb" id="stepFiveback" type="button"> <i class="fa fa-backward"> <span class="hidden-xs"></span></i></button></div>
<div class="col-xs-3"><button class="btn btn-default blackb btn-big" id="playIt" type="button"> <i class="fa fa-play"> </i></button></div>
<div class="col-xs-3"><button class="btn btn-default blackb" id="stepFive" type="button"> <i class="fa fa-forward"> <span class="hidden-xs"></span></i></button></div>
</div>
</div>
</div>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/js/simple_player.js"></script>
</body>
</html>
strong text
You will want to add a function to help convert all the Seconds to Minutes and Seconds.
Consider the following Example.
function convertSeconds(sec) {
var m = Math.floor(sec / 60);
var s = sec % 60;
return (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
}
This get the calculated Minutes and Seconds from a total number of Seconds using Division and Modulus. It may look like this in use:
$(document).ready(function() {
var timeDrag = false; /* Drag status */
var isPlaying = false;
var theSound = $("#firstTrack");
var allIcons = $("i");
var isLoaded = false;
function convertSeconds(sec) {
var m = Math.floor(sec / 60);
var s = sec % 60;
return (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
}
theSound.on("timeupdate", function() {
var currentPos = theSound[0].currentTime; //Get currenttime
var maxduration = theSound[0].duration; //Get video duration
var percentage = 100 * currentPos / maxduration; //in %
$('.timeBar').css('width', percentage + '%');
$("#getTime").html(convertSeconds(Math.floor(theSound[0].duration)));
$('#goTime').html(convertSeconds(Math.floor(theSound[0].currentTime)));
});
$("#playIt").click(function(event) {
if (!isLoaded) {
theSound.trigger('load');
setTimeout(startBuffer, 500);
isLoaded = true;
}
if (!isPlaying) {
theSound.trigger('play');
$("#playIt").find(allIcons).removeClass("fa-play");
$("#playIt").find(allIcons).addClass("fa-pause");
isPlaying = true;
} else {
theSound.trigger('pause');
$("#playIt").find(allIcons).removeClass("fa-pause");
$("#playIt").find(allIcons).addClass("fa-play");
isPlaying = false;
}
});
$("#stepFive").click(function() {
var currentPos = theSound[0].currentTime + 5;
theSound[0].currentTime = currentPos;
});
$("#stepFiveback").click(function() {
var currentPos = theSound[0].currentTime - 5;
theSound[0].currentTime = currentPos;
});
$('.progressBar').mousedown(function(e) {
timeDrag = true;
updatebar(e.pageX);
});
$(document).mouseup(function(e) {
if (timeDrag) {
timeDrag = false;
updatebar(e.pageX);
}
});
$(document).mousemove(function(e) {
if (timeDrag) {
updatebar(e.pageX);
}
});
//update Progress Bar control
var updatebar = function(x) {
var progress = $('.progressBar');
var maxduration = theSound[0].duration; //Video duraiton
var position = x - progress.offset().left; //Click pos
var percentage = 100 * position / progress.width();
//Check within range
if (percentage > 100) {
percentage = 100;
}
if (percentage < 0) {
percentage = 0;
}
//Update progress bar and video currenttime
$('.timeBar').css('width', percentage + '%');
theSound[0].currentTime = maxduration * percentage / 100;
};
//loop to get HTML5 video buffered data
var startBuffer = function() {
var maxduration = $("#firstTrack")[0].duration;
var currentBuffer = $("#firstTrack")[0].buffered.end(0);
var percentage = 100 * currentBuffer / maxduration;
$('.bufferBar').css('width', percentage + '%');
//re-loop if not entierely buffered
if (currentBuffer < maxduration) {
setTimeout(startBuffer, 500);
}
};
});
#charset "utf-8";
/*head*/
html,
html * {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #1e1f1f;
max-height: 100vh;
/* change here */
}
/* -- */
.noPad {
padding: 0;
}
.playBar {
transition: all 0.5s ease;
height: 10px;
background-color: rgba(186, 44, 44, 0.59);
/*border: 1.5px;*/
/*border-color: black;*/
/*border-style: inset;*/
opacity: 0.85;
width: 0;
}
#audioCtrl>div {
margin: 0;
padding: 0;
}
.progressBar {
position: relative;
width: 100%;
height: .4em;
backgroud-color: #474848;
color: #474848;
scroll-behavior: smooth;
border: solid;
border-color: #474848;
border-width: 1px;
border-radius: 5px;
}
.timeBar {
transition: all 0.5s ease;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #8c8d8e;
border-radius: 5px;
}
.bufferBar {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #474949;
opacity: 0.5;
border-radius: 5px;
}
/* -- */
.row {
/* background-color: #535252; */
border-radius: 10px;
}
.img-container img {
margin-top: 10em;
border-radius: 15px;
height: 22em;
}
.navigation {
display: flex;
align-items: center;
justify-content: center;
}
.info1 {}
.title {
font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, "sans-serif";
font-size: 1.7em;
margin: 0;
padding-bottom: .4em;
margin-left: .2em;
color: #f1f1f1;
}
.time-btn {
float: right;
margin-top: .3em;
background-color: #1E1F1F;
color: aliceblue;
border: 0;
font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
font-size: 1em;
margin-right: .3em;
}
.time-btn2 {
margin-top: .3em;
background-color: #1E1F1F;
color: aliceblue;
border: 0;
font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
font-size: 1em;
margin-left: .2em;
}
.btn {
background-color: #1e1f1f;
color: #D7D7D7;
border: 0;
font-size: 2.2em;
padding: .3em .7em;
}
.btn-big {
color: #FFFFFF;
font-size: 2.4em;
}
.btn:focus {
border: 0;
}
.scrollformore {
color: #FFFFFF;
font-family: "Gill Sans", "Gill Sans MT", "Myriad Pro", "DejaVu Sans Condensed", Helvetica, Arial, "sans-serif";
font-size: 1em;
margin-top: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.min.css" />
<div class="container-fluid">
<audio id="firstTrack" width="100%" preload="none">
<source src="https://www.bensound.com/bensound-music/bensound-ukulele.mp3" type="audio/mpeg" />
</audio>
<div class="img-container"><img src="https://www.bensound.com/bensound-img/ukulele.jpg" alt="cover"></div>
<h2 class="title info1">Ukulele</h2>
<div class="row" id="audioCtrl">
<div class="col-xs-3 progressBar">
<div class="bufferBar"></div>
<div class="timeBar"></div>
</div>
<div class="col-xs-3"><button class="time-btn info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="getTime"><div class="durationTime">00:00</div></span></i></button></div>
<div class="col-xs-3"><button class="time-btn2 info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="goTime"><div class="currentTime">00:00</div></span></i></button></div>
<div class="navigation">
<div class="col-xs-3"><button class="btn btn-default blackb" id="stepFiveback" type="button"> <i class="fa fa-backward"> <span class="hidden-xs"></span></i></button></div>
<div class="col-xs-3"><button class="btn btn-default blackb btn-big" id="playIt" type="button"> <i class="fa fa-play"> </i></button></div>
<div class="col-xs-3"><button class="btn btn-default blackb" id="stepFive" type="button"> <i class="fa fa-forward"> <span class="hidden-xs"></span></i></button></div>
</div>
</div>
</div>
</div>
Try this:
export function timeFormat(d: number) {
const duration = Math.floor(d);
const h = Math.floor(duration / 3600);
const m = Math.floor((duration - h * 3600) / 60);
const s = duration % 60;
const H = h === 0 ? '' : `${h}:`;
const M = m < 10 ? `0${m}:` : `${m}:`;
const S = s < 10 ? `0${s}` : `${s}`;
return H + M + S;
}

Why does getting input boxes' .value not work after it's been submitted?

I have an input box that I'm getting the value of with .value, and it will get the value the first time, but after the input box has been submitted once, getting it's .value doesn't work anymore. Is there a way to fix this or an alternative way to get the value of the input box, or am I just doing something wrong?
To recreate the error, just run the snippet below and input something twice.
var chatinput = document.getElementById("chatinput");
var body = document.getElementById("body");
var username;
var inp = null;
var message = "";
username = prompt("Enter a username:", "Username");
if (username !== null) {
inp = username.toLowerCase();
}
while (inp === null || inp === "" || inp == "username" || inp.includes("fuck") || inp.includes("ass") || inp.includes("shit") || inp.includes("*")) {
username = prompt("That's not an appropriate username...", "Username");
if (username !== null) {
inp = username.toLowerCase();
}
}
function sendchat() {
message = "[" + username + "]: " + chatinput.value;
body.innerHTML += "<p class=\"chatbox\">" + message + "</p>";
chatinput.value = "";
}
addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
sendchat();
}
});
* {
transition-duration: 0.5s;
scroll-behavior: smooth;
}
body {
background-color: black;
}
div {
width: 100%;
text-align: justify;
}
h1 {
font: 8vw courier;
color: white;
}
h2 {
font: 7vw courier;
color: white;
}
h3 {
font: 6vw courier;
color: white;
}
h4 {
font: 5vw courier;
color: white;
}
h5 {
font: 4vw courier;
color: white;
}
h6 {
font: 3vw courier;
color: white;
}
p {
font: 2vw courier;
color: white;
}
button, input, a {
text-decoration: none;
font: 2vw courier;
color: cyan;
border: 0.2vw solid cyan;
border-radius: 1vw;
background-color: darkblue;
}
a:hover, input:hover, button:hover {
background-color: blue;
box-shadow: 0px 0px 2.5vw white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Stuff</title>
<link href="/logo.png" rel="icon">
<link href="/style.css" rel="stylesheet">
</head>
<body id="body">
<p>Message: <input id="chatinput"></p>
<script src="script.js"></script>
</body>
</html>
The listener is getting clobbered. Here is a way to protect the listener by adding a div and appending the new chat elements.
var chatinput = document.getElementById("chatinput");
var body = document.getElementById("body");
var username;
var inp = null;
var message = "";
username = prompt("Enter a username:", "Username");
if (username !== null) {
inp = username.toLowerCase();
}
while (inp === null || inp === "" || inp == "username" || inp.includes("fuck") || inp.includes("ass") || inp.includes("shit") || inp.includes("*")) {
username = prompt("That's not an appropriate username...", "Username");
if (username !== null) {
inp = username.toLowerCase();
}
}
function sendchat() {
var objchatAreaElem = document.getElementById("chatArea");
var newMessageElem = document.createElement('p');
message = "[" + username + "]: " + chatinput.value;
newMessageElem.appendChild(document.createTextNode(message));
objchatAreaElem.appendChild(newMessageElem );
chatinput.value = "";
}
addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
sendchat();
}
});
* {
transition-duration: 0.5s;
scroll-behavior: smooth;
}
body {
background-color: black;
}
div {
width: 100%;
text-align: justify;
}
h1 {
font: 8vw courier;
color: white;
}
h2 {
font: 7vw courier;
color: white;
}
h3 {
font: 6vw courier;
color: white;
}
h4 {
font: 5vw courier;
color: white;
}
h5 {
font: 4vw courier;
color: white;
}
h6 {
font: 3vw courier;
color: white;
}
p {
font: 2vw courier;
color: white;
}
button, input, a {
text-decoration: none;
font: 2vw courier;
color: cyan;
border: 0.2vw solid cyan;
border-radius: 1vw;
background-color: darkblue;
}
a:hover, input:hover, button:hover {
background-color: blue;
box-shadow: 0px 0px 2.5vw white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Stuff</title>
<link href="/logo.png" rel="icon">
<link href="/style.css" rel="stylesheet">
</head>
<body id="body">
<p>Message: <input id="chatinput"></p>
<div id="chatArea"></div>
<script src="script.js"></script>
</body>
</html>

How to pass a parentNode.id as a parameter to an element out of the querySelector

I have these elements created inside a "querySelector('ul'). It's working property.
I want the "blue-Save" button to have the same function as the "yellow-Save".
But the Blue-save button was created in the HTML file, and the Yellow-Save button was created in JavaScript to listen to an event from the "querySelector('ul').
Is there anyway I can just link the Blue-Save to react as if I was clicking in the Yellow-Save?
(I'm sorry if I didn't explain it property or If it seems too confused, this is my first application, It doesn't seems too organized but I'm focused in making things work before dive in 'well developed apps').
Thank You Everyone!
var todoList = {
todos: [],
addTodo: function (todoText) {
this.todos.push({
todoText: todoText,
/*the name of the property (even if it is the same name as the parameter) never change. Only the value, which follows in this case is following the parameter*/
completed: false
});
},
changeTodo: function (position, todoText) {
this.todos[position].todoText = todoText;
},
deleteTodo: function (position) {
this.todos.splice(position, 1);
},
toggleCompleted: function (position) {
var todo = this.todos[position];
todo.completed = !todo.completed;
/*Here we flip the boolean to his oposite value. if todo.completed is equal false, so changes it to true, and so on. */
},
toggleAll: function () {
// recording the number of todos and completed todos
var totalTodos = this.todos.length;
var completedTodos = 0;
// get the number of completed todos.
this.todos.forEach(function (todo) {
if (todo.completed === true) {
completedTodos++;
}
});
this.todos.forEach(function (todo) {
// Case 1: If everything is true, make everything.
if (completedTodos === totalTodos) {
todo.completed = false;
// Case 2: Otherwise, make everything true.
} else {
todo.completed = true;
}
});
}
};
var handlers = {
addTodo: function () {
var addTodoTextInput = document.getElementById('add-todo-text-input');
todoList.addTodo(addTodoTextInput.value);
addTodoTextInput.value = '';
view.displayTodos();
},
changeTodo: function (position) {
var changeTodoTextInput = document.getElementById('change-todo-text-input');
todoList.changeTodo(position, changeTodoTextInput.value);
changeTodoTextInput.value = '';
view.displayTodos();
},
deleteTodo: function (position) {
todoList.deleteTodo(position);
view.displayTodos();
},
toggleCompleted: function (position) {
todoList.toggleCompleted(position);
view.displayTodos();
},
toggleAllButton: function () {
todoList.toggleAll();
view.displayTodos();
}
};
var view = {
displayTodos: function () {
var todosUl = document.querySelector('ul');
todosUl.innerHTML = '';
todoList.todos.forEach(function (todo, position) {
var todoLi = document.createElement('li');
var todoTextWithCompletion = '';
if (todo.completed === true) {
todoTextWithCompletion = todo.todoText;
todoLi.classList.add('item-completed');
} else {
todoTextWithCompletion = todo.todoText;
}
todoLi.id = position;
todoLi.textContent = todoTextWithCompletion;
todoLi.appendChild(this.createEditButton());
todoLi.appendChild(this.createToggleButton());
todoLi.appendChild(this.createDeleteButton());
todoLi.appendChild(this.createSaveButton());
todosUl.appendChild(todoLi);
}, this);
},
createDeleteButton: function () {
var deleteButton = document.createElement('button');
deleteButton.textContent = '\u2715';
deleteButton.className = 'delete-button';
return deleteButton;
},
createToggleButton: function () {
var toggleButton = document.createElement('button');
toggleButton.textContent = '\u2713';
toggleButton.className = 'toggle-button';
return toggleButton;
},
createSaveButton: function () {
var saveButton = document.createElement('button');
saveButton.textContent = 'Save';
saveButton.className = 'save-button';
return saveButton;
},
createEditButton: function () {
var editButton = document.createElement('button');
editButton.textContent = '\u270E';
editButton.className = 'edit-button';
return editButton;
},
setUpEventListeners: function () {
var todosUl = document.querySelector('ul');
todosUl.addEventListener('click', function (event) {
// Get the element that was clicked on.
var elementClicked = event.target;
// Check if elementClicked is a delete button.
if (elementClicked.className === 'delete-button') {
handlers.deleteTodo(parseInt(elementClicked.parentNode.id));
} else if (elementClicked.className === 'toggle-button') {
handlers.toggleCompleted(parseInt(elementClicked.parentNode.id));
} else if (elementClicked.className === 'save-button') {
handlers.changeTodo(parseInt(elementClicked.parentNode.id));
} else if (elementClicked.className === 'edit-button') {
}
});
}
};
view.setUpEventListeners();
body {
font-family: Helvetica, sans-serif;
font-size: 25px;
background: rgb(236, 236, 236);
}
h1 {
color: rgb(255, 255, 255);
text-align: center;
font-family: Helvetica, sans-serif;
font-size: 50px;
text-transform: uppercase;
background: rgb(48, 48, 48);
position: relative;
}
.container {
margin: auto;
width: 50%;
}
ul {
list-style: none;
padding:0px;
margin: 10px;
}
.add-button {
background-color: rgb(68, 165, 230); /* Blue */
border: none;
color: white;
margin:auto;
padding: 15px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 5px;
width:20%;
}
.add-button:hover {
background-color :rgb(53, 127, 177); /* Green */
color: white;
}
.save-change-button {
background-color: rgb(68, 165, 230); /* Blue */
border: none;
color: white;
margin:auto;
padding: 15px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 5px;
width:20%;
}
.save-change-button:hover {
background-color :rgb(53, 127, 177); /* Green */
color: white;
}
.toggle-all-button {
background-color: rgb(38, 156, 38); /* Green */
border: none;
color: white;
margin: 10px 0;
padding: 15px 32px;
text-align: center;
text-decoration: none;
font-size: 16px;
border-radius: 5px;
width: 100%;
}
.toggle-all-button:hover {
background-color : rgb(36, 114, 36); /* Green */
color: white;
}
.edit-button {
background-color: rgb(219, 208, 50); /* Green */
border: none;
color: white;
padding: 0;
text-align: center;
text-decoration: none;
font-size: 18px;
border-radius: 5px;
width: 25px;
height: 25px;
margin: 0 0 0 10px;
}
.edit-button:hover {
background-color: rgb(185, 175, 26); /* Green */
color: white;
}
.toggle-button {
background-color: rgb(38, 156, 38); /* Green */
border: none;
color: white;
padding: 0;
text-align: center;
text-decoration: none;
font-size: 18px;
border-radius: 5px;
width: 25px;
height: 25px;
margin: 0 0 0 10px;
}
.toggle-button:hover {
background-color: rgb(36, 114, 36); /* Green */
color: white;
}
.delete-button {
background-color: rgb(168, 44, 44); /* Green */
border: none;
color: white;
margin: 0 0 0 10px;
padding: 0;
text-align: center;
text-decoration: none;
font-size: 18px;
border-radius: 5px;
width: 25px;
height: 25px;
}
.delete-button:hover {
background-color :rgb(128, 31, 31); /* Green */
color: white;
}
.save-button {
background-color: rgb(219, 208, 50); /* Green */
border: none;
color: white;
padding: 0;
text-align: center;
text-decoration: none;
font-size: 18px;
border-radius: 5px;
width: 55px;
height: 25px;
margin: 0 10px;
}
.save-button:hover {
background-color :rgb(185, 175, 26); /* Green */
color: white;
}
.add-input {
margin: 10px 0;
padding: 6px 0;
text-align: center;
font-family: Arial, Helvetica, sans-serif;
font-size: 18px;
width: 78%;
}
.edit-input {
margin: 10px 0;
padding: 6px 0;
text-align: center;
font-family: Arial, Helvetica, sans-serif;
font-size: 18px;
width: 78%;
}
.item-completed {
text-decoration: line-through;
}
::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */
color: rgba(209, 209, 209, 0.555);
font-family: 'Times New Roman', Times, serif;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Todo List</title>
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1>Todo List</h1>
<div>
<input id="add-todo-text-input" class="add-input" placeholder="Add a New Todo to Your List" type="text">
<button class="add-button" onclick="handlers.addTodo()">Add</button>
</div>
<ul>
</ul>
<div id="edit-todo"">
<input id="change-todo-text-input" class="edit-input" placeholder="Add the Changes Your Want to Make" type="text">
<button class="save-change-button">Save</button>
</div>
<div id="toggle-all"">
<button class="toggle-all-button" onclick="handlers.toggleAllButton()">Toggle All</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
You can add a common class to both blue and yellow buttons, and attach a click event by the class name like below
$(".custom_save_button").on("click", function() {
//your code
});
Since you are creating that button, sharing the same class won't just work as expected, instead use delegated events which allow you to attach events on new elements added to the DOM
Add a common class for both and then add an event listener for that class using event delegation.
For this example Let's suppose you chose the class name: stack_class
//I added this function for you to be able to know if an element has a class
function hasClass( target, className ) {
return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
}
//you could change body to the closest parent's selector both buttons share
document.querySelector('body').addEventListener('click', function(event) {
var clickedElement = event.target;
if(hasClass(clickedElement, "stack_class")) {
//create your functionality for both buttons here
}
});
If you assign a common class to both buttons, then you can add the same event listener to all buttons that have that class. Here is a simple example:
var saveButton = document.createElement('button');
saveButton.textContent = 'Save';
saveButton.className = 'save-button yellow-button';
body = document.querySelector('body');
body.appendChild(saveButton);
buttons = document.getElementsByClassName('save-button');
for (var i = 0; i < buttons.length; i += 1) {
buttons[i].addEventListener('click', function (event) {
alert('Hello!');
});
}
.yellow-button {
background: #ffff00;
}
.blue-button {
background: #0000ff;
}
<button class="save-button blue-button">Save</button>

click area problems with a div in javascript

I'm new with javascript, I've made some customize buttons with <div> and css style, the mouseover, mouseout and click events are controlled with Javascript. These events works relatively well but the click area is not working. Instead of work with all the button size, the click area is a small portion on the top of the <div>. How can I correct the click area to work with all the button?
This is the HTML, CSS and JavaScript code I'm using.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Customize Button</title>
<!--import stylesheet -->
<link rel="stylesheet" type="text/css" href="botonesStyles.css">
</head>
<body>
<section class="services-wrap">
<div class="service-button" id="service_account" >
<span id="serviceA-text" class="service-button-text">ACCOUNT
TO ACCOUNT</span>
</div>
<div class="service-button" id="service_credit">
<span id="serviceB-text" class="service-button-text">CREDIT
CARD</span>
</div>
<div class="service-button" id="service_cash">
<span id="serviceC-text" class="service-button-text">WORLD
CASH</span>
</div>
<div class="service-button" id="service_exchange">
<span id="serviceC-text" class="service-button-text">EXCHANGE
UPDATES</span>
</div>
<div class="service-text-wrap">
<div id="service-account-wrap" class="service-account-wrap">
<span class="service-text"> Transfer money between accounts
in different currencies as one-time or recurrent transactions.</span>
</div>
<div id="service-credit-wrap" class="service-credit-wrap">
<span class="service-text"> Send money to your foreign credit
cards. Or use your local credit card to send cash worldwide. </span>
</div>
<div id="service-world-wrap" class="service-world-wrap">
<span class="service-text"> From your account or credit card
transfer money and collect it in cash at selected destination. </span>
</div>
<div id="service-exchange-wrap" class="service-exchange-wrap">
<span class="service-text"> Receive notification via email on
the exchange rate that meets your criteria free of charge. </span>
</div>
<script type="text/javascript">
//text variables to set it true or false
var t1 = 0;
var x1 = document.getElementById("service-account-wrap");
var x2 = document.getElementById("service-credit-wrap");
var x3 = document.getElementById("service-world-wrap");
var x4 = document.getElementById("service-exchange-wrap");
/* Add Event Listener for all service buttons */
document.getElementById("service_account").addEventListener("mouseover", showtextAccount);
document.getElementById("service_account").addEventListener("mouseout", hidetextAcount);
document.getElementById("service_account").addEventListener("click", clickAccount);
document.getElementById("service_credit").addEventListener("mouseover", showtextCredit);
document.getElementById("service_credit").addEventListener("mouseout", hidetextCredit);
document.getElementById("service_credit").addEventListener("click", clickCredit);
document.getElementById("service_cash").addEventListener("mouseover", showtextCash);
document.getElementById("service_cash").addEventListener("mouseout", hidetextCash);
document.getElementById("service_cash").addEventListener("click", clickCash);
document.getElementById("service_exchange").addEventListener("mouseover", showtextExchange);
document.getElementById("service_exchange").addEventListener("mouseout", hidetextExchange);
document.getElementById("service_exchange").addEventListener("click", clickExcahnge);
function showtextAccount() {
x1.style.display ="block";
x2.style.display = "none";
x3.style.display = "none";
x4.style.display = "none";
this.style.backgroundColor ="#7b3454";
}
function showtextCredit() {
x1.style.display ="none";
x2.style.display = "block";
x3.style.display = "none";
x4.style.display = "none";
this.style.backgroundColor ="#7b3454";
}
function showtextCash() {
x1.style.display ="none";
x2.style.display = "none";
x3.style.display = "block";
x4.style.display = "none";
this.style.backgroundColor ="#7b3454";
}
function showtextExchange() {
x1.style.display ="none";
x2.style.display = "none";
x3.style.display = "none";
x4.style.display = "block";
this.style.backgroundColor ="#7b3454";
}
function hidetextAcount() {
x1.style.display = "none";
document.getElementById("service_account").style.backgroundColor ="#1f1e20";
}
function hidetextCredit() {
x2.style.display = "none";
document.getElementById("service_credit").style.backgroundColor ="#1f1e20";
}
function hidetextCash() {
x3.style.display = "none";
document.getElementById("service_cash").style.backgroundColor ="#1f1e20";
}
function hidetextExchange() {
x4.style.display = "none";
document.getElementById("service_exchange").style.backgroundColor ="#1f1e20";
}
function clickAccount() {
t1 = 1;
document.getElementById("service_account").removeEventListener("mouseover", showtextAccount);
document.getElementById("service_account").removeEventListener("mouseout", hidetextAcount);
document.getElementById("service_credit").addEventListener("mouseover", showtextCredit);
document.getElementById("service_credit").addEventListener("mouseout", hidetextCredit);
document.getElementById("service_cash").addEventListener("mouseover", showtextCash);
document.getElementById("service_cash").addEventListener("mouseout", hidetextCash);
document.getElementById("service_exchange").addEventListener("mouseover", showtextExchange);
document.getElementById("service_exchange").addEventListener("mouseout", hidetextExchange);
x1.style.display ="block";
x2.style.display = "none";
x3.style.display = "none";
x4.style.display = "none";
document.getElementById("service_account").style.backgroundColor ="#f27a20";
document.getElementById("service_credit").style.backgroundColor ="#1f1e20";
document.getElementById("service_cash").style.backgroundColor ="#1f1e20";
document.getElementById("service_exchange").style.backgroundColor ="#1f1e20";
}
function clickCredit() {
t1 =2;
document.getElementById("service_account").addEventListener("mouseover", showtextAccount);
document.getElementById("service_account").addEventListener("mouseout", hidetextAcount);
document.getElementById("service_credit").removeEventListener("mouseover", showtextCredit);
document.getElementById("service_credit").removeEventListener("mouseout", hidetextCredit);
document.getElementById("service_cash").addEventListener("mouseover", showtextCash);
document.getElementById("service_cash").addEventListener("mouseout", hidetextCash);
document.getElementById("service_exchange").addEventListener("mouseover", showtextExchange);
document.getElementById("service_exchange").addEventListener("mouseout", hidetextExchange);
x1.style.display ="none";
x2.style.display = "block";
x3.style.display = "none";
x4.style.display = "none";
document.getElementById("service_account").style.backgroundColor ="#1f1e20";
document.getElementById("service_credit").style.backgroundColor ="#f27a20";
document.getElementById("service_cash").style.backgroundColor ="#1f1e20";
document.getElementById("service_exchange").style.backgroundColor ="#1f1e20";
}
function clickCash() {
t1 = 3;
document.getElementById("service_account").addEventListener("mouseover", showtextAccount);
document.getElementById("service_account").addEventListener("mouseout", hidetextAcount);
document.getElementById("service_credit").addEventListener("mouseover", showtextCredit);
document.getElementById("service_credit").addEventListener("mouseout", hidetextCredit);
document.getElementById("service_cash").removeEventListener("mouseover", showtextCash);
document.getElementById("service_cash").removeEventListener("mouseout", hidetextCash);
document.getElementById("service_exchange").addEventListener("mouseover", showtextExchange);
document.getElementById("service_exchange").addEventListener("mouseout", hidetextExchange);
x1.style.display ="none";
x2.style.display = "none";
x3.style.display = "block";
x4.style.display = "none";
document.getElementById("service_account").style.backgroundColor ="#1f1e20";
document.getElementById("service_credit").style.backgroundColor ="#1f1e20";
document.getElementById("service_cash").style.backgroundColor ="#f27a20";
document.getElementById("service_exchange").style.backgroundColor ="#1f1e20";
}
function clickExcahnge() {
t1 = 4;
document.getElementById("service_account").addEventListener("mouseover", showtextAccount);
document.getElementById("service_account").addEventListener("mouseout", hidetextAcount);
document.getElementById("service_credit").addEventListener("mouseover", showtextCredit);
document.getElementById("service_credit").addEventListener("mouseout", hidetextCredit);
document.getElementById("service_cash").addEventListener("mouseover", showtextCash);
document.getElementById("service_cash").addEventListener("mouseout", hidetextCash);
document.getElementById("service_exchange").removeEventListener("mouseover", showtextExchange);
document.getElementById("service_exchange").removeEventListener("mouseout", hidetextExchange);
x1.style.display ="none";
x2.style.display = "none";
x3.style.display = "none";
x4.style.display = "block";
document.getElementById("service_account").style.backgroundColor ="#1f1e20";
document.getElementById("service_credit").style.backgroundColor ="#1f1e20";
document.getElementById("service_cash").style.backgroundColor ="#1f1e20";
document.getElementById("service_exchange").style.backgroundColor ="#f27a20";
}
</script>
</div>
</section>
</body>
</html>
CSS code:
#media only screen and (min-device-width: 768px) {
html {
position: relative;
left: 15%;
margin: 10px;
padding: 0;
width: 1280px;
}
body {
display: block;
font-family: 'Open Sans', sans-serif;
text-align: center;
background-color: #cccccc;
}
/* ---------- SERVICES SECTION -----------*/
.services-wrap {
display: inline-block;
position: absolute;
top: 170px;
left: 0;
width: 100%;
height: 60px;
margin: 0;
padding: 0;
}
.service-button {
float: left;
cursor: pointer;
background: #1f1e20;
width: 25%;
height: 35px;
margin: 0;
padding: 0;
}
.service-button-text {
position: relative;
top: 5px;
font-family: 'Open Sans', sans-serif;
font-weight: 300;
font-size: 14px;
color: #FFFFFF;
width: 50%;
height: 16px;
text-align: center;
margin: 0;
}
/*-------------- SERVICE TEXT ---------------------------*/
.service-text-wrap {
width: 100%;
height: 90px;
}
.service-text {
font-family: 'Open Sans', sans-serif;
font-weight: 300;
font-size: 14px;
text-align: left;
color: #1f1e20;
}
.service-account-wrap {
display: none;
position: relative;
top: 10px; font-family : 'Open Sans', sans-serif;
font-weight: 300;
font-size: 14px;
text-align: left;
color: #1f1e20;
width: 90%;
height: 50px;
margin: 0 50px 0 50px;
padding: 0;
font-family: 'Open Sans', sans-serif;
}
.service-credit-wrap {
display: none;
position: relative; top : 10px;
font-family: 'Open Sans', sans-serif;
font-weight: 300;
font-size: 14px;
text-align: left;
color: #1f1e20;
width: 90%;
height: 50px;
margin: 0 50px 0 50px;
padding: 0;
top: 10px;
}
.service-world-wrap {
display: none;
position: relative; top : 10px;
font-family: 'Open Sans', sans-serif;
font-weight: 300;
font-size: 14px;
text-align: left;
color: #1f1e20;
width: 90%;
height: 50px;
margin: 0 50px 0 50px;
padding: 0;
top: 10px;
}
.service-exchange-wrap {
display: none;
position: relative; top : 10px;
font-family: 'Open Sans', sans-serif;
font-weight: 300;
font-size: 14px;
text-align: left;
color: #1f1e20;
width: 90%;
height: 50px;
margin: 0 50px 0 50px;
padding: 0;
top: 10px;
}
}
I have go through your code. I found some design issue. Your mouseover, mouseout, and click events are working on "service-button". This class have a style "float:left;". Your next div "service-text-wrap" is coming over "service-button". You just need to add
<div style="clear:both;"> </div>
just before "service-text-wrap" div. Hope this will help you.

Categories

Resources