HTML Javascript image slider - adding slide animation/ - javascript

I made an image slider that work, but now I'm trying to add an animation effect to it, and I believe JavaScript may be the answer for that.
I'm trying to add the possibility to click the arrow buttons and have the image slide left or right depending on whether the left or right arrow is being clicked.
Is that possible.
Here is my HTML file.
<body>
<div id="hcg-slider-1" class="hcg-slider">
<div class="hcg-slide-container">
<div class="hcg-slider-body">
<a class="hcg-slides animated" style="display:block">
<span class="hcg-slide-number">1/5</span>
<img src="https://www.html-code-generator.com/images/slider/1.png" alt="image 1">
<span class="hcg-slide-text">image 1</span>
</a>
</div>
<a class="hcg-slide-prev" href="#">❮</a>
<a class="hcg-slide-next" href="#">❯</a>
</div>
<div class="hcg-slide-dot-control"></div>
</div>
<script>
(function(){
//If you want to include more images, add the link name and URL of the image in the array list below.
let images_list = [
{"url":"photos/headers/ABY-header.png",
"link":"",
"name": "just text"},
{"url":"photos/headers/TMN-header.png",
"link":"",
"name": "just text"},
{"url":"photos/headers/TW-header.png",
"link":"",
"name": "just text"},
{"url":"photos/headers/NY-header.png",
"link":"",
"name": "just text"},
];
let slider_id = document.querySelector("#hcg-slider-1");
// append all images
let dots_div = "";
let images_div = "";
for (let i = 0; i < images_list.length; i++) {
// if no link without href="" tag
let href = (images_list[i].link == "" ? "":' href="'+images_list[i].link+'"');
images_div += '<a'+href+' class="hcg-slides animated"'+(i === 0 ? ' style="display:block"':'')+'>'+
'<span class="hcg-slide-number">'+(i+1)+'/'+images_list.length+'</span>'+
'<img src="'+images_list[i].url+'" alt="'+images_list[i].name+'">'+
'<span class="hcg-slide-text">'+images_list[i].name+'</span>'+
'</a>';
dots_div += '<span class="hcg-slide-dot'+(i === 0 ? ' dot-active':'')+'" data-id="'+i+'"></span>';
}
slider_id.querySelector(".hcg-slider-body").innerHTML = images_div;
slider_id.querySelector(".hcg-slide-dot-control").innerHTML = dots_div;
let slide_index = 0;
let images = slider_id.querySelectorAll(".hcg-slides");
let dots = slider_id.querySelectorAll(".hcg-slide-dot");
let prev_button = slider_id.querySelector(".hcg-slide-prev");
let next_button = slider_id.querySelector(".hcg-slide-next");
function showSlides() {
if (slide_index > images.length-1) {
slide_index = 0;
}
if (slide_index < 0) {
slide_index = images.length-1;
}
for (let i = 0; i < images.length; i++) {
images[i].style.display = "none";
dots[i].classList.remove("dot-active");
if (i == slide_index) {
images[i].style.display = "block";
dots[i].classList.add("dot-active");
}
}
}
prev_button.addEventListener("click", function(event) {
event.preventDefault();
slide_index--;
showSlides();
}, false);
next_button.addEventListener("click", function(event){
event.preventDefault();
slide_index++;
showSlides();
}, false);
function dot_click(event) {
slide_index = event.target.dataset.id;
showSlides();
}
for (let i = 0; i < dots.length; i++) {
dots[i].addEventListener("click", dot_click, false);
}
})();
</script>

I managed to add a sliding animation using JavaScript. Here's a good guide as to how it can be done.
https://www.cssscript.com/animated-image-slider/
This is the code I added.
const content = document.querySelector(".content");
const slider = document.querySelector(".slider");
const sliderImage = Array.from(document.querySelectorAll(".slider-image"));
const btnChevron = document.querySelectorAll(".btn-chevron");
let i = 0;
let reset = (container, clase) => {
container.forEach(item => item.classList.remove(clase));
}
let createInfo = text => {
const sliderInfo = document.createElement("p");
sliderInfo.className = "slider-info";
sliderInfo.textContent = text;
content.appendChild(sliderInfo);
};
let createIndicators = () => {
const container = document.createElement("div");
container.className = "indicator";
content.appendChild(container)
sliderImage.forEach(image => {
let indicator = document.createElement("p");
indicator.textContent = sliderImage.indexOf(image) + 1;
container.appendChild(indicator);
})
}
let Image = (index) => {
const indicators = document.querySelectorAll('.indicator p');
const sliderInfo = document.querySelector('.slider-info');
sliderImage[index].classList.add('slider-image-active');
reset(indicators, 'indicator-active');
indicators[i].classList.add('indicator-active');
if (content.hasElement(".slider-info")) return sliderInfo.textContent = sliderImage[index].dataset.info;
createInfo(sliderImage[index].dataset.info);
}
let setPosition = (index) => {
let width = sliderImage[index].getBoundingClientRect().width;
slider.style.transform = `translateX(-${width * index}px)`;
}
let moveImage = () => {
if (i === sliderImage.length) {
i = 0; // Si el contador ya llego al ultimo item, lo manda al primer item.
} else if (i == -1) {
i = sliderImage.length - 1; // Si llego al primero lo manda hasta el ultimo.
}
reset(sliderImage, 'slider-image-active');
setPosition(i);
Image(i);
};
btnChevron.forEach(btn => {
btn.addEventListener('click', () => {
if (btn.dataset.action == "right") {
i++;
return moveImage();
}
i--;
return moveImage();
})
})
createIndicators();
Image(i);

Related

Carousel with dynamic images

Hello I want to implement a carousel in Java Script.
When I launch the page the image loads very strangely and the bootstrap carousel does not work. Do I need to import something to make it work? If I make it static in HTML it works. However the task is to load the images with iiif. Also, there would be way too many images to make it static. Also, I would like to have a filter function implemented which only works dynamically.
Can someone help me how to implement the carousel?
Here is all the JS code:
'import bootstrap.js'
function changeIIIFInformation(iiif, size, quality) {
var index = iiif.indexOf('full')
iiif = iiif.substring(0, index)
iiif += "full/"
iiif += "pct:" +size.toString() +"/"
iiif += "0/"
iiif += quality +".jpg"
return iiif
}
function search_period(period, max_num, offset) {
var count = 0;
var link = ""
var div = document.createElement('div')
var div1 = document.createElement ('div')
var a=document.createElement('a')
var span1=document.createElement('span')
var span2=document.createElement('span')
a.setAttribute('class','carousel-control-prev')
a.setAttribute('href','#carouselExampleControls')
a.setAttribute('role','button')
a.setAttribute('data-slide','prev')
span1.setAttribute('class','carousel-control-prev-icon')
span1.setAttribute('aria-hidden', 'true')
span2.setAttribute('class','sr-only')
span2.innerHTML = 'Previous'
div.setAttribute('class', 'carousel slide')
div.setAttribute('data-ride', 'carousel')
div.setAttribute('id', 'carouselExampleControls')
div1.setAttribute('class','carousel-inner')
var h2 = document.createElement('h2')
var iiif = ""
h2.innerHTML = period
document.body.appendChild(h2)
const keys = Object.keys(urls);
for(const elem of keys) {
var label = urls[elem].label
for(const el of urls[elem].variants) {
if(el.label.includes('front')) {
iiif = el.url
}
}
if(!periods.hasOwnProperty(label)) {
continue;
}
if(periods[label] != period) {
continue;
}
if(count < offset) {
count+=1
continue
}
var div2= document.createElement ('div')
div2.setAttribute('class','carousel-item active')
link = changeIIIFInformation(iiif, 10, "default")
var figure = document.createElement('figure')
var figcaption = document.createElement('figcaption')
var linkToImage = document.createElement('a')
//linkToImage.setAttribute('#image', label)
linkToImage.setAttribute('href', 'annotator#'+label)
linkToImage.innerHTML = label
figcaption.appendChild(linkToImage)
var image = document.createElement('img')
image.setAttribute("id", "myimg");
image.setAttribute('src', link)
image.setAttribute('class','d-block w-100')
// figure.appendChild(image)
// figure.appendChild(figcaption)
div.appendChild(div1)
div.appendChild(a)
div1.appendChild(div2)
a.appendChild(span1)
a.appendChild(span2)
div2.appendChild(image)
figure.setAttribute("id", "myFigure");
count += 1;
if(count >= max_num+offset) {
break;
}
}
document.body.appendChild(div)
}
function clear_dom() {
var elements = document.getElementsByTagName('div')
var headings = document.getElementsByTagName('h2')
var buttons = document.getElementsByTagName('button')
while(buttons.length > 0) {
buttons.item(0).remove()
}
while(elements.length > 0) {
elements.item(0).remove()
}
while(headings.length > 0) {
headings.item(0).remove()
}
}
function show_initial_load() {
search_period('Ur III (ca. 2100-2000 BC)', )
}
function show_filtered(selected, offset) {
clear_dom()
search_period(selected, 10, offset)
var previous = document.createElement('button')
if(offset-10 < 0) {
previous.onclick = () => show_filtered(selected, 0)
} else {
previous.onclick = () => show_filtered(selected, offset-10)
}
previous.innerHTML = 'Previous'
document.body.appendChild(previous)
var next = document.createElement('button')
next.onclick = () => show_filtered(selected, offset+10)
next.innerHTML = 'More'
document.body.appendChild(next)
}
function update_view() {
var selected = document.getElementById('perriod-select').value
clear_dom()
if(selected == '') {
show_initial_load()
} else {
show_filtered(selected, 0)
}
}

Condition pagination javascript

My problem is When I Select page 2 i want to hide element 0-4 and show 5-8 but when i click 0-4 not hide
I thing because My if condition can some one help me about if condition ? or another way to do ?
and can i limit show data when load first time ?
let data = Array.from(Array(15).keys()).map(item => ({ topic: `Header ${item}`, detail: `Detail ${item}`}))
let tourlek = document.querySelector('#tourlek')
let pagination = document.querySelector('#pagination')
let itemPage = document.getElementsByTagName('item-page')
let item = data.length
let page = 1
let limit = 4
let limitFn = Math.ceil(item / limit)
for (let i = 0; i < item; i++) {
let div = document.createElement('div')
div.textContent = `${data[i].topic} - ${data[i].detail}`
div.classList = 'pd'
tourlek.appendChild(div)
}
for (let i = page; i <= limitFn; i++){
let a = document.createElement('a')
a.textContent = `P:${page}`
// addEventListener onPage function when click
a.addEventListener('click', onPage)
a.setAttribute('data-page', page)
page = page + 1
pagination.appendChild(a).href = 'javascript:void(0)'
}
function onPage (event) {
let itemDom = document.querySelectorAll('.pd')
let currentPage = event.target.getAttribute('data-page')
for (let i = 0; i < itemDom.length; i++) {
if (i >= limit * currentPage ) {
itemDom[i].style.display = 'none'
// console.log(0 < limit * currentPage )
} else {
itemDom[i].style.display = ''
}
}
console.log(event.target.getAttribute('data-page'))
}
a {
margin: 0 10px;
}
<div>
<div id="tourlek"></div>
<div id="pagination"></div>
</div>
To start on page 1 just do
document.querySelector("[data-page='1']").click();
To find the range
const lim = currentPage * limit
for (let i = 0; i < itemDom.length; i++) {
itemDom[i].hidden = i > lim || i < lim -limit
}
let data = Array.from(Array(15).keys()).map(item => ({
topic: `Header ${item}`,
detail: `Detail ${item}`
}))
let tourlek = document.querySelector('#tourlek')
let pagination = document.querySelector('#pagination')
let itemPage = document.getElementsByTagName('item-page')
let currentPage = 1;
let item = data.length
let page = 1
let limit = 4
let limitFn = Math.ceil(item / limit)
let lastPage = 1;
for (let i = 0; i < item; i++) {
let div = document.createElement('div')
div.textContent = `${data[i].topic} - ${data[i].detail}`
div.classList = 'pd'
tourlek.appendChild(div)
}
document.querySelector(".box").addEventListener("click", onPage)
for (let i = page; i <= limitFn; i++) {
let a = document.createElement('a')
a.textContent = `P:${page}`
a.setAttribute('data-page', page)
page = page + 1
pagination.appendChild(a).href = 'javascript:void(0)'
}
document.querySelector("[data-page='1']").click();
function onPage(event) {
const tgt = event.target;
if (tgt.id === "arwL") {
const p = currentPage - 1
if (p===0) return
document.querySelector(`[data-page='${p}']`).click()
return;
}
if (tgt.id === "arwR") {
const p = +currentPage + 1
if (p>=data.length) return
document.querySelector(`[data-page='${p}']`).click()
return;
}
let itemDom = document.querySelectorAll('.pd')
currentPage = event.target.dataset.page;
const lim = currentPage * limit
for (let i = 0; i < itemDom.length; i++) {
itemDom[i].hidden = i > lim || i < lim - limit
}
}
a {
padding: 0 10px;
}
.box {
display: flex;
}
#arwL,
#arwR {
cursor: pointer
}
<div>
<div id="tourlek"></div>
<div class='box'>
<div id="arwL"><</div>
<div id="pagination"></div>
<div id="arwR">></div>
</div>
</div>

clearInterval seems to be stopping unrelated code

let questions = [
{
title: "Commonly used data types DO NOT include:",
choices: ["strings", "booleans", "alerts", "numbers"],
answer: "alerts"
},
{
title: "The condition in an if / else statement is enclosed within ____.",
choices: ["quotes", "curly brackets", "parentheses", "square brackets"],
answer: "parentheses"
}
]
let main = document.getElementById('main');
let content = document.getElementById('content');
let title = document.getElementById('quiz-title');
let instr = document.getElementById('instructions');
let btn = document.getElementById('start-button');
let time = document.getElementById('time');
let h2;
let btns;
let newElement;
let correct;
let questionCounter;
let seconds;
const timer = () => {
time.textContent = seconds;
seconds--;
if (seconds < 0) {
clearInterval(timerStart);
questionCounter = 4;
}
}
var timerStart = setInterval(timer, 1000);
const startQuiz = () => {
title.style.display = 'none';
instr.style.display = 'none';
btn.style.display = 'none';
questionCounter = 0;
newElement = document.createElement('h2');
newElement.textContent = questions[questionCounter].title;
newElement.id = questionCounter;
content.appendChild(newElement);
questions[questionCounter].choices.forEach(function(choice) {
newElement = document.createElement('button');
newElement.textContent = choice;
newElement.setAttribute('class', 'btn btn-success btn-block');
newElement.id = choice;
content.appendChild(newElement);
})
seconds = 10;
timerStart;
};
const advanceQuestion = () => {
document.getElementById(`${questionCounter}-answered`).style.display = 'none';
questionCounter++;
if (questionCounter < 2) {
newElement = document.createElement('h2');
newElement.textContent = questions[questionCounter].title;
newElement.id = questionCounter;
content.appendChild(newElement);
questions[questionCounter].choices.forEach(function(choice) {
newElement = document.createElement('button');
newElement.textContent = choice;
newElement.setAttribute('class', 'btn btn-success btn-block');
newElement.id = choice;
content.appendChild(newElement);
})
} else {
newElement = document.createElement('h2');
newElement.textContent = 'Good job!';
content.appendChild(newElement);
newElement = document.createElement('p');
newElement.textContent = `Your score is ${time.innerHTML}`;
content.appendChild(newElement);
}
}
const checkAnswer = (Event) => {
if (questions[questionCounter].choices.indexOf(Event.target.id) == -1) {
return;
} else {
newElement = document.createElement('h4');
newElement.textContent = 'Answered';
newElement.id = `${questionCounter}-answered`;
content.appendChild(newElement);
}
h2 = document.getElementById(questionCounter)
h2.style.display = 'none';
for (let i = 0; i < questions[questionCounter].choices.length; i++) {
btns = document.getElementById(questions[questionCounter].choices[i]);
btns.style.display = 'none';
}
setTimeout(advanceQuestion, 1000);
}
btn.onclick = startQuiz;
document.onclick = checkAnswer;
main {
text-align: center;
}
section {
width: 80%;
margin: 0 auto;
}
.btn {
margin: 0.5rem 0;
}
#timer {
position: absolute;
top: 0;
right: 0;
}
<header>
<h6 id="high-scores">View Highscores</h6>
<h6 id="timer">Time: <span id="time">0</span></h6>
</header>
<main id="main">
<section id="content">
<h1 id="quiz-title">Coding Quiz Challenge</h1>
<p id="instructions">Try to answer the following code related questions within the time limit. Keep in mind that incorrect answers will penalize your score/time by ten seconds!</p>
<button id="start-button" type="button" class="btn btn-success">Begin Quiz</button>
</section>
</main>
I am new to JavaScript and have been tasked with writing a code quiz application (no jQuery allowed). The application works as follows: the questions are loaded one at a time as answered and a question counter is incremented as it goes. Once the question counter hits the threshold, the quiz ends and the score is displayed. I have added a timer and there is no issue if the quiz is finished within the time given but if the timer reaches 0, the whole application stops working after the clearInterval runs.
const timer = () => {
time.textContent = seconds;
seconds--;
if (seconds < 0) {
clearInterval(timerStart);
questionCounter = 4;
}
}
const timerStart = setInterval(timer, 1000);
The timer is set to 75 seconds in the calling function. The application advances based on the onclick method for what it's worth, and that seems to stop taking inputs after the clearInterval() call. I can post the rest of the code if needed but it is a bit verbose as I am new to this.
EDIT
const advanceQuestion = () => {
if (correct === false) {
document.getElementById(`${questionCounter}-incorrect`).style.display = 'none';
} else {
document.getElementById(`${questionCounter}-correct`).style.display = 'none';
}
questionCounter++;
if (questionCounter < 5) {
newElement = document.createElement('h2');
content.appendChild(newElement);
questions[questionCounter].choices.forEach(function(choice) {
newElement = document.createElement('button');
content.appendChild(newElement);
})
} else {
newElement = document.createElement('h2');
newElement.textContent = 'Good job!';
content.appendChild(newElement);
newElement = document.createElement('p');
newElement.textContent = `Your score is ${time.innerHTML}`;
content.appendChild(newElement);
}
const checkAnswer = (Event) => {
if (Event.target.id === questions[questionCounter].answer) {
newElement = document.createElement('h4');
newElement.textContent = 'Correct!';
content.appendChild(newElement);
} else {
newElement = document.createElement('h4');
newElement.textContent = 'Incorrect';
content.appendChild(newElement);
}
h2 = document.getElementById(questionCounter)
h2.style.display = 'none';
for (let i = 0; i < questions[questionCounter].choices.length; i++) {
btns = document.getElementById(questions[questionCounter].choices[i]);
btns.style.display = 'none';
}
setTimeout(advanceQuestion, 1000);
}
const startQuiz = () => {
title.style.display = 'none';
questionCounter = 0;
newElement = document.createElement('h2');
content.appendChild(newElement);
questions[questionCounter].choices.forEach(function(choice) {
newElement = document.createElement('button');
content.appendChild(newElement);
})
seconds = 10;
timerStart;
btn.onclick = startQuiz;
document.onclick = checkAnswer;

HTML Div Element turns to null when I'm accessing it a 2nd time?

Here are the relevant bits of the client-side code:
function simpsonsShow(forest) {
alert(document.getElementById("simpsons"));
var ind = simpsonsIndex(forest).toFixed(2); // simpsonsIndex is a function not shown here
document.getElementById("simpsons").innerHTML = "";
document.getElementById("simpsons").innerHTML =
document.getElementById("simpsons").innerHTML + ind;
}
document.addEventListener("DOMContentLoaded", function () {
document.querySelector("div#intro button").addEventListener("click", function clicked() {
document.getElementById("intro").style.display = "none";
document.getElementById("sim").style.display = "block";
document.getElementById("simpsons").style.display = "block";
let content = document.getElementById("inputForest").value;
let forest = forestGenerate(content);
const ind = simpsonsShow(forest);
let button = document.createElement("button");
button.appendChild(document.createTextNode("generate"));
button.addEventListener("click", function () {
forest = forestGenerate(content);
simpsonsShow(forest);
});
document.getElementById("sim").appendChild(button);
});
});
When that simpsonsShow function is ran a second time, all of a sudden document.getElementById("simpsons") becomes null even though upon first try, it's a proper HTML Div Element.
Here are the relevant parts of the HTML:
<head>
<script src="sim.js"></script>
</head>
<body>
<div id="content">
<div id="intro">
</div>
<div id="sim" class="hidden">
<h2>the current Simpson's Index is:
</h2>
<div id="simpsons">
</div>
</div>
</div><!--close id="content"-->
</body>
</html>
I've added the code snippet: The website works by pressing generate, then continually pressing generate. The error pops up once you press generate a 2nd time
function forestGenerate(content) {
const forest = [];
if (content.length === 0) {
const possible = ["", "🌲", "🌳", "🌴", "🌵", "🌶", "🌷", "🌸", "🌹", "🌺", "🌻", "🌼", "🌽", "🌾", "🌿", "🍀", "🍁", "🍂", "🍃"];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
}
else {
const possible = [...content, ""];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
}
for (let i = 0; i < forest.length; i++) {
let row = document.createElement("div");
let newContent = document.createTextNode(forest[i]);
row.appendChild(newContent);
row.addEventListener("click", function () {
row.style.backgroundColor = "grey";
row.setAttribute("pinned", "yes");
});
document.getElementById("sim").appendChild(row);
}
return forest;
}
function simpsonsShow(forest) {
const simpsonsIndex = forest =>
1 - Object.entries(
[...forest.join("")].reduce(
(counts, emoji) => ({ ...counts, [emoji]: (counts[emoji] || 0) + 1 }),
{}
)
).reduce(([top, bottom], [species, count]) => [top + (count * (count - 1)), bottom + count], [0, 0])
.reduce((sumLilN, bigN) => sumLilN / (bigN * (bigN - 1)))
alert(document.getElementById("simpsons"));
var ind = simpsonsIndex(forest).toFixed(2);
document.getElementById("simpsons").innerHTML = "";
document.getElementById("simpsons").innerHTML = document.getElementById("simpsons").innerHTML + ind;
}
document.addEventListener("DOMContentLoaded", function () {
let element = document.getElementById("sim");
element.classList.add("hidden");
let element1 = document.getElementById("pushtray");
element1.classList.add("hidden");
document.querySelector("div#intro button").addEventListener("click", function clicked() {
document.getElementById("intro").style.display = "none";
document.getElementById("sim").style.display = "block";
document.getElementById("simpsons").style.display = "block";
let content = document.getElementById("inputForest").value;
let forest = forestGenerate(content);
const ind = simpsonsShow(forest);
if (ind <= .7) {
let over = document.createElement("div");
let newContent = document.createTextNode("WARNING: Simpson's Index Dropped To" + simpsonsIndex);
over.appendChild(newContent);
document.getElementById("pushtray").appendChild(over);
document.getElementById("pushtray").style.zIndex = "100";
document.getElementById("pushtray").style.right = "50px";
document.getElementById("pushtray").style.position = "fixed";
document.getElementById("pushtray").style.display = "block";
}
let button = document.createElement("button");
button.appendChild(document.createTextNode("generate"));
button.addEventListener("click", function () {
const curr = document.getElementById("sim").querySelectorAll("div");
for (let i = 0; i < curr.length; i++) {
if (!curr[i].hasAttribute("pinned")) {
document.getElementById("sim").removeChild(curr[i]);
}
}
document.getElementById("sim").removeChild(button);
forest = forestGenerate(content);
simpsonsShow(forest);
document.getElementById("sim").appendChild(button);
});
document.getElementById("sim").appendChild(button);
});
});
<!doctype html>
<html>
<head>
<title>FOREST SIMULATOR</title>
<script src="sim.js"></script>
<link rel="stylesheet" href="base.css" type="text/css" media="screen" title="no title" charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Lato|Playfair+Display" rel="stylesheet" >
</head>
<link href="https://fonts.googleapis.com/css?family=Lato|Playfair+Display" rel="stylesheet">
<body>
<div id="content">
<h1>FOREST SIMULATOR</h1>
<style>
.hidden{
display:none;
}
</style>
<div id="intro">
starting forest (leave empty to randomize):
<br />
<textarea id="inputForest" name="inputForest" cols="16" rows="8"></textarea>
<br />
<button>generate</button>
</div>
<div id="sim" class="hidden">
<h2>the current Simpson's Index is:
</h2>
<div id="simpsons">
</div>
</div>
<div id="pushtray" class="overlay">
</div>
</div><!--close id="content"-->
</body>
</html>
#simpsons is a child of #sim. The problem is in this code here:
const curr = document.getElementById("sim").querySelectorAll("div");
for (let i = 0; i < curr.length; i++) {
if (!curr[i].hasAttribute("pinned")) {
document.getElementById("sim").removeChild(curr[i]);
}
}
It effectively removes all div children of #sim which don't have a pinned attribute. Try removing only divs after the first index, thereby keeping #simpsons (which is the first div inside #sim):
for (let i = 1; i < curr.length; i++) {
function forestGenerate(content) {
const forest = [];
if (content.length === 0) {
const possible = ["", "🌲", "🌳", "🌴", "🌵", "🌶", "🌷", "🌸", "🌹", "🌺", "🌻", "🌼", "🌽", "🌾", "🌿", "🍀", "🍁", "🍂", "🍃"];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
} else {
const possible = [...content, ""];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
}
for (let i = 0; i < forest.length; i++) {
let row = document.createElement("div");
let newContent = document.createTextNode(forest[i]);
row.appendChild(newContent);
row.addEventListener("click", function() {
row.style.backgroundColor = "grey";
row.setAttribute("pinned", "yes");
});
document.getElementById("sim").appendChild(row);
}
return forest;
}
function simpsonsShow(forest) {
const simpsonsIndex = forest =>
1 - Object.entries(
[...forest.join("")].reduce(
(counts, emoji) => ({ ...counts,
[emoji]: (counts[emoji] || 0) + 1
}), {}
)
).reduce(([top, bottom], [species, count]) => [top + (count * (count - 1)), bottom + count], [0, 0])
.reduce((sumLilN, bigN) => sumLilN / (bigN * (bigN - 1)))
var ind = simpsonsIndex(forest).toFixed(2);
document.getElementById("simpsons").innerHTML = "";
document.getElementById("simpsons").innerHTML = document.getElementById("simpsons").innerHTML + ind;
}
document.addEventListener("DOMContentLoaded", function() {
let element = document.getElementById("sim");
element.classList.add("hidden");
let element1 = document.getElementById("pushtray");
element1.classList.add("hidden");
document.querySelector("div#intro button").addEventListener("click", function clicked() {
document.getElementById("intro").style.display = "none";
document.getElementById("sim").style.display = "block";
document.getElementById("simpsons").style.display = "block";
let content = document.getElementById("inputForest").value;
let forest = forestGenerate(content);
const ind = simpsonsShow(forest);
if (ind <= .7) {
let over = document.createElement("div");
let newContent = document.createTextNode("WARNING: Simpson's Index Dropped To" + simpsonsIndex);
over.appendChild(newContent);
document.getElementById("pushtray").appendChild(over);
document.getElementById("pushtray").style.zIndex = "100";
document.getElementById("pushtray").style.right = "50px";
document.getElementById("pushtray").style.position = "fixed";
document.getElementById("pushtray").style.display = "block";
}
let button = document.createElement("button");
button.appendChild(document.createTextNode("generate"));
button.addEventListener("click", function() {
const curr = document.getElementById("sim").querySelectorAll("div");
for (let i = 1; i < curr.length; i++) {
if (!curr[i].hasAttribute("pinned")) {
document.getElementById("sim").removeChild(curr[i]);
}
}
document.getElementById("sim").removeChild(button);
forest = forestGenerate(content);
simpsonsShow(forest);
document.getElementById("sim").appendChild(button);
});
document.getElementById("sim").appendChild(button);
});
});
.hidden {
display: none;
}
<div id="content">
<h1>FOREST SIMULATOR</h1>
<div id="intro">
starting forest (leave empty to randomize):
<br />
<textarea id="inputForest" name="inputForest" cols="16" rows="8"></textarea>
<br />
<button>generate</button>
</div>
<div id="sim" class="hidden">
<h2>the current Simpson's Index is:
</h2>
<div id="simpsons">
</div>
</div>
<div id="pushtray" class="overlay">
</div>
</div>

What to do when looping repeats in 2 different areas

The code gets the values of the input and sends it to the textarea, but when you add more than one title the values are repeated in the result of the titles, for example, the DESCRIPTIONS of title 1 are the same as in title 2, why does this happen? and how to make it work without changing the purpose?
Run the code in codepen.io or jsfiddle.net
This is what happens:
This is what should happen:
function result() {
var inp2 = document.getElementsByName("inp2");
var titu = document.getElementsByName("titu");
var res = document.getElementById("result");
res.value = "";
if (titu[0]) {
for (var k = 0; k < titu.length; k++) {
if (titu[k].value.trim() != '') {
res.value += `<div>
<span>${titu[k].value.trim()}</span>
</div>
<ul>\n`;
for (var j = 0; j < inp2.length; j++) {
if (inp2[j].value.trim() != '') {
res.value += `<li>${inp2[j].value.trim()}</li>\n`;
}
}
}
}
}else {
console.log("test")
res.value += `<ul>\n`;
for (var l = 0; l < inp2.length; l++) {
if (inp2[l].value.trim() != '') {
res.value += `<li>${inp2[l].value.trim()}</li>\n`;
}
}
}
};
// -----------------------------------------
if (document.getElementById("add2")) {
let cont2 = 1;
document.getElementById("add2").onclick = function clone2() {
let container2 = document.getElementById("output2");
let tempLinha2 = document.querySelector('#template2');
let clone2 = document.importNode(tempLinha2.content, true);
const label2 = clone2.querySelector("label");
label2.htmlFor = cont2;
clone2.querySelector("input").className = cont2;
container2.appendChild(clone2);
cont2++;
};
document.getElementById("del2").onclick = function del2() {
document.querySelector('#output2 #linha2:last-child').remove();
};
}
// ---------------------------------------
if (document.getElementById("addtit")) {
let cont3 = 1;
document.getElementById("addtit").onclick = function clone3() {
let container3 = document.getElementById("output2");
let tempLinha3 = document.querySelector('#template3');
let clone3 = document.importNode(tempLinha3.content, true);
const label3 = clone3.querySelector("label");
label3.htmlFor = cont3;
clone3.querySelector("input").className = cont3;
container3.appendChild(clone3);
cont3++;
document.getElementById('add2').id = 'add3';
document.getElementById('del2').id = 'del3';
};
document.getElementById("deltit").onclick = function deltit() {
document.querySelector('#output2 #alg:last-child').remove();
document.getElementById('add3').id = 'add2';
document.getElementById('del3').id = 'del2';
};
}
// -----------------------------------------
if (document.getElementById("add3")) {
let cont4 = 1;
document.getElementById("add3").onclick = function clone4() {
let container4 = document.getElementById("output3");
let tempLinha4 = document.querySelector('#template2');
let clone4 = document.importNode(tempLinha4.content, true);
const label4 = clone4.querySelector("label");
label4.htmlFor = cont4;
clone4.querySelector("input").className = cont4;
container4.appendChild(clone4);
cont4++;
};
document.getElementById("del3").onclick = function del4() {
document.querySelector('#output3 #linha2:last-child').remove();
};
}
<div class="container">
<button id="addtit">+ TITLE</button>
<button id="deltit">- TITLE</button>
<button id="add2">+ DESCRIPTION</button>
<button id="del2">- DESCRIPTION</button>
<div id="output2"></div>
<div class='botoes'>
<button onclick="result()" id='done'>DONE</button>
</div>
<div class="header"><span class="title">RESULT</span>
</div>
<div class="linha"><textarea id="result"></textarea>
</div>
</div>
<!-- template 2 -->
<template id="template2">
<div class="linha" id="linha2"><div class="coluna1"><label for="0">DESCRIPTION:</label></div><div class="coluna2"><input name="inp2" class="0" type="text"/></div>
</div>
</template>
<!-- template 3 -->
<template id="template3">
<div id="alg">
<div class="linha"><div class="coluna1"><label for="0">TITLE:</label></div><div class="coluna2"><input name="titu" class="0" type="text"/></div>
</div>
<div class="linha" id="linha3"><div class="coluna1"><label for="0">DESCRIPTION:</label></div><div class="coluna2"><input name="inp2" class="0" type="text"/></div>
</div>
<div id="output3"></div>
</div>
</template>
Ok. it's because this part of code in function result:
if (titu[0]) {
for (var k = 0; k < titu.length; k++) {
if (titu[k].value.trim() != '') {
res.value += `<div>
<span>${titu[k].value.trim()}</span>
</div>
<ul>\n`;
for (var j = 0; j < inp2.length; j++) {
if (inp2[j].value.trim() != '') {
res.value += `<li>${inp2[j].value.trim()}</li>\n`;
}
}
}
}
}
your titles have the same names : 'titu' , and your descriptions have same names : 'inp2', and you have two nested loops, for each title, loop on description, and it results as you see.
it's better to change your code and make different names and ids
by the way. if you persist to do not change your code, you should use one loop for both of them, like this code
if (titu[0]) {
for (var k = 0; k < titu.length; k++) {
if (titu[k].value.trim() != '') {
res.value += `<div>
<span>${titu[k].value.trim()}</span>
</div>
<ul>\n`;
if (inp2[k].value.trim() != '') {
res.value += `<li>${inp2[k].value.trim()}</li>\n`;
}
}
}
}
UPDATE
for the case of more description for each title, you have to change the code of onClick methods of Title+ and Description+, the added title and all of its description must have same parent, and after doing that, it's possible to solve the problem like this . (assuming the parent that I already have said has class name 'parent')
function result() {
var parents = document.querySelectorAll(".parent")
parents.forEach(function(parent){
var title = parent.querySelector("titu");
var descriptions = parent.querySelectorAll("inp2");
var res = document.getElementById("result");
if (title.value.trim() != '') {
res.value += `<div>
<span>${title.value.trim()}</span>
</div>
<ul>\n`;
}
descriptions.forEach(function(inp2){
if (inp2.value.trim() != '') {
res.value += `<li>${inp2.value.trim()}</li>\n`;
}
});
});
}
notice that this code could work after modifying Title+ and Description+ events and add same parent with class name parent to title and descriptions inputs

Categories