refactoring javascript code to create for loop - javascript

I am practicing Javascript. I want each link to display something different in the DOM when clicked.
Here is my current Javascript that works.
//used a 'for' loop to hide each 'notes' page
const element = document.querySelectorAll(".notes");
for (let x = 0; x < element.length; x++)
element[x].style.display = 'none';
const html_link= document.getElementById('html-link');
const css_link = document.getElementById('css-link');
const javascript_link = document.getElementById('js-link');
const html_notes = document.getElementById('html-notes');
const css_notes = document.getElementById('css-notes');
const js_notes = document.getElementById('js-notes');
html_link.onclick = function() {
html_notes.style.display = "block";
css_notes.style.display = "none";
js_notes.style.display = "none";
}
css_link.onclick = function() {
css_notes.style.display = "block";
html_notes.style.display = "none";
js_notes.style.display = "none";
}
javascript_link.onclick = () => {
js_notes.style.display = "block";
html_notes.style.display = "none";
css_notes.style.display = "none";
}
How can I refactor it using a for loop? My thinking was for each link clicked, display notes. But I am struggling to figure out how to display the notes div correctly that matches the link clicked. This is what I have started.
const links = document.querySelectorAll('.links')
for (const link of links) {
link.addEventListener('click', function() {
let ref = event.target.parentElement.id.replace('link','notes');
//replaces parent element with id 'notes'
const show = document.getElementById(ref);
//'show' div with new id
})
}

Welcome, fellow newbie! I've taken the liberty of writing the html and very minimal styling as well. This is my first attempt at an answer on stackoverflow.
Please note some features of the code I've added:
'links' class added to all links.
'notes' class added to all notes.
'data-notes' attribute added to all links (with the id of each link's respective notes)
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
</head>
<body>
<div class="outer">
<div id="html-link" data-notes="html-notes" class="links">
<p>html-link</p>
</div>
<div id="css-link" data-notes="css-notes" class="links">
<p>css-link</p>
</div>
<div id="javascript-link" data-notes="javascript-notes" class="links">
<p>javascript-link</p>
</div>
</div>
<div class="outer">
<div id="html-notes" class="notes">
<p>html-notes</p>
</div>
<div id="css-notes" class="notes">
<p>css-notes</p>
</div>
<div id="javascript-notes" class="notes">
<p>javascript-notes</p>
</div>
</div>
<style>
.links {
cursor: pointer;
background: green;
color: white;
padding: 1rem;
margin: 1rem;
}
.notes {
display: none;
background: blue;
color: white;
padding: 1rem;
margin: 1rem;
}
.outer {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-around;
margin: 2rem 0;
}
</style>
<script>
const links = document.querySelectorAll('.links');
const notes = document.querySelectorAll('.notes');
for (const link of links) {
link.onclick = function () {
for (const note of notes) {
if (note.id == link.dataset.notes) {
note.style.display = "block";
} else {
note.style.display = "none";
}
}
}
}
</script>
</body>
</html>

Related

trying to show re render the page when i click on the show details button

Hello guys i am new to this i am trying to re render my page any time i click on the show details buttons so i can show the name, height and gender of the sky wars characters i have tried initializing a variable to false and on click i tried changing the value to true but it did not work. please here is my code.
const containerEl = document.getElementById("container");
const list = document.createDocumentFragment();
const images = [
"https://oyster.ignimgs.com/mediawiki/apis.ign.com/star-wars-episode-7/2/2d/Luke.jpg?width=1280",
"https://images.immediate.co.uk/production/volatile/sites/3/2019/10/EP9-FF-001686-336e75b.jpg?quality=90&resize=980,654",
"https://hips.hearstapps.com/digitalspyuk.cdnds.net/17/07/1487160686-r2-d2.jpg",
"https://lumiere-a.akamaihd.net/v1/images/darth-vader-main_4560aff7.jpeg?region=0%2C67%2C1280%2C720",
"https://www.costumerealm.com/wp-content/uploads/2019/12/51G4Jox9MlL._SX466_.jpg",
"https://static.wikia.nocookie.net/starwars/images/e/eb/OwenCardTrader.png/revision/latest?cb=20171108050140",
"https://static.wikia.nocookie.net/fanmade-works/images/8/8d/Beru_Lars.png/revision/latest/scale-to-width/360?cb=20200317025929",
"https://static.wikia.nocookie.net/star-wars-canon-extended/images/2/23/R5.jpg/revision/latest?cb=20160123232521",
"https://static.wikia.nocookie.net/starwars/images/0/00/BiggsHS-ANH.png/revision/latest?cb=20130305010406",
"https://media.gq.com/photos/622919842677fb88bf480855/16:9/w_2143,h_1205,c_limit/Screen%20Shot%202022-03-09%20at%204.15.50%20PM.png"
]
const getData = async () => {
const res = await fetch("https://swapi.dev/api/people");
const resData = await res.json();
const result = resData.results;
console.log(result)
main(result)
}
getData();
const main = (data) => {
let isVisible = false;
containerEl.innerHTML = "";
data.map(({ gender, height, name }, i) => {
const starWars = `
<img class="images" src=${images[i]}/>
<button id="btn" class="btn">Show Details</button>
<h1 class="starwars">${isVisible ? name : ""}</h1>
<h3>${isVisible ? gender : ""}</h3>
<h3>${isVisible ? height : ""}</h3>
`;
const item = document.createElement("div");
item.classList.add("items")
item.innerHTML = starWars
const btn = item.querySelector(".btn");
btn.addEventListener("click", () => {
isVisible = true
})
list.appendChild(item)
})
containerEl.append(list)
}
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/index.css" >
<title>Star Wars</title>
</head>
<body>
<!-- Write your implementation here -->
<div id="container" class="container">
</div>
<script src="./script/index.js"></script>
</body>
</html>
This approach is not possible. The string literals, such as ${isVisible ? name : ""} are evaluated at the time that your template item is created, so since you've set the isVisible is false, it will only ever produce an empty string.
Instead, generate your string template with the values and then use a class to toggle the visibility of the details.
const containerEl = document.getElementById("container");
const images = [
"https://oyster.ignimgs.com/mediawiki/apis.ign.com/star-wars-episode-7/2/2d/Luke.jpg?width=1280",
"https://images.immediate.co.uk/production/volatile/sites/3/2019/10/EP9-FF-001686-336e75b.jpg?quality=90&resize=980,654",
"https://hips.hearstapps.com/digitalspyuk.cdnds.net/17/07/1487160686-r2-d2.jpg",
"https://lumiere-a.akamaihd.net/v1/images/darth-vader-main_4560aff7.jpeg?region=0%2C67%2C1280%2C720",
"https://www.costumerealm.com/wp-content/uploads/2019/12/51G4Jox9MlL._SX466_.jpg",
"https://static.wikia.nocookie.net/starwars/images/e/eb/OwenCardTrader.png/revision/latest?cb=20171108050140",
"https://static.wikia.nocookie.net/fanmade-works/images/8/8d/Beru_Lars.png/revision/latest/scale-to-width/360?cb=20200317025929",
"https://static.wikia.nocookie.net/star-wars-canon-extended/images/2/23/R5.jpg/revision/latest?cb=20160123232521",
"https://static.wikia.nocookie.net/starwars/images/0/00/BiggsHS-ANH.png/revision/latest?cb=20130305010406",
"https://media.gq.com/photos/622919842677fb88bf480855/16:9/w_2143,h_1205,c_limit/Screen%20Shot%202022-03-09%20at%204.15.50%20PM.png"
]
async function getData () {
const res = await fetch("https://swapi.dev/api/people");
const resData = await res.json();
return resData.results;
}
async function main () {
const data = await getData();
containerEl.innerHTML = "";
const list = document.createElement("ul")
data.map(({ gender, height, name }, i) => {
const starWars = `
<img class="images" src=${images[i]}/>
<button id="btn" class="btn">Show Details</button>
<div class="details">
<h2 class="starwars">${name}</h2>
<h3>${gender}</h3>
<h3>${height}</h3>
</div>
`;
const item = document.createElement("li");
item.classList.add("item", "hidden")
item.innerHTML = starWars
const btn = item.querySelector(".btn");
btn.addEventListener("click", toggleVisibility)
list.appendChild(item)
})
containerEl.append(list)
}
main()
function toggleVisibility(event) {
const el = event.target.closest('.item')
el.classList.toggle("hidden")
}
img {
width: 100%;
}
ul {
padding: 0;
margin: 0;
list-style-type: none;
display: grid;
gap: 1rem;
}
li {
border: 2px solid #ccc;
border-radius: .5rem;
overflow: hidden;
}
button {
font-weight: bold;
border: 0;
background-color: #222;
padding: .5rem .75rem;
color: white;
}
.item {
display: grid;
width: 25rem;
margin: auto;
}
.details {
padding: 1rem;
}
.hidden .details {
display: none;
}
<div id="container" class="container"></div>

Can a function be inside another function?

I am working on a library project but my function called changeColor inside the readStatus function does not appear to be working.
I've tried separating it but having two event listeners on the same button does not appear to work. My goal is for readStatus function to allow a user to update the status of a book from no to yes when finished with the book.
Likewise, I want to change the background color of the div (class: card) when yes to be green and no to be red.
Can anyone tell me what I'm doing wrong?
let myLibrary = [];
function Book(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
function addBookToLibrary(title, author, pages, read) {
let book = new Book(title, author, pages, read);
myLibrary.push(book);
displayOnPage();
}
function displayOnPage() {
const books = document.querySelector(".books");
const removeDivs = document.querySelectorAll(".card");
for (let i = 0; i < removeDivs.length; i++) {
removeDivs[i].remove();
}
let index = 0;
myLibrary.forEach((myLibrarys) => {
let card = document.createElement("div");
card.classList.add("card");
books.appendChild(card);
for (let key in myLibrarys) {
let para = document.createElement("p");
para.textContent = `${key}: ${myLibrarys[key]}`;
card.appendChild(para);
}
let read_button = document.createElement("button");
read_button.classList.add("read_button");
read_button.textContent = "Read ";
read_button.dataset.linkedArray = index;
card.appendChild(read_button);
read_button.addEventListener("click", readStatus);
let delete_button = document.createElement("button");
delete_button.classList.add("delete_button");
delete_button.textContent = "Remove";
delete_button.dataset.linkedArray = index;
card.appendChild(delete_button);
delete_button.addEventListener("click", removeFromLibrary);
function removeFromLibrary() {
let retrieveBookToRemove = delete_button.dataset.linkedArray;
myLibrary.splice(parseInt(retrieveBookToRemove), 1);
card.remove();
displayOnPage();
}
function readStatus() {
let retrieveBookToToggle = read_button.dataset.linkedArray;
Book.prototype = Object.create(Book.prototype);
const toggleBook = new Book();
if (myLibrary[parseInt(retrieveBookToToggle)].read == "yes") {
toggleBook.read = "no";
myLibrary[parseInt(retrieveBookToToggle)].read = toggleBook.read;
} else if (myLibrary[parseInt(retrieveBookToToggle)].read == "no") {
toggleBook.read = "yes";
myLibrary[parseInt(retrieveBookToToggle)].read = toggleBook.read;
}
let colorDiv = document.querySelector(".card");
function changeColor() {
for (let i = 0; i < length.myLibrary; i++) {
if (myLibrary[i].read == "yes") {
colorDiv.style.backgroundColor = "green";
} else if (myLibrary[i].read == "no") {
colorDiv.style.backgroundColor = "red";
}
}
}
displayOnPage();
}
index++;
});
}
let add_book = document.querySelector(".add-book");
add_book.addEventListener("click", popUpForm);
function popUpForm() {
document.getElementById("data-form").style.display = "block";
}
function closeForm() {
document.getElementById("data-form").style.display = "none";
}
let close_form_button = document.querySelector("#close-form");
close_form_button.addEventListener("click", closeForm);
function intakeFormData() {
let title = document.getElementById("title").value;
let author = document.getElementById("author").value;
let pages = document.getElementById("pages").value;
let read = document.getElementById("read").value;
if (title == "" || author == "" || pages == "" || read == "") {
return;
}
addBookToLibrary(title, author, pages, read);
document.getElementById("data-form").reset();
}
let submit_form = document.querySelector("#submit-form");
submit_form.addEventListener("click", function (event) {
event.preventDefault();
intakeFormData();
});
* {
margin: 0;
padding: 0;
background-color: rgb(245, 227, 205);
}
.books {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
text-align: center;
margin: 20px;
gap: 10px;
}
.card {
border: 1px solid black;
border-radius: 15px;
padding: 10px;
}
.forms {
display: flex;
flex-direction: column;
align-items: center;
}
form {
margin-top: 20px;
}
select,
input[type="text"],
input[type="number"] {
width: 100%;
box-sizing: border-box;
}
.buttons-container {
display: flex;
margin-top: 10px;
}
.buttons-container button {
width: 100%;
margin: 2px;
}
.add-book {
margin-top: 20px;
}
#data-form {
display: none;
}
.read_button {
margin-right: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>Document</title>
</head>
<body>
<div class="container">
<div class="forms">
<button class="add-book">Add Book To Library</button>
<div class="pop-up">
<form id="data-form">
<div class="form-container">
<label for="title">Title</label>
<input type="text" name="title" id="title" />
</div>
<div class="form-container">
<label for="author">Author</label>
<input type="text" name="author" id="author" />
</div>
<div class="form-container">
<label for="pages">Pages</label>
<input type="number" name="pages" id="pages" />
</div>
<div class="form-container">
<label for="read">Read</label>
<select name="read" id="read">
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div class="buttons-container">
<button type="submit" id="submit-form">Submit Form</button>
<button type="button" id="close-form">Close Form</button>
</div>
</form>
</div>
</div>
<div class="books"></div>
</div>
<script src="script.js"></script>
</body>
</html>
A couple things needed.
First, you should put the readStatus and removeFromLibrary functions outside of the foreach loop.
Then I think you are wanting changeColor to run whenever readStatus is run. Either put the changeColor code directly inside the readStatus or put changeColor() inside readStatus.
I think you want the Book to not be a function but a class.

how to save toogle class with localstorage. so can someone check what's wrong with this code

if( localStorage.getItem("color") == "black" ) {
{
var element = document.getElementById("body");
element.classList.toggle("bdark");
}
{
var element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
var element = document.getElementById("sh");
element.classList.toggle("shh");
}
}
function myFunction() {
{
var element = document.getElementById("body");
element.classList.toggle("bdark");
}
{
var element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
var element = document.getElementById("sh");
element.classList.toggle("shh");
}
var hs = document.getElementById("hs");
var color;
if(localStorage.getItem("color") == "black") {
color = "black";
localStorage.setItem("color",color)
}
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body id="body" class="light">
<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>
<button id="button" onclick="myFunction()">Try it</button>
<div id="aaas">
<div id="sh" class="sh">☾</div>
<div id="hs" class="hs">☀</div>
</div>
</body>
</html>
i want this code to onclick toggle class and when i refresh the page those toggled class remain same as they were before reloading the page with localstorage. so can someone check what's wrong with this code. help me with something similar/alternative to this one. thanks for reading this.
Details:-
i want this code to work as (onclick class change + saved with cokies/localstorage/or anything) so whenever i refresh or reopen the page it would be same class as it was when i left. or some alternative code that works same.
I fixed your code
if( localStorage.getItem("color") == "black" ) {
{
let element = document.getElementsByTagName("body");
element.classList.toggle("bdark");
}
{
let element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
let element = document.getElementById("sh");
element.classList.toggle("shh");
}
}
function myFunction() {
{
let element = document.getElementsByTagName("body");
element.classList="bdark";
}
{
let element = document.getElementById("theader");
element.classList="hdark";
}
{
let element = document.getElementById("sh");
element.classList="shh";
}
{
let hs = document.getElementById("hs");
}
let color;
if(localStorage.getItem("color") != "black") {
color = "black";
localStorage.setItem("color", color)
}
}
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>
<button id="button" onclick="myFunction()">Try it</button>
<div id="aaas">
<div id="sh" class="sh">☾</div>
<div id="hs" class="hs">☀</div>
</div>

JavaScript Function

Hello everybody I have this code that I have made alone.
function appearafter() {
document.getElementById("buttonappear").style.display = "block";
document.getElementById("button").style.display = "block";
document.getElementById("hinzufuegen").style.display = "none";
function myFunction() {
var itm = document.getElementById("myList2").lastChild;
var cln = itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
function allFunction() {
myFunction();
appearafter();
}
#button {
display: none;
}
#buttonappear {
display: none;
}
#test {
width: 300px;
height: 300px;
background-color: red;
}
<!DOCTYPE html>
<html>
<body>
<button id="hinzufuegen" onclick="allFunction()">ADD</button>
<div id="myList1">
<button id="button" onclick="">DELETE</button>
<div id="myList2">
<div id="test">
</div>
</div>
</div>
<button onclick="allFunction()" id="buttonappear">ADD</button>
</body>
</html>
What I want to make is that the red square whenever you are clicking on the ADD button it will be a clone and when you click on the DELETED button that the clone is deleted. Can somebody help me, please?
In addition to missing } as was mentioned in the comments, there was a not-so-obvious problem with finding the <div> to clone. The lastChild was actually a text node containing the \n (newline), after the <div>. It's better to search for <div> by tag:
var itm = document
.getElementById('myList2')
.getElementsByTagName('div')[0];
Since there's only one <div> we can use the zero index to find this first and only one.
And for delete function you can use a similar approach and get the last <div> and remove it.
function appearafter() {
document.getElementById("buttonappear").style.display = "block";
document.getElementById("button").style.display = "block";
document.getElementById("hinzufuegen").style.display = "none";
}
function myFunction() {
var itm = document.getElementById("myList2").getElementsByTagName("div")[0];
var cln = itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
function deleteFunction() {
var list1 = document.getElementById("myList1");
var divs = Array.from(list1.getElementsByTagName("div"));
// If the number of divs is 3, it means we're removing the last
// cloned div, hide the delete button.
if (divs.length === 3) {
document.getElementById("button").style.display = "none";
}
var lastDivToDelete = divs[divs.length - 1];
list1.removeChild(lastDivToDelete);
}
function allFunction() {
myFunction();
appearafter();
}
#button {
display: none;
}
#buttonappear {
display: none;
}
#test {
/* make it smaller so it's easier to show in a snippet */
width: 30px;
height: 30px;
background-color: red;
}
<button id="hinzufuegen" onclick="allFunction()">ADD</button>
<div id="myList1">
<button id="button" onclick="deleteFunction()">DELETE</button>
<div id="myList2">
<div id="test"></div>
</div>
</div>
<button onclick="allFunction()" id="buttonappear">ADD</button>

Time for populating a UI dynamically increases linearly, with each try?

Requirement:
User will enter "Number of Containers" and "Number of Controls"
Random input elements (numeric, checkbox, etc) will be created and equally distributed among the containers.
When user clicks on "Create" again, the input elements shown in the UI will be deleted and new set of random input elements will be populated again.
Issue:
Every time I create new set of input elements, the time taken for creating increases linearly up to a point then decreases little and increases again
I use the below code to empty the div that accommodates the containers and create input elements
Emptying the overall div
node.innerHTML = ""
Creating a numeric control with label
function createNumber(display) {
let controlWrap = document.createElement("div");
let label = document.createElement("label")
let control = document.createElement("input")
control.type = "number";
label.append("Numeric Input");
label.append(control);
controlWrap.append(label);
controlWrap.style.display = display;
controlWrap.classList.add("ctrl");
return controlWrap;
}
Find the entire code below,
//Constands
const CTRL_DISPLAY_TYPE = "block"
//Selection
const numOfContainers = document.querySelector("#numOfContainers");
const numOfControls = document.querySelector("#numOfControls");
const createContainersBtn = document.querySelector("#create");
const containerWrapper = document.querySelector(".containerWrapper");
const controlHeading = document.querySelectorAll(".ctrlHeading");
//Event Listeners
createContainersBtn.addEventListener("click",createContainers);
controlHeading.forEach(element => element.addEventListener("click"),expandControl);
//Support-functions
function createControl(newControlContainer){
let newControlWrapper = document.createElement("div")
newControlWrapper.classList.add("ctrlWrapper");
let newControl = createNumber(CTRL_DISPLAY_TYPE);
newControlWrapper.appendChild(newControl);
newControlContainer.appendChild(newControlWrapper);
}
function createNumber(display){
let controlWrap = document.createElement("div");
let label = document.createElement("label")
let control = document.createElement("input")
control.type = "number";
label.append("Numeric Input");
label.append(control);
controlWrap.append(label);
controlWrap.style.display = display;
controlWrap.classList.add("ctrl");
return controlWrap;
}
function calculateControlPerContainer(numOfContainers,numOfControls,maxLimit){
let controlsPerContainer = []
let pendingControls = numOfControls%numOfContainers
let controlPerContainerNum = Math.floor(numOfControls/numOfContainers)
for (let i=0;i<numOfContainers;i++){
if (pendingControls>0){
newControlsPerContainer=controlPerContainerNum+1;
controlsPerContainer.push(newControlsPerContainer);
--pendingControls;
}
else{
controlsPerContainer.push(controlPerContainerNum);
}
}
return controlsPerContainer
}
function expandControl(event){
const control = event.currentTarget.nextElementSibling;
if (control.style.display === "none"){
control.style.display = "block";
}
else {
control.style.display = "none"
}
}
//utility-functions
function removeChild(node){
while(node.firstChild){
node.removeChild(node.firstChild);
}
}
function clearNodeData(node){
node.innerHTML = ""
}
//main-Functions
function createContainers(event){
console.time("Deleting controls");
const controlsPerContainer = calculateControlPerContainer(parseInt(numOfContainers.value),parseInt(numOfControls.value));
clearNodeData(containerWrapper);
//removeChild(containerWrapper);
console.timeEnd("Deleting controls");
console.time("populating controls");
controlsPerContainer.forEach(num=>{
let newControlContainer = document.createElement("div")
newControlContainer.classList.add("ctrlContainer");
for(let j=0;j<num;j++){
createControl(newControlContainer);
}
containerWrapper.appendChild(newControlContainer);
})
console.timeEnd("populating controls");
}
* {
box-sizing: border-box;
}
html, body {
margin: 0;
padding: 0;
border: 0;
height:100%
}
.containerWrapper{
display:flex;
flex-direction: row;
height: 90%;
}
.ctrlContainer{
/* flex-grow:1; */
flex-shrink: 0;
border-style: solid;
border-width: 0.5px;
margin:0 2px;
flex-basis: calc(25% - 4px);
align-items: stretch;
display:flex;
flex-direction: column;
overflow: auto;
}
.ctrlWrapper{
border-style: solid;
border-width: .5px;
margin:2px
}
.ctrlHeading{
display:block;
width: 100%;
text-align: left;
border: 0;
}
.ctrl{
display:none;
}
<!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>Dynamic Controls</title>
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<label for="numOfContainers">Number of Containers</label>
<input type="number" id="numOfContainers" name="numOfContainers" min="1" max="500" value="100">
<label for="numOfControls">Number of Controls</label>
<input type="number" id="numOfControls" name="numOfControls" min="1" max="1500" value="1500"><br>
<button id="create">Create</button>
<div class="containerWrapper">
<!-- <div class="ctrlContainer">
<div class="ctrlWrapper">
<button class="ctrlHeading">Checkbox</button>
<input class="ctrl" type="checkbox">
</div>
<div class="ctrlWrapper">
<button class="ctrlHeading">Checkbox</button>
<input class="ctrl" type="checkbox">
</div>
</div>
<div class="ctrlContainer">2</div>
<div class="ctrlContainer">3</div> -->
</div>
<script type="module" src="scripts/MainBackup.js"></script>
</body>
</html>
I tried analyzing using chrome developer tools and could see "append" function is taking more total time. Please let me know if I am doing something wrong in deleting or adding controls and how to avoid this time build up with every run.
More Information after some more exploration:
I am seeing this behavior only in chrome. In firefox and edge, there is no time buildup.
Firefox:
This occurs only in my system. Others are not able to replicate.
The time build-up occurs in portion of code in which I append inputs to the label to assign it to the input without using id. If I directly append the input to container, the time buildup doesn't happen

Categories