Condition pagination javascript - 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>

Related

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 to remove all of the divs? with Vanilla JS

When I want to change the grid, I want the old one to disappear but right now the old one is being added to the new one. So how to remove all of the old divs? https://codepen.io/diana-larussa/pen/RwGMxqL
if (gridDOMElement.value === 'second') {
const elementsCount = 36
for (let index = 0; index < elementsCount; index++) {
const div = document.createElement("div")
container.appendChild(div)
}
container.style.gridTemplateColumns = "repeat(6, 7vmax)"
container.style.gridTemplateRows = "repeat(6, 7vmax)"
}
if (gridDOMElement.value === "third") {
const elementsCount = 70
for (let index = 0; index < elementsCount; index++) {
const div = document.createElement("div")
container.appendChild(div)
}
container.style.gridTemplateColumns = "repeat(10, 7vmax)"
container.style.gridTemplateRows = "repeat(7, 7vmax)"
}
}
document.querySelector("#grid").addEventListener("change", newGrid)```
I added this inside of the newGrid() function and it helped:
const item = document.querySelector('.container')
while (item.firstChild) {
item.removeChild(item.firstChild)
}

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>

Can't set the number of paginations with JavaScript

I'm trying to add the numbers of pagination using Javascript. The arrows navigation is working fine but when I try to add the numbers of pages my code doesn't work. I have 2 pages with 10 results each. When I click in the number 1 the console print the number 3. The problem is inside the function createPagination when I create the loop for the page numbers. Any help?
var arrFull = [];
var pageSize = 10;
var pages = -1;
var actualPage = 0;
function changePagination(pagination) {
if(Number(pagination) !== actualPage && pagination > 0 && pagination <= pages) {
var start = ((pagination - 1) * pageSize) + 1;
if(pagination === 1) {
ini = 0;
}
var end = pagination * pageSize;
if(end > arrFull.length) {
end = arrFull.length;
}
var arr = arrFull.slice(start,end);
for(var i = 0; i < arr.length; i++) {
createObject(arr[i]);
}
actualPage = Number(pagination);
createPagination();
}
}
function createPagination() {
var paginator = document.getElementById('pagination');
paginator.innerHTML = "";
var arrowLeft = document.createElement('a');
arrowLeft.setAttribute('href', '');
var arrowRight = document.createElement('a');
arrowRight.setAttribute('href', '');
arrowLeft.innerHTML = '<span class="arrow"></span>';
arrowLeft.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage - 1);
});
arrowRight.innerHTML = '<span class="arrow"></span>';
arrowRight.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage + 1);
});
paginator.appendChild(arrowLeft);
for(var pagination = 1; pagination <= pages; pagination++) {
var number = document.createElement('a');
number.setAttribute('href', '');
number.innerHTML = pagination;
number.addEventListener('click', function(event) {
event.preventDefault();
changePagination(pagination);
console.log(pagination);
});
paginator.appendChild(number);
}
paginator.appendChild(arrowRight);
}
When you pass on your pagination variable it passes the last value set to it in that context (the 3 because of its last iteration in the loop).
You should declare a variable inside the click event and assign to it the value of pagination and then pass your local variable to your method:
number.addEventListener('click', function(event)
{
let currentPage = pagination;
event.preventDefault();
changePagination(currentPage);
console.log(currentPage);
});
That should do the trick.
Edit
This is the actual solution:
number.setAttribute("page", pagination);
number.addEventListener('click', function(event) {
let currentPage = +event.target.getAttribute("page");
event.preventDefault();
changePagination(currentPage);
console.log(currentPage);
});
The reason why the number 3 is being returned is because the let currentPage = pagination; line is being executed when the event triggers; by that time the value of the variable pagination is equal to 3, so you need to save its value through every iteration (it can be saving it inside a property within your element outside of the event scope like so: number._pageNumber = pagination;; or as the given example: number.setAttribute("page", pagination);).
Full implementation
<html>
<body>
<!--Element to simulate the pagination-->
<div id="pagination"></div>
<script>
var arrFull = [];
var pageSize = 10;
var pages = 2; // Change to simulate your case (changed the '-1' to '2')
var actualPage = 0;
function changePagination(pagination) {
if(Number(pagination) !== actualPage && pagination > 0 && pagination <= pages) {
var start = ((pagination - 1) * pageSize) + 1;
if(pagination === 1) {
ini = 0;
}
var end = pagination * pageSize;
if(end > arrFull.length) {
end = arrFull.length;
}
var arr = arrFull.slice(start,end);
for(var i = 0; i < arr.length; i++) {
createObject(arr[i]);
}
actualPage = Number(pagination);
createPagination();
}
}
function createPagination() {
var paginator = document.getElementById('pagination');
paginator.innerHTML = "";
var arrowLeft = document.createElement('a');
arrowLeft.setAttribute('href', '');
var arrowRight = document.createElement('a');
arrowRight.setAttribute('href', '');
arrowLeft.innerHTML = '<span class="arrow"></span>';
arrowLeft.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage - 1);
});
arrowRight.innerHTML = '<span class="arrow"></span>';
arrowRight.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage + 1);
});
paginator.appendChild(arrowLeft);
for(var pagination = 1; pagination <= pages; pagination++) {
var number = document.createElement('a');
number.setAttribute('href', '');
number.innerHTML = pagination;
// <Here_is_the_sugested_code> //
number.setAttribute("page", pagination);
number.addEventListener('click', function(event) {
let currentPage = +event.target.getAttribute("page");
event.preventDefault();
changePagination(currentPage);
console.log(currentPage);
});
// </Here_is_the_sugested_code> //
paginator.appendChild(number);
}
paginator.appendChild(arrowRight);
}
createPagination(); // Call to the function to simulate the generation
</script>
</body>
</html>

How to change this code to list post titles of all the post on Blogger in format YYYY.MM.DD <title> and chronological order?

I like to show my titles of posts on a specific page. It is more effective to get know what author have written than scroll all pages or navigate using archive widget.
I found code (code is below) for generate list that sort post titles alphabetically but I like to show titles in chronological order. There is lot of code example about this but they are outdated. They doesnโ€™t work anymore after some changes in blogger platform.
How to change code to get post titles in chronological order and in format YYYY.MM.DD ?
<div>
<ul id="postList12"></ul>
</div>
<script type="text/javascript">
var startIndex = 1;
var maxResults = 150;
var allResults = [];
function sendQuery12() {
var scpt = document.createElement("script");
scpt.src = "/feeds/posts/summary?alt=json&callback=processPostList12&start-index=" + startIndex + "&max-results=" + maxResults;
document.body.appendChild(scpt);
}
function printArrayResults(root) {
//Sort Alphebetically
allResults.sort(function(a, b)
{
var a_string = a.children[0].textContent ;
var b_string = b.children[0].textContent ;
if(a_string < b_string) return -1;
if(a_string > b_string) return 1;
return 0;
})
var elmt = document.getElementById("postList12");
for (index = 0; index < allResults.length; index++) {
elmt.appendChild(allResults[index]);
}
}
function processPostList12(root) {
var elmt = document.getElementById("postList12");
if (!elmt)
return;
var feed = root.feed;
if (feed.entry.length > 0) {
for (var i = 0; i < feed.entry.length; i++) {
var entry = feed.entry[i];
var title = entry.title.$t;
var date = entry.published.$t
for (var j = 0; j < entry.link.length; j++) {
if (entry.link[j].rel == "alternate") {
var url = entry.link[j].href;
if (url && url.length > 0 && title && title.length > 0) {
var liE = document.createElement("li");
var a1E = document.createElement("a");
a1E.href = url;
a1E.textContent = title + " (" + date.substr(0,10) + ")";
liE.appendChild(a1E);
//elmt.appendChild(liE);
allResults.push(liE);
}
break;
}
}
}
if (feed.entry.length >= maxResults) {
startIndex += maxResults;
sendQuery12();
} else {
printArrayResults();
}
}
}
sendQuery12();
</script>
Code is copied from here: https://dansator.blogspot.fi/2015/10/general-alphabetical-list-of-posts.html
Remove sort method from the code. remove the following :
//Sort Alphebetically
allResults.sort(function(a, b){
var a_string = a.children[0].textContent ;
var b_string = b.children[0].textContent ;
if(a_string < b_string) return -1;
if(a_string > b_string) return 1;
return 0;
})
Your code should be
<div>
<ul id="postList12"></ul>
</div>
<script type="text/javascript">
var startIndex = 1;
var maxResults = 150;
var allResults = [];
function sendQuery12()
{
var scpt = document.createElement("script");
scpt.src = "/feeds/posts/summary?alt=json&callback=processPostList12&start-index=" + startIndex + "&max-results=" + maxResults;
document.body.appendChild(scpt);
}
function printArrayResults(root)
{
var elmt = document.getElementById("postList12");
for (index = 0; index < allResults.length; index++) {
elmt.appendChild(allResults[index]);
}
}
function processPostList12(root)
{
var elmt = document.getElementById("postList12");
if (!elmt)
return;
var feed = root.feed;
if (feed.entry.length > 0)
{
for (var i = 0; i < feed.entry.length; i++)
{
var entry = feed.entry[i];
var title = entry.title.$t;
var date = entry.published.$t
for (var j = 0; j < entry.link.length; j++)
{
if (entry.link[j].rel == "alternate")
{
var url = entry.link[j].href;
if (url && url.length > 0 && title && title.length > 0)
{
var liE = document.createElement("li");
var a1E = document.createElement("a");
a1E.href = url;
a1E.textContent = title + " (" + date.substr(0,10) + ")";
liE.appendChild(a1E);
//elmt.appendChild(liE);
allResults.push(liE);
}
break;
}
}
}
if (feed.entry.length >= maxResults)
{
startIndex += maxResults;
sendQuery12();
} else {
printArrayResults();
}
}
}
sendQuery12();
</script>

Categories