next and prev button functionality with pagination - javascript

I want to add to my pagination the next and prev button functionality so i can also move the pages through them. in my code i only manage to display the next or prev page and see the content from the second page on click but without also moving the selected number of the button from 1 to 2, or the next page if there are more and so on. same for the prev. also, if i cannot go next/prev i want to have the next/prev button disabled.
any help with this, please?
here is what i have till now:
window.onload = function(){
var data = {
"headings": {
"propBook": "Book",
"propAuthor": "Author",
"propYear": "Year",
},
"items": [{
"fields": {
"propBook": "The Great Gatsby",
"propAuthor": "F Scott Fitzgerald",
"propYear": "1925",
},
"button": {
"name": "View book",
"propURL": "https://google.com"
}
},
{
"fields": {
"propBook": "The Grapes of Wrath",
"propAuthor": "John Steinbeck",
"propYear": "1939",
},
"button": {
"name": "View book",
"propURL": ""
}
},
{
"fields": {
"propBook": "A Wild Sheep Chase",
"propAuthor": "Haruki Murakami",
"propYear": "1982",
},
"button": {
"name": "View book",
"propURL": "https://google.com"
}
}
]
}
const HEADINGS = data.headings;
const ITEMS = data.items;
const TABLE_WRAPPER = document.querySelector('.book-component .table-wrapper');
const TABLE = document.createElement('table');
TABLE.setAttribute('class', 'pagination');
TABLE.setAttribute('data-pagecount', 2);
TABLE_WRAPPER.appendChild(TABLE);
for (const field in data) {
const TABLE_ROW = document.createElement('tr');
TABLE_ROW.setAttribute('id', 'myRow');
if (field == 'headings') {
for (const child in HEADINGS) {
const HEADER_CELL = document.createElement('th');
TABLE_ROW.appendChild(HEADER_CELL);
HEADER_CELL.setAttribute('class', 'sort-cta');
HEADER_CELL.innerText = HEADINGS[child];
TABLE.appendChild(TABLE_ROW);
}
} else if (field == 'items') {
for (const child in ITEMS) {
const TABLE_ROW = document.createElement('tr');
let item = ITEMS[child].fields;
let btn = ITEMS[child].button;
for (const row in item) {
const TABLE_DATA = document.createElement('td');
TABLE_ROW.appendChild(TABLE_DATA);
TABLE_DATA.innerText = item[row];
TABLE.appendChild(TABLE_ROW);
}
if (btn.propURL !== '') {
let link = document.createElement('a');
link.setAttribute('href', btn.propURL);
link.innerHTML = btn.name;
x = TABLE_ROW.insertCell(-1);
x.appendChild(link);
} else {
let link = document.createElement('span');
link.innerHTML = 'Reserved';
x = TABLE_ROW.insertCell(-1);
x.appendChild(link);
}
}
}
}
let perPage = 10;
function genTables() {
let tables = document.querySelectorAll('.pagination');
tables.forEach((table) => {
perPage = parseInt(table.dataset.pagecount);
createFooters(table);
createTableMeta(table);
loadTable(table);
});
}
// based on current page, only show the elements in that range
function loadTable(table) {
let startIndex = 0;
if (table.querySelector('th')) startIndex = 1;
const START = parseInt(table.dataset.currentpage) * table.dataset.pagecount + startIndex;
const END = START + parseInt(table.dataset.pagecount);
const TABLE_ROWS = table.rows;
for (var x = startIndex; x < TABLE_ROWS.length; x++) {
if (x < START || x >= END) TABLE_ROWS[x].classList.add('inactive');
else TABLE_ROWS[x].classList.remove('inactive');
}
}
function createTableMeta(table) {
table.dataset.currentpage = '0';
}
function createFooters(table) {
const COUTING_WRAPPER = document.createElement('div');
COUTING_WRAPPER.setAttribute('class', 'counting-wrapper');
const COUNTING_MSG = document.createElement('p');
COUTING_WRAPPER.appendChild(COUNTING_MSG);
let TABLE_WRAP = document.querySelector('.table-wrapper');
TABLE_WRAP.appendChild(COUTING_WRAPPER);
let hasHeader = false;
if (table.querySelector('th')) hasHeader = true;
let ROWS = table.rows.length;
if (hasHeader) ROWS = ROWS - 1;
let NUM_PAGES = ROWS / perPage;
let pager = document.createElement('div');
// add an extra page
if (NUM_PAGES % 1 > 0) NUM_PAGES = Math.floor(NUM_PAGES) + 1;
pager.className = 'pager';
let nextPage = document.createElement('button');
nextPage.innerHTML = 'next';
nextPage.className = 'item';
let prevPage = document.createElement('button');
prevPage.innerHTML = 'prev';
prevPage.className = 'item';
pager.appendChild(prevPage);
pager.appendChild(nextPage);
nextPage.addEventListener('click', () => {
table.dataset.currentpage = parseInt(table.dataset.currentpage) + 1;
loadTable(table);
});
prevPage.addEventListener('click', () => {
table.dataset.currentpage = parseInt(table.dataset.currentpage) - 1;
loadTable(table);
})
for (var i = 0; i < NUM_PAGES; i++) {
var page = document.createElement('button');
page.innerHTML = i + 1;
page.className = 'pager-item';
page.dataset.index = i;
if (i == 0) page.classList.add('selected');
page.addEventListener('click', function () {
var items = pager.querySelectorAll('.pager-item');
for (var x = 0; x < items.length; x++) {
items[x].classList.remove('selected');
}
this.classList.add('selected');
table.dataset.currentpage = this.dataset.index;
loadTable(table);
});
pager.appendChild(page);
}
// insert page at the top of the table
table.parentNode.insertBefore(pager, table);
}
genTables();
};
tr.inactive {
display: none;
}
.table-wrapper {
display: flex;
flex-direction: column-reverse;
}
.pager {
display: flex;
justify-content: center;
padding: 0;
margin-top: 10px;
font-weight: 800;
}
.pager-item.selected {
outline: none;
border-color: #0077cc;
background: #0077cc;
color: #fff;
cursor: default;
}
<div class="book-component">
<div class="table-wrapper">
</div>
</div>

Your loadTable function is updating the DOM based on the current state of your application. You can extend this to set the disabled state of the prev/next buttons, and to set the selected class of the page number button.
Here's an example where the button state is set by the loadTable function. The click event handlers should only update the current page (ie. set the state of the app). Then you can do your rendering of the state in the loadTable function.
// based on current page, only show the elements in that range
function loadTable(table) {
let startIndex = 0;
if (table.querySelector('th')) startIndex = 1;
const START = parseInt(table.dataset.currentpage) * table.dataset.pagecount + startIndex;
const END = START + parseInt(table.dataset.pagecount);
const TABLE_ROWS = table.rows;
for (var x = startIndex; x < TABLE_ROWS.length; x++) {
if (x < START || x >= END) TABLE_ROWS[x].classList.add('inactive');
else TABLE_ROWS[x].classList.remove('inactive');
}
// You should move this calculation outside of the function
const ROWS = table.rows.length - 1;
const NUM_PAGES = Math.ceil(ROWS / perPage);
const prevPage = document.getElementsByName('pagination-prev-button')[0];
const nextPage = document.getElementsByName('pagination-next-button')[0];
const isNextDisabled = +table.dataset.currentpage >= NUM_PAGES - 1;
const isPrevDisabled = +table.dataset.currentpage === 0;
if (isNextDisabled) {
nextPage.setAttribute('disabled', true);
} else {
nextPage.removeAttribute('disabled');
}
if (isPrevDisabled) {
prevPage.setAttribute('disabled', true);
} else {
prevPage.removeAttribute('disabled');
}
const items = document.querySelectorAll('.pager-item');
for (var x = 0; x < items.length; x++) {
if (x === +table.dataset.currentpage) {
items[x].classList.add('selected');
} else {
items[x].classList.remove('selected');
}
}
}
Here's the full working example.
https://jsfiddle.net/aloshea/r68gtvmc/

Related

How to check if the last page is active JavaScript?

I have created buttons within JavaScript. Above these buttons, items are displayed. When I am on the first page, the button titled 'Back' is disabled.
When I am on the last page, the button titled 'Next' should be disabled.
I have this code:
const items = [
{name: "item1"},
{"name: item2"},
{"name: item3"},
{"name: item4"},
{"name: item5"},
]
I have displayed the items using this 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++) {
const item = document.createElement('div');
item.innerHTML = `
<p>$item[i].name</p>
`;
content.append(item);
}
minusPage();
loadPageNav();
plusPage();
}
function loadPageNav() {
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();
});
nav.append(button);
}
}
function plusPage() {
const button = document.createElement('button');
button.classList.add('btn');
button.innerHTML = "Next";
button.addEventListener('click', () => {
pageIndex = pageIndex + 1;
loadItems();
});
nav.append(button);
}
function minusPage() {
nav.innerHTML = "";
const button = document.createElement('button');
button.classList.add('btn');
button.innerHTML = "Back";
button.addEventListener('click', () => {
pageIndex = pageIndex - 1;
loadItems();
});
nav.append(button);
if (pageIndex === 0) {
button.style.backgroundColor = "#cccccc";
}
}
I now want to add a different colour to the Next button when the user is on the last page. How can I find out when the user is on the last page.

Need help adjusting the grid size based on user input

Need help!
simply put I am creating a grid that is x * x. the "x" variable is going to be whatever the user inputs.
Where I am struggling is I need be able to click a button and have a prompt widow come up, collect the number the user enters, and then use that number as an argument for a function I created to build the grid.
As you can probably tell by my question, I am fairly new to coding. So the simpler the solution the better for me to understand.
Thanks a ton!
const div = document.querySelector('#container')
const clearButton = document.querySelector('.button-clear');
const resizeButton = document.querySelector('.button-resize')
createGrid = gridNumber => {
if (gridNumber === undefined) {
gridNumber = 16;
} else gridNumber = gridNumber;
let gridSize = gridNumber * gridNumber;
for (i = 0; i < gridSize; i++) {
let squares = document.createElement('div');
squares.classList.add('squares');
div.style.gridTemplateRows = `repeat(${gridNumber}, 1fr)`;
div.style.gridTemplateColumns = `repeat(${gridNumber}, 1fr)`;
div.appendChild(squares);
}
let boxes = document.querySelectorAll('.squares');
boxes.forEach(box => box.addEventListener('mouseover', () => {
box.style.backgroundColor = "gray";
}));
}
resetGrid = () => {
let boxes = document.querySelectorAll('.squares');
boxes.forEach(box => {
box.style.backgroundColor = 'white';
})
}
createGrid();
clearButton.addEventListener('click', resetGrid);
Just prompt for the value and call the function again. Check for undefined in case user didn't enter anything.
const div = document.querySelector('#container')
const clearButton = document.querySelector('.button-clear');
const resizeButton = document.querySelector('.button-resize')
createGrid = gridNumber => {
if (gridNumber === undefined) {
gridNumber = 16;
} else gridNumber = gridNumber;
let gridSize = gridNumber * gridNumber;
for (i = 0; i < gridSize; i++) {
let squares = document.createElement('div');
squares.classList.add('squares');
div.style.gridTemplateRows = `repeat(${gridNumber}, 1fr)`;
div.style.gridTemplateColumns = `repeat(${gridNumber}, 1fr)`;
div.appendChild(squares);
}
let boxes = document.querySelectorAll('.squares');
boxes.forEach(box => box.addEventListener('mouseover', () => {
box.style.backgroundColor = "gray";
}));
}
resetGrid = () => {
let boxes = document.querySelectorAll('.squares');
boxes.forEach(box => {
box.style.backgroundColor = 'white';
})
}
createGrid(4);
clearButton.addEventListener('click', resetGrid);
resizeButton.addEventListener('click', function() {
var value = prompt("enter size: ", 16);
if (typeof value === 'undefined') {
return
}
createGrid(value)
});
.squares {
border: 1px solid black;
width: 20px;
height: 20px;
float: left;
}
<div id="container">
</div>
<button class="button-clear">clear</button>
<button class="button-resize">resize</button>

Show when element is found in array

I am creating a word search solver and used the find() method to detect when a value is inside an array.
The values of the table are placed in two arrays, one for rows, one for columns.
Right now, my program detects if a value is in the table or not.
However, how could I highlight each value found in the table when the word is found?
Code:
//GENERATE TABLE
const table = document.querySelector('table');
function GenerateTable(x, y) {
for (let column = 0; column < x; column++) {
const newRow = table.insertRow();
for (let row = 0; row < y; row++) {
newRow.insertCell().appendChild(document.createElement('INPUT'));
}
}
let cells = document.querySelectorAll('td > input');
for (const x of cells) {
x.maxLength = 1;
x.type = 'text';
const index = [...cells].indexOf(x);
x.onkeyup = function() {
if (this.value != '' && cells[index + 1]) {
cells[index + 1].focus();
}
}
}
}
GenerateTable(5, 5)
//FIND WORDS
const input = document.getElementById('inputSearch');
function SubmitSearch() {
console.clear();
//Find Rows
const arrayX = [];
for (const row of table.rows) {
for (const cell of row.cells) {
const valueCell = cell.firstChild.value.toLowerCase();
arrayX.push(valueCell)
}
}
const values = chunkArray(arrayX, table.rows[0].cells.length);
const valuesX = values.map(x => x.join(''));
const foundX = valuesX.find(e => e.includes(input.value.toLowerCase()));
//Find Columns
const arrayY = [];
for (let a = 0; a < values.length; a++) {
for (let b in values) {
arrayY.push(values[b][a]);
}
}
let valuesY = chunkArray(arrayY, table.rows[0].cells.length);
valuesY = valuesY.map(x => x.join(''));
const foundY = valuesY.find(e => e.includes(input.value.toLowerCase()));
console.log(`Rows values: ${JSON.stringify(valuesX)}`);
console.log(`Columns values: ${JSON.stringify(valuesY)}`);
if (foundX || foundY) {
console.log(`Word found!`);
} else {
console.log('Word not found')
}
}
function chunkArray(x, chunk) {
const array = [];
while (x.length) {
array.push(x.splice(0, chunk));
}
return array;
}
<table></table>
<br>
<input type="text" id="inputSearch">
<button id="search" onclick="SubmitSearch()"> Find Words </button>
An example to illustrate my objective would be:
Thanks so much!
Please note that diagonal and reversed search is not to be taken in consideration in my program
You were looking for the index of the arrays,
Array.prototype.find returns the item if it finds it
Array.prototype.findIndex returns the index if it finds it and -1 otherwise
Because of Array indexing you have to add 1 to the return value of Array.prototype.findIndex
If the word was found on the column, the row wouldn't have the valid index and vice-versa.
So I used the index I got from the Array.prototype.findIndex and used it get the word in that row or column then I used String.prototype.search to get the index from which the word that was found started from and returned that as the row (or column) number
// I would advise you stop using inline event handlers (onevent)
const button = document.getElementById('search');
const table = document.querySelector('table');
function GenerateTable(x, y) {
for (let column = 0; column < x; column++) {
const newRow = table.insertRow();
for (let row = 0; row < y; row++) {
newRow.insertCell().appendChild(document.createElement('INPUT'));
}
}
let cells = document.querySelectorAll('td > input');
for (const x of cells) {
x.maxLength = 1;
x.type = 'text';
const index = [...cells].indexOf(x);
x.onkeyup = function() {
if (this.value != '' && cells[index + 1]) {
cells[index + 1].focus();
}
}
}
}
GenerateTable(5, 5)
//FIND WORDS
const input = document.getElementById('inputSearch');
function SubmitSearch() {
console.clear();
//Find Rows
const arrayX = [];
const searchWord = input.value.toLowerCase(); // We use this a lot so its best to store it in a value
[...document.querySelectorAll('td.found')].forEach(cell => cell.classList.remove('found')); // To reset the styles for the cells
for (const row of table.rows) {
for (const cell of row.cells) {
const valueCell = cell.firstChild.value.toLowerCase();
arrayX.push(valueCell)
}
}
const values = chunkArray(arrayX, table.rows[0].cells.length);
const valuesX = values.map(x => x.join(''));
let foundX = valuesX.findIndex(e => e.includes(searchWord));
//Find Columns
const arrayY = [];
for (let a = 0; a < values.length; a++) {
for (let b in values) {
arrayY.push(values[b][a]);
}
}
let valuesY = chunkArray(arrayY, table.rows[0].cells.length);
valuesY = valuesY.map(x => x.join(''));
let foundY = -1;
if (foundX < 0) foundY = valuesY.findIndex(e => e.includes(searchWord));
console.log(`Rows values: ${JSON.stringify(valuesX)}`);
console.log(`Columns values: ${JSON.stringify(valuesY)}`);
if (foundY > -1 || -1 < foundX) {
console.log(`Word found!`);
if (foundX < 0) {
foundX = valuesY[foundY].search(searchWord);
// I got the rows and selected the rows the word were found in, then iterated through its children picking out the column to get its cell and added the class found with styling
[...table.rows].slice(foundX, foundX + searchWord.length).forEach(row => row.children[foundY].classList.add('found'));
}
if (foundY < 0) {
foundY = valuesX[foundX].search(searchWord);
// I got the columns, then selected the particular row the word was found in, then iterated through its children and added the class found with styling
[...table.rows[foundX].children].slice(foundY, foundY + searchWord.length).forEach(col => col.classList.add('found'));
}
} else console.log('Word not found');
}
function chunkArray(x, chunk) {
const array = [];
while (x.length) {
array.push(x.splice(0, chunk));
}
return array;
}
td.found {
border: 2px solid yellow;
}
td.found input {
border: none;
outline: none;
}
<table></table>
<br>
<input type="text" id="inputSearch">
<button id="search" onclick="SubmitSearch()"> Find Words </button>

Creating a Word Find grid

I am attempting to create a grid that contains one letter in each box (like a Word Find puzzle).
I have successfully created a grid that shows w/ the determined number of cols/rows, but when I attempt to put one letter in each box, I get the following ten times in each box instead of a single letter:
[object
Object]
Here is the JavaScript:
$(function() {
var letters = [
'rzeabppssgcddrvddydtjrkei', // 1
'cezcqubhniittonieqerbiuvm', // 2
'jqcjnasionsncvbsrwtabddsu', // 3
'olselesitneagittrjanreinv', // 4
'nqnaisdenmeibvurellsnrioc', // 5
'ydnlevrnyeaidrwifkufmsuis', // 6
'dcccjeeaogsemudbeemefaptn', // 7
'evonsqpdepislsnudnurwjbpo', // 8
'grytiunnafsexattmtclaimoi', // 9
'pnqrhocbiieeinoitacilppat', // 10
];
var letter = [];
function splitRows(arr, arr2) {
for (let i=0; i < arr.length; i++) {
arr[i].split();
for (let j=0; j < arr.length; j++) {
arr2[j] = arr[i][j];
}
}
}
splitRows(letters, letter);
function* gen(arr) {
for(i=0; i < arr.length; i++) {
yield arr[i];
}
}
function generateGrid(rows, cols, arr) {
var grid = "<table>";
for(row = 1; row <= rows; row++) {
grid += "<tr>";
for(col = 1; col <= cols; col++) {
grid += "<td>";
for(let i=0; i < arr.length; i++) {
grid += gen(arr).next(); // not sure if the .next() generator works yet
}
grid += "</td>"; // 'letters' needs to input the next letter in letters each time it is called
}
grid += "</tr>";
}
return grid;
}
$("#tableContainer").append(generateGrid(26, 22, letter));
});
The first function is intended to take rows and split them into singular letters (eventually taking rows as an input, but for testing purposes I have them in an array)
The second function is a generator to insert into the generateGrid() function that is used to generate the next letter in the sequence each time a box is created.
You should convert your string data to a matrix first then you can run the matrix through a table.
The following jQuery plugin clears the table and replaces it with rows and columns based on the data.
Note: I also added in tag name validation, in the case where the element the plugin was being invoked upon was not a <table> element.
var DEBUG_EXPERIMENTAL = false;
initializePlugins(); // Forward Declaration of jQuery plugins
let rawStringData = `
rzeabppssgcddrvddydtjrkei
cezcqubhniittonieqerbiuvm
jqcjnasionsncvbsrwtabddsu
olselesitneagittrjanreinv
nqnaisdenmeibvurellsnrioc
ydnlevrnyeaidrwifkufmsuis
dcccjeeaogsemudbeemefaptn
evonsqpdepislsnudnurwjbpo
grytiunnafsexattmtclaimoi
pnqrhocbiieeinoitacilppat
`;
$('.word-search').buildWordSearch(rawStringData, 'letter');
$('.letter').enableHighliting('highlight');
function initializePlugins() {
(($) => {
$.stringToMatrix = function(str) {
return str.trim().split('\n').map(row => row.trim().split(''));
};
$.fn.buildWordSearch = function(stringData, cellClass) {
this.throwErrorIfNotType('TABLE');
return this.append($('<tbody>')
.append($.stringToMatrix(stringData).map(row => {
return $('<tr>').append(row.map(col => {
return $('<td>').addClass(cellClass).text(col);
}));
})));
};
$.fn.throwErrorIfNotType = function(expectedTagName) {
let actualTagName = this.prop('tagName');
if (actualTagName !== expectedTagName) {
throw Error(`Element '${actualTagName}' is not a '${expectedTagName}'!`);
}
};
$.fn.getCell = function(x, y) {
return this.find(`tr:nth-child(${y + 1}) td:nth-child(${x + 1})`);
};
$.fn.enableHighliting = function(cls) {
return this.each(() => {
this.on({
mouseover: function() {
let $table = $(this).closest('table');
let $row = $(this).closest('tr');
let rowIndex = $row.index();
let colIndex = $(this).index();
let rowCount = $table.find('tbody tr').length;
let colCount = $row.find('td').length;
// Hightlights diagonals.
if (DEBUG_EXPERIMENTAL) {
let limit = rowCount;
let xNeg = colIndex - 1;
let xPos = colIndex + 1;
let yNeg = rowIndex - 1;
let yPos = rowIndex + 1;
while (limit > 0) {
if (xNeg > -1 && yNeg > -1) {
$table.getCell(xNeg, yNeg).addClass(cls);
}
if (xPos < colCount && yNeg > -1) {
$table.getCell(xPos, yNeg).addClass(cls);
}
if (xNeg > -1 && yPos < rowCount) {
$table.getCell(xNeg, yPos).addClass(cls);
}
if (xPos < colCount && yPos < rowCount) {
$table.getCell(xPos, yPos).addClass(cls);
}
xNeg--;
xPos++;
yNeg--;
yPos++;
limit--;
}
}
$row.addClass(cls);
$table.find(`td:nth-child(${colIndex + 1})`).addClass(cls);
},
mouseout: function() {
let $table = $(this).closest('table');
let $row = $(this).closest('tr');
let rowIndex = $row.index();
let colIndex = $(this).index();
let rowCount = $table.find('tbody tr').length;
let colCount = $row.find('td').length;
// Un-hightlights diagonals.
if (DEBUG_EXPERIMENTAL) {
let limit = rowCount;
let xNeg = colIndex - 1;
let xPos = colIndex + 1;
let yNeg = rowIndex - 1;
let yPos = rowIndex + 1;
while (limit > 0) {
if (xNeg > -1 && yNeg > -1) {
$table.getCell(xNeg, yNeg).removeClass(cls);
}
if (xPos < colCount && yNeg > -1) {
$table.getCell(xPos, yNeg).removeClass(cls);
}
if (xNeg > -1 && yPos < rowCount) {
$table.getCell(xNeg, yPos).removeClass(cls);
}
if (xPos < colCount && yPos < rowCount) {
$table.getCell(xPos, yPos).removeClass(cls);
}
xNeg--;
xPos++;
yNeg--;
yPos++;
limit--;
}
}
$row.removeClass(cls);
$table.find(`td:nth-child(${colIndex + 1})`).removeClass(cls);
}
});
});
};
})(jQuery);
}
.word-search {
border: 2px solid #000;
border-collapse: collapse;
}
.word-search td {
width: 1.25em;
height: 1.25em;
line-height: 1.25em;
text-align: center;
}
.highlight {
background: #FFD;
}
.letter.highlight:hover {
background: #FF0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="word-search"></table>

How do I style this code using html and css?

The code below is for listing blogger posts within a Label Name, if the post has the specific Label Name it will be shown in this list. I would like to be able to change the appearance of how everything is displayed by changing where the post image would look, and where the title would look, change background color, add borders, shadows change the font etc ...(I know how to change the appearance with css, but I do not know how to integrate the code below with css and html) At the moment the code shows the title and the right of the title the image.
var startIndex = 1;
var maxResults = 5;
var allResults = [];
function sendQuery12()
{
var scpt = document.createElement("script");
scpt.src = "https://levon-ltr.blogspot.com//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;
if( entry.media$thumbnail != undefined ){
var imageThumb = entry.media$thumbnail.url ;
} else {
var imageThumb = 'https://i.imgur.com/PqPqZQN.jpg' ;
}
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");
var postImage = document.createElement("img");
a1E.href = url;
a1E.textContent = title;
postImage.src = imageThumb;
liE.appendChild(a1E);
liE.appendChild(postImage);
//elmt.appendChild(liE);
allResults.push(liE);
}
break;
}
}
}
if (feed.entry.length >= maxResults)
{
startIndex += maxResults;
sendQuery12();
} else {
printArrayResults();
}
}
}
sendQuery12();
<div>
<ul id="postList12"></ul>
</div>
This creates stuff you can style with CSS. For example:
#postList12 li {
border: 1px solid blue;
}
Use the inspector in your browser to see what it makes. If you want to change the order of elements or add new ones you’ll have to edit the script to do that.

Categories

Resources