Issue looping through all of the elements in an Array JavaScript - javascript

I have an Array of objects:
let myArray = [
{myParagraph: "This is paragraph 1"},
{myParagraph: "This is paragraph 2"},
{myParagraph: "This is paragraph 3"},
{myParagraph: "This is paragraph 4"},
{myParagraph: "This is paragraph 5"},
]
I want to loop through and display all of these objects. These objects should be paginated. To do this, I used this code:
let page = 1;
let button_number = 1;
let first_element_shown = 0;
let last_element_shown = 10;
let number_of_pages = Math.ceil(myArray.length / 10);
for (let i of myArray) {
for (let j = 0; j < number_of_pages; j++) {
for (let k = first_element_shown; k < last_element_shown; k++) {
let card = document.createElement('div')
let myParagraph = document.createElement('p');
myParagraph.innerText = i.myParagraph;
card.appendChild('myParagraph')
document.getElementById("example_DIV").appendChild(card);
}
}
}
However, this loops through and displays the same objects multiple times. Is there a way to loop through all of the objects in myArray without using the for (let i of myArray) line in order to stop the same objects from showing multiple times.

You need to set
pageSize
page
start equal to (page - 1) * pageSize
end equal to start + pageSize
use slice method to slice the shown part in the array.
This is an example.
let myArray = [{
myParagraph: "This is paragraph 1"
},
{
myParagraph: "This is paragraph 2"
},
{
myParagraph: "This is paragraph 3"
},
{
myParagraph: "This is paragraph 4"
},
{
myParagraph: "This is paragraph 5"
},
{
myParagraph: "This is paragraph 6"
},
{
myParagraph: "This is paragraph 7"
},
{
myParagraph: "This is paragraph 8"
},
{
myParagraph: "This is paragraph 9"
},
{
myParagraph: "This is paragraph 10"
},
{
myParagraph: "This is paragraph 11"
},
{
myParagraph: "This is paragraph 12"
},
{
myParagraph: "This is paragraph 13"
},
{
myParagraph: "This is paragraph 14"
},
]
let pageSize = 3;
let page = 1;
const elementsContainer = document.querySelector('.elements-container');
const next = document.querySelector('#next');
const prev = document.querySelector('#prev');
const changePageNumber = (pageValue) => {
console.log(pageValue)
let page = pageValue;
let start = (page - 1) * pageSize;
let end = start + pageSize;
let shownElements = myArray.slice(start, end);
elementsContainer.innerHTML = '';
shownElements.forEach(item => {
const div = document.createElement('div');
div.textContent = item.myParagraph;
elementsContainer.append(div);
})
}
next.addEventListener('click', () => changePageNumber(++page));
prev.addEventListener('click', () => changePageNumber(--page));
changePageNumber(page)
.elements-container {
margin-top: 20px;
border: 1px solid red;
}
<button id="next">Next</button>
<button id="prev">Previous</button>
<div class="elements-container">
</div>

let page = 1;
let button_number = 1;
let count = 0;
let first_element_shown = 0;
let last_element_shown = 10;
let number_of_pages = Math.ceil(myArray.length / 10);
for (let j = 0; j < number_of_pages; j++) {
for (let k = first_element_shown; k < last_element_shown & count<myArray.length; k++) {
let card = document.createElement('div')
let myParagraph = document.createElement('p');
myParagraph.innerText = myArray[count].myParagraph;
card.appendChild(myParagraph)
document.getElementById("example_DIV").appendChild(card);
count++
}
}
While this isn't perfect, it fixes some of your issues and you can probably figure out the rest from there.

Related

Add next/ previous page buttons JavaScript

How could I add the next/ previous page buttons to an Array in JavaScript?
I have this Array:
let products = {
data: [
{
productName: "Product1",
},
{
productName: "Product2",
},
{
productName: "Product3",
},
{
productName: "Product4",
},
{
productName: "Product5",
},
{
multiple other products
},
],
};
After 5 products, a new page should begin. I have done this using the following JavaScript code:
const nav = document.getElementById('nav');
const content = document.getElementById('content');
let pageIndex = 0;
let itemsPerPage = 3;
loadItems();
function loadItems() {
content.innerHTML = "";
for (let i = pageIndex * itemsPerPage; i < (pageIndex * itemsPerPage) + itemsPerPage; i++) {
if (!items[i]) break;
const item = document.createElement('div');
item.innerHTML = `
<div>
<img src="${items[i].src}"/>
</div>
<div>
<button>${items[i].desc}</button>
</div>
`;
content.append(item);
}
loadPageNav();
}
function loadPageNav() {
nav.innerHTML = "";
for (let i = 0; i < items.length / itemsPerPage; i++) {
const button = document.createElement('button');
button.classList.add('btn');
button.innerHTML = i + 1;
button.addEventListener('click', (e) => {
pageIndex = e.target.innerHTML - 1;
loadItems();
});
if (i === pageIndex) {
/*button.style.fontSize = "2rem";*/
}
nav.append(button);
}
}
I now also want to include the next and previous buttons. This means that when the user clicks the next button, the next page should be shown. When the user clicks the previous page button, the previous page should be shown.
When the first page is shown, the previous page button should be a different colour. When the last page is shown, the next page button should be a different colour.

HTML Javascript image slider - adding slide animation/

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);

How can I put individual "p" elements into the "container" div using js function?

I tried to put "p" elements() into the "div"(container) elements but failed -->
let t = [
"First line!",
"Second line!",
"Third line!",
"Fourth line!"
];
let T = t.length;
function load(){
for(let i = 0; i < T; i++){
let contElem = document.createElement("div");
contElem.setAttribute("class", "container");
contElem.setAttribute("onload", "load02()");
document.querySelector("#main").appendChild(contElem);
}
}
function load02(){
for(let i = 0; i < T; i++){
let myElem = document.createElement("p");
myElem.innerHTML = t[i];
document.querySelector(".container").appendChild(myElem);
}
}
but it did not work! Help!
You're attribute onload will never fire ... Since the DOM has already "loaded" at this point .. You just need to call the function .. And call load2() at the end of function 1
let t = [
"First line!",
"Second line!",
"Third line!",
"Fourth line!"
];
let T = t.length;
load(); // RUN YOUR FUNCTION
function load(){
for(let i = 0; i < T; i++){
let contElem = document.createElement("div");
contElem.setAttribute("class", "container");
//contElem.setAttribute("onload", "load2()"); // REMOVE THIS
document.querySelector("#main").appendChild(contElem);
}
load2(); //ADD THIS
}
function load2(){
for(let i = 0; i < T; i++){
let myElem = document.createElement("p");
myElem.innerHTML = t[i];
document.querySelector(".container").appendChild(myElem);
}
}
.container{
border:1px solid #FF0000;
height:50px;
width:50px;
}
<div id="main">
</div>
let t = [
"First line!",
"Second line!",
"Third line!",
"Fourth line!"
];
let T = t.length;
function load() {
for (let i = 0; i < T; i++) {
let contElem = document.createElement("div"), myElem = document.createElement("p");
contElem.setAttribute("class", "container");
myElem.innerHTML = t[i];
contElem.appendChild(myElem);
document.querySelector("#main").appendChild(contElem);
}
}
load();
<div id="main"></div>
Does that work? Or were you wanting to put all four p elements in each containing div element?

Trying to reset select options based on change w/out jQuery

I'm working in an environment where I can't use jQuery. I want to update options in one select box when options in another select box are changed. What I have now doesn't totally clear out the prior set of options or it's adding options I don't want.
I want the entity options to be dependent on the sponsor option selected.
https://codepen.io/dzamora54/pen/poogwJN
<label for="sponsorDropdown">Sponsor</label>
<select name="sponsorDropdown" id="sponsorDropdown">
<option disabled selected value>Select an option</option>
</select>
<label for="entityDropdown">Entity</label>
<select name="entityDropdown" id="entityDropdown">
<option disabled selected value>Select an option</option>
</select>
// List of sponsors
const sponsorList = [
{
sponsorName: "Sponsor One",
sponsorEntities: ["Sp1 Entity One", "Sp1 Entity Two", "Sp1 Entity Three"],
sponsorSigners: [
{ signerName: "Sp1 Signer One", signerTitle: "Sp1 Si1 Title" },
{ signerName: "Sp1 Signer Two", signerTitle: "Sp1 Si2 Title" }
]
},
{
sponsorName: "Sponsor Two",
sponsorEntities: ["Not Applicable"],
sponsorSigners: [
{ SignerName: "Sp2 Signer One", signerTitle: "Sp2 Si1 Title" }
]
},
{
sponsorName: "Sponsor Three",
sponsorEntities: ["Not Applicable"],
sponsorSigners: [
{ signerName: "Sp3 Signer One", signerTitle: "Sp3 Si1 Title" },
{ signerName: "Sp3 Signer Two", signerTitle: "Sp3 Si2 Title" }
]
}
];
let sponsorValue;
let sponsorIndex;
// On load calls populateSponsorDropdown function
window.addEventListener("load", function() {
this.populateSponsorDropdown();
});
// Populates sponsor dropdown from list of sponsors
function populateSponsorDropdown() {
for (let i = 0; i < sponsorList.length; i++) {
let sponsor = document.getElementById("sponsorDropdown");
let option = document.createElement("option");
option.text = sponsorList[i].sponsorName;
sponsor.add(option);
}
}
// When sponsor dropdown changes, update entity dropdown as neccessary
document
.getElementById("sponsorDropdown")
.addEventListener("change", updateSponsorValueAndEntityDropdown);
function updateSponsorValueAndEntityDropdown() {
sponsorValue = document.getElementById("sponsorDropdown").value;
for (let i = 0; i < sponsorList.length; i++) {
if (sponsorValue === sponsorList[i].sponsorName) {
sponsorIndex = i;
}
}
populateEntityDropdown();
}
// Populates entity dropdown based on sponsor that is selected
function populateEntityDropdown() {
const emptyDropdown = document.getElementById("entityDropdown");
const length = emptyDropdown.options.length;
for (i = 0; i < length; i++) {
emptyDropdown.options[i] = null;
}
// for (let i = 0; i < entityDropdown.length; i++) {
// let emptyDropdown = document.getElementById("entityDropdown");
// emptyDropdown.remove(i);
for (let j = 0; j < sponsorList[sponsorIndex].sponsorEntities.length; j++) {
let entity = document.getElementById("entityDropdown");
let option = document.createElement("option");
option.text = sponsorList[sponsorIndex].sponsorEntities[j];
entity.add(option);
}
}
I think I solved this by replacing
const emptyDropdown = document.getElementById("entityDropdown");
const length = emptyDropdown.options.length;
for (i = 0; i < length; i++) {
emptyDropdown.options[i] = null;
with
const emptyDropdown = document.querySelector("#entityDropdown");
emptyDropdown.innerHTML = "";

Function not running on button click? [duplicate]

This question already has answers here:
Is "clear" a reserved word in Javascript?
(4 answers)
Closed 6 years ago.
I have a button on my page that is intended to clear all the textareas that are in the document, however when I click said button it appears that the function isn't being run. I've tried adding a button listener to the document, and that still didn't seem to work, I don't understand what the problem is, as the line with the alert isn't even running.
function markForm(tagID) {
var x = document.getElementById(tagID)
var pre = document.createElement("pre");
x.appendChild(pre);
var SectionDetails = [
{ name: "Dynamic Table", maxMarks: 20},
{ name: "IntelliJ usage", maxMarks: 10},
{ name: "Calendar Controller", maxMarks: 30},
{ name: "Active Form", maxMarks: 20},
{ name: "Object Database", maxMarks: 20}
];
var table = pre.appendChild(document.createElement("table"));
var tableHeader = table.appendChild(document.createElement("thead"));
var tableRow = tableHeader.appendChild(document.createElement("tr"));
var headRow = tableRow.appendChild(document.createElement("th"));
headRow.appendChild(document.createTextNode("Section"));
headRow = tableRow.appendChild(document.createElement("th"));
headRow.appendChild(document.createTextNode("Max Mark"));
headRow = tableRow.appendChild(document.createElement("th"));
headRow.appendChild(document.createTextNode("Comments"));
headRow = tableRow.appendChild(document.createElement("th"));
headRow.appendChild(document.createTextNode("Mark"));
var resultsRows = table.appendChild(document.createElement("tbody"));
for (var i = 0; i < SectionDetails.length; i++) {
tableRow = resultsRows.appendChild(document.createElement("tr"));
var tableData = tableRow.appendChild(document.createElement("td"));
tableData.appendChild(document.createTextNode(SectionDetails[i].name));
tableData = tableRow.appendChild(document.createElement("td"));
tableData.appendChild(document.createTextNode(SectionDetails[i].maxMarks));
tableData = tableRow.appendChild(document.createElement("td"));
var tarea = document.createElement("textarea");
tarea.value = "Enter Comments";
tableData.appendChild(tarea);
tableData = tableRow.appendChild(document.createElement("td"));
var dropDown = document.createElement("select");
dropDown.name = SectionDetails[i].name;
for (var j = 0; j < (SectionDetails[i].maxMarks + 1); j++) {
var listItem = new Option(j);
listItem.value=j;
dropDown.appendChild(listItem);
}
tableData.appendChild(dropDown);
}
var h2 = document.createElement("h2");
h2.innerHTML = "Total Marks: " + document.createTextNode(totalMarks);
x.appendChild(h2);
}
function totalMarks() {
var total = 0;
for (var a = 0; a < SectionDetails.length; a++) {
var e = document.getElementById(SectionDetails[a].name);
var total = total + Number(e.options[e.selectedIndex].value);
}
return total;
}
function clear() {
var textareas = documents.getElementsByTagName("textarea");
console.log(textareas);
for (var i = 0; i < textareas.length; i++) {
textareas[i].value="Enter Comments";
}
alert("Fields Cleared");
}
<body onload="markForm('conversion')">
<h2>Marking Form: </h2>
<p id='conversion'>
</p>
<p id='clear'>
<input type="button" id="but" value="Clear" onclick="clear()"/>
</p>
There seems an error in your clear() function. it should be document.getElementsByTagName(). and yours is "documents" - also clear is a word used elsewhere: document.clear

Categories