I’m a beginner in javascript and im having a few problems with my code rn
First of all, sorry for the long and weird question
(i will share all of my code as i fetch the data from an url along with examples of the calls results)
function displayImage(postId) {
const img = document.createElement("img");
img.src = `http://10.0.0.17:7099/v1_api/blogimg/abcdef/${postId}/0.png`;
img.alt = "Blog Image";
img.classList.add("img-responsive");
img.addEventListener("click", function () {
window.location.href = `blog-item.html?id=${postId}`;
});
return img;
}
document.addEventListener("DOMContentLoaded", function () {
let skip = 0;
const postsPerPage = 2;
const baseUrl = "http://10.0.0.17:7099/v1_api/bloglist/abcdef";
const urlCategories = "http://10.0.0.17:7099/v1_api/blogstatistics/abcdef";
const postsContainer = document.getElementById("posts-container");
const paginationContainer = document.getElementById("pagination");
const categoriesContainer = document.getElementById("blog-categories");
const tagsContainer = document.getElementById("tag-cloud");
const recentPostsContainer = document.querySelector(".widget-recent-post");
function fetchPosts(skip) {
const url = `${baseUrl}?skip=${skip}&take=${postsPerPage}&requireTotalCount=true`;
fetch(url)
.then((response) => response.json())
.then((data) => {
const totalRecords = data.totalRecordCount;
const posts = data.rows.sort(
(a, b) => new Date(b.creation) - new Date(a.creation)
);
const numPages = Math.ceil(totalRecords / postsPerPage);
function displayPosts(page) {
postsContainer.innerHTML = "";
const start = (page - 1) * postsPerPage;
const end = start + postsPerPage;
const paginatedPosts = posts.slice(start, end);
paginatedPosts.forEach((post) => {
const postElement = document.createElement("div");
postElement.classList.add("blog-post");
postElement.innerHTML = `
<example></example>?
`;
const imgContainer = displayImage(post.id);
postElement.insertBefore(imgContainer, postElement.firstChild);
postsContainer.appendChild(postElement);
});
const pagination = Array.from(
{ length: numPages },
(_, index) => index + 1
)
.map(
(pageNum) =>
`<li class="page-item ${
pageNum === page ? "active" : ""
}"><a href="#" class="page-link" data-page="${pageNum}">${pageNum}</a></li>`
)
.join("");
paginationContainer.innerHTML = `
<li class="page-item ${
page === 1 ? "disabled" : ""
}"><a href="#" aria-label="Start" class="page-link" data-page="1">Inicio</a></li>
<li class="page-item ${
page === 1 ? "disabled" : ""
}"><a href="#" aria-label="Previous" class="page-link" data-page="${
page - 1
}">Anterior</a></li>
${pagination}
<li class="page-item ${
page === numPages ? "disabled" : ""
}"><a href="#" aria-label="Next" class="page-link" data-page="${
page + 1
}">Siguiente</a></li>
<li class="page-item ${
page === numPages ? "disabled" : ""
}"><a href="#" aria-label="End" class="page-link" data-page="${numPages}">Final</a></li>
`;
const pageLinks = document.querySelectorAll(".page-link");
pageLinks.forEach((link) => {
link.addEventListener("click", () => {
const pageNum = parseInt(link.getAttribute("data-page"));
skip = (pageNum - 1) * postsPerPage;
fetchPosts(skip);
});
});
}
displayPosts(1);
})
.catch((error) => console.error("Error obtaining posts", error));
}
function fetchRecentPosts() {
const url = `${baseUrl}?take=3&requireTotalCount=true`;
fetch(url)
.then((response) => response.json())
.then((data) => {
const posts = data.rows.sort(
(a, b) => new Date(b.creation) - new Date(a.creation)
);
posts.forEach((post) => {
const postItem = document.createElement("div");
postItem.classList.add("media");
postItem.innerHTML = `
<div class="media-left">
<a href="blog-item.html?id=${post.id}">
<img class="media-object" src="https://10.0.0.17:7099/v1_api/blogimg/abcdef/${
post.id
}/0.png" alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading"><a href="blog-item.html?id=${
post.id
}">${post.title}</a></h4>
<ul>
<li><a href="blog-item.html?id=${post.id}">${
post.usrName
}</a></li>
<li>${new Date(post.creation).toLocaleDateString()}</li>
</ul>
</div>
`;
recentPostsContainer.appendChild(postItem);
});
})
.catch((error) => console.error("Error :", error));
}
function fetchCategories() {
fetch(urlCategories)
.then((response) => response.json())
.then((data) => {
const categories = data.rows.filter((row) => row.rectype === 0);
const categoriesList = categories
.map(
(category) => `
<li>
<i class="fa fa-angle-double-right"></i>
<a href="#" data-id="${category.id}" class="category-link">${category.description}</a>
<a href="#" class="cat-counter">(${category.Count})</a>
</li>
`
)
.join("");
categoriesContainer.innerHTML = categoriesList;
const categoryLinks =
categoriesContainer.querySelectorAll(".category-link");
categoryLinks.forEach((link) => {
link.addEventListener("click", (event) => {
event.preventDefault();
const categoryId = link.getAttribute("data-id");
fetchPostsByCategory(categoryId);
});
});
})
.catch((error) =>
console.error("Error al obtener las categorías:", error)
);
}
function fetchPostsByCategory(categoryId) {
const url = `${baseUrl}?category=${categoryId}&skip=0&take=${postsPerPage}&requireTotalCount=true`;
fetch(url)
.then((response) => response.json())
.then((data) => {
const totalRecords = data.totalRecordCount;
const posts = data.rows.sort(
(a, b) => new Date(b.creation) - new Date(a.creation)
);
const numPages = Math.ceil(totalRecords / postsPerPage);
displayPosts(posts, numPages);
})
.catch((error) => console.error("Error obtaining posts:", error));
}
function fetchTags() {
fetch(urlCategories)
.then((response) => response.json())
.then((data) => {
const tags = data.rows.filter((row) => row.rectype === 1);
const tagsList = tags
.map(
(tag) => `
<a href="#">${tag.description}</a>
`
)
.join("");
tagsContainer.innerHTML = tagsList;
})
.catch((error) =>
console.error("Error al obtener las etiquetas:", error)
);
}
fetchPosts(skip);
fetchRecentPosts();
fetchCategories();
fetchTags();
document.addEventListener("click", function (event) {
if (event.target.classList.contains("readmore")) {
const postId = event.target.getAttribute("data-id");
window.location.href = `blog-item.html?id=${postId}`;
}
});
});
That is all my, im going to explain it a bit
Function fetchPosts(skip): This function collects all the data from an url query and then they are shown (this one works as intended and initially no need to change anything except pagination)
- const pagination (lane 78) it should collect the total count of posts (by id) then print it on your typical pagination thingy, this works as intended, but the problem comes at the moment of changing the “active” class where it always stays at one (tho you can propperly navigate thru the pages) id also like to make it so there is a limit of numbers you can see and click (example, there are 20 pages in total, so if you are in page 1 you should only be able to go from page 1 to 10, then if on page 5 from 1 to 15 etc)
fetchRecentPosts(): working as intended
fetchCatecories(): working as intended
fetchPostByCategory():this is my second problem, when clicking on a post category (rows.description) it should call to fetchPosts but then only show the post with the same category as the one clicked (post.category) using this url: http://10.0.0.17:7099/v1_api/bloglistCat/abcdef/
{category ID}
fetchTags(): working as intended
fetchPostByTag(): this needs to be done still but same as ByCategory, this time using http://10.0.0.17:7099/v1_api/bloglistTag/abcdef/Procesos/%7Bdescription%7D
this are 2 examples of my url calls:
baseUrl:
"usrName": "JA",
"id": 6,
"title": "Procesos contables habituales",
"categoryid": 2,
"category": "Finances",
"abstract": "Sample Text",
"img": "blogimg/abcdef/6/0.png",
"creation": "2024-05-10T11:18:04.953",
"taglist": "["Industry"]"
},
{
categoryUrl:
{
"rows": [
{
"Count": 2,
"description": "Industry",
"category": 0,
"rectype": 1
},
{
"Count": 5,
"description": "Finances",
"category": 2,
"rectype": 0
}
],
"requeryError": ""
}
Where rectype = 0 is category and rectype = 1 are tags
Now, finally my html so you knows how it should be organized:
<body>
<header>
<div class="navbar navbar-default navbar-top">
<div class="container">
<div class="navbar-header">
<!-- Stat Toggle Nav Link For Mobiles -->
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<i class="fa fa-bars"></i>
</button>
<!-- End Toggle Nav Link For Mobiles -->
<!--a class="navbar-brand" href="index.html"></a-->
<a title="runit" href="index.html" class="logo-link">
<img src="images/Logotipo.png" alt="Logo" class="logo-img">
</a>
</div>
<div class="navbar-collapse collapse">
<!-- Start Navigation List -->
<ul class="nav navbar-nav navbar-right">
<li>
<a href="index.html">Inicio</a>
</li>
<li>
<a href="about.html">Sobre nosotros</a>
</li>
<li>
<a href="service.html">Servicios y Productos</a>
</li>
<li>
<a href="portfolio.html">Portfolio</a>
</li>
<li>
<a class="active" href="blog.html">Blog</a>
</li>
<li><a href="contact.html">Contacto</a>
</li>
</ul>
<!-- End Navigation List -->
</div>
</div>
</div>
</header>
<!-- Start Header Section -->
<div class="page-header-blog">
<div class="overlay">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Blog</h1>
</div>
</div>
</div>
</div>
</div>
<!-- End Header Section -->
<!-- Start Blog Page Section -->
<div class="container">
<div class="row">
<!-- Start Blog Body Section -->
<div class="col-md-8 blog-bodyt">
<!-- Start Blog Body -->
<div class="col-md-8" id="posts-container" class="scroll">
<!-- Blog Content comes here -->
</div>
<!-- End Blog Body Section -->
<!-- Start Pagination -->
<nav>
<ul id="pagination" class="pagination">
</ul>
</nav>
<!-- End Pagination -->
</div>
<!-- End Blog Body Section -->
<!-- Start Sidebar Section -->
<div class="col-md-4 sidebar right-sidebar">
<!-- Start Recent Post Widget -->
<div class="widget widget-recent-post">
<div class="section-heading-2">
<h3 class="section-title">
<span>Latest Posts</span>
</h3>
</div>
<div id="posts-container">
</div>
</div>
<!-- End Recent Post Widget -->
<!-- Blog categories widget -->
<div class="widget widget-categories">
<div class="section-heading-2">
<h3 class="section-title">
<span>Categories</span>
</h3>
</div>
<ul id="blog-categories">
</ul>
</div>
<!-- End Blog categories widget -->
<!-- Tag Cloud Widget -->
<div class="widget widget-tags">
<div class="section-heading-2">
<h3 class="section-title">
<span>Tags Popular</span>
</h3>
</div>
<div class="tagcloud" id="tag-cloud">
</div>
</div>
<!-- End Tag Cloud Widget -->
</div>
<!-- End Sidebar Section -->
</div>
</div>
<!-- End Blog Page Section -->
</body>
for the pagination i tried following this tutorial (starts at min 5:40), but op is using a different way to keep track of the current page
About the tag/category part i cant really find anything similar to what I wanted so i was hoping any of you could give me more insight on how to make it work
Thanks in advance, and sorry again for the long question, im still a bit new to stack over