Как добавить/удалить класс элементам коллекции?
Пытаюсь сделать галерею в которой есть карточки (картинка, название, ссылка) с пагинацией. Информацию для карточек беру из массива объектов.
Нужно при клике на элемент с классом gallery__caption добавить ему класс gallery__caption--active, а при повторном клике удалить, но чтобы у других карточек не срабатывало добавление/удаление класса gallery__caption--active.
upd: Подправил вопрос. upd new:
galleryCaption = document.querySelectorAll(".gallery__caption");
galleryCaption.forEach((item) => {
item.addEventListener("click", function (e) {
galleryCaption.forEach((el) => {
el.classList.remove("gallery__caption--active");
this.classList.add("gallery__caption--active");
item.addEventListener("click", function (e) {
e.target.classList.remove("gallery__caption--active");
});
});
});
});
const nextBtn = document.getElementById("btn_next");
const prevBtn = document.getElementById("btn_prev");
let current_page = 1;
let records_per_page = 3;
const objJson = [
{
imgLink: "../img/project-1.jpg",
title: "example title1 ",
btnLink: "https://test/example 1",
},
{
imgLink: "../img/project-2.jpg",
title: "example title 2",
btnLink:
"https://test/example 2",
},
{
imgLink: "../img/project-3.jpg",
title: "example title 3",
btnLink:
"https://test/example 3",
},
{
imgLink: "../img/project-4.jpg",
title: "example title 4",
btnLink:
"https://test/example 4",
},
{
imgLink: "../img/project-5.jpg",
title: "example title 5",
btnLink:
"https://test/example 5",
},
{
imgLink: "../img/project-6.jpg",
title: "example title 6",
btnLink: "https://test/example 6",
},
];
function prevPage() {
if (current_page > 1) {
current_page--;
changePage(current_page);
}
}
function nextPage() {
if (current_page < numPages()) {
current_page++;
changePage(current_page);
}
}
function changePage(page) {
var galleryList = document.querySelector("ul.gallery__list");
var page_span = document.getElementById("page");
// Validate page
if (page < 1) page = 1;
if (page > numPages()) page = numPages();
galleryList.innerHTML = "";
for (
var i = (page - 1) * records_per_page;
i < page * records_per_page && i < objJson.length;
i++
) {
// Создаю элементы разметки
const galleryItem = document.createElement("li");
galleryItem.classList.add("gallery__item");
galleryList.append(galleryItem);
galleryItem.innerHTML += `<img loading="lazy" src="${objJson[i].imgLink}" alt="test">`;
let galleryCaption = document.createElement("div");
galleryCaption.classList.add("gallery__caption");
galleryItem.append(galleryCaption);
const galleryTitle = document.createElement("h3");
galleryTitle.classList.add("gallery__title");
galleryTitle.textContent = objJson[i].title;
galleryCaption.append(galleryTitle);
const galleryBottom = document.createElement("div");
galleryBottom.classList.add("gallery__bottom");
galleryCaption.append(galleryBottom);
// неудачная попытка добавить gallery__caption--active к элементу с классом gallery__caption
galleryCaption = document.querySelectorAll(".gallery__caption");
galleryCaption.forEach((item) => {
item.addEventListener("click", function (e) {
e.target.classList.remove("gallery__caption--active");
this.classList.add("gallery__caption--active");
});
});
const galleryBtnLink = document.createElement("a");
galleryBtnLink.classList.add("gallery__link", "gallery-btn__item");
galleryBtnLink.setAttribute("href", objJson[i].btnLink);
galleryBtnLink.setAttribute("target", "_blank");
galleryBtnLink.textContent = "Open";
galleryBottom.append(galleryBtnLink);
}
page_span.innerHTML = page + "/" + numPages();
if (page == 1) {
prevBtn.style.visibility = "hidden";
} else {
prevBtn.style.visibility = "visible";
}
if (page == numPages()) {
nextBtn.style.visibility = "hidden";
} else {
nextBtn.style.visibility = "visible";
}
}
nextBtn.addEventListener("click", () => {
nextPage();
});
prevBtn.addEventListener("click", () => {
prevPage();
});
function numPages() {
return Math.ceil(objJson.length / records_per_page);
}
window.onload = function () {
changePage(1);
};
<ul class="list-reset gallery__list">
</ul>
<a href="javascript:void(0)" id="btn_prev">Prev</a>
<a href="javascript:void(0)" id="btn_next">Next</a>
page: <span id="page"></span>
Ответы (1 шт):
Автор решения: ksa
→ Ссылка
Как вариант...
document.querySelector('.list-reset.gallery__list').addEventListener('click', e => {
let o = e.target
o = o.closest('.gallery__caption')
if (o) o.classList.toggle('gallery__caption--active')
})
const nextBtn = document.getElementById("btn_next");
const prevBtn = document.getElementById("btn_prev");
let current_page = 1;
let records_per_page = 3;
const objJson = [{
imgLink: "../img/project-1.jpg",
title: "example title1 ",
btnLink: "https://test/example 1",
},
{
imgLink: "../img/project-2.jpg",
title: "example title 2",
btnLink: "https://test/example 2",
},
{
imgLink: "../img/project-3.jpg",
title: "example title 3",
btnLink: "https://test/example 3",
},
{
imgLink: "../img/project-4.jpg",
title: "example title 4",
btnLink: "https://test/example 4",
},
{
imgLink: "../img/project-5.jpg",
title: "example title 5",
btnLink: "https://test/example 5",
},
{
imgLink: "../img/project-6.jpg",
title: "example title 6",
btnLink: "https://test/example 6",
},
];
function prevPage() {
if (current_page > 1) {
current_page--;
changePage(current_page);
}
}
function nextPage() {
if (current_page < numPages()) {
current_page++;
changePage(current_page);
}
}
function changePage(page) {
var galleryList = document.querySelector("ul.gallery__list");
var page_span = document.getElementById("page");
// Validate page
if (page < 1) page = 1;
if (page > numPages()) page = numPages();
galleryList.innerHTML = "";
for (
var i = (page - 1) * records_per_page; i < page * records_per_page && i < objJson.length; i++
) {
// Создаю элементы разметки
const galleryItem = document.createElement("li");
galleryItem.classList.add("gallery__item");
galleryList.append(galleryItem);
galleryItem.innerHTML += `<img loading="lazy" src="${objJson[i].imgLink}" alt="test">`;
let galleryCaption = document.createElement("div");
galleryCaption.classList.add("gallery__caption");
galleryItem.append(galleryCaption);
const galleryTitle = document.createElement("h3");
galleryTitle.classList.add("gallery__title");
galleryTitle.textContent = objJson[i].title;
galleryCaption.append(galleryTitle);
const galleryBottom = document.createElement("div");
galleryBottom.classList.add("gallery__bottom");
galleryCaption.append(galleryBottom);
const galleryBtnLink = document.createElement("a");
galleryBtnLink.classList.add("gallery__link", "gallery-btn__item");
galleryBtnLink.setAttribute("href", objJson[i].btnLink);
galleryBtnLink.setAttribute("target", "_blank");
galleryBtnLink.textContent = "Open";
galleryBottom.append(galleryBtnLink);
}
page_span.innerHTML = page + "/" + numPages();
if (page == 1) {
prevBtn.style.visibility = "hidden";
} else {
prevBtn.style.visibility = "visible";
}
if (page == numPages()) {
nextBtn.style.visibility = "hidden";
} else {
nextBtn.style.visibility = "visible";
}
}
nextBtn.addEventListener("click", () => {
nextPage();
});
prevBtn.addEventListener("click", () => {
prevPage();
});
function numPages() {
return Math.ceil(objJson.length / records_per_page);
}
window.onload = function() {
changePage(1);
};
.gallery__caption--active {
color: red;
}
<ul class="list-reset gallery__list"></ul>
<a href="javascript:void(0)" id="btn_prev">Prev</a>
<a href="javascript:void(0)" id="btn_next">Next</a> page: <span id="page"></span>