Javascript кнопка показать еще

Кнопка «Показать еще»

Несколько примеров, как сделать AJAX подгрузку записей из базы данных кликом на кнопку «Показать еще».

Первый вариант: отдельный AJAX-обработчик

В тело страницы помещается PHP-скрипт, который выводит только первые три записи из таблицы `prods` и кнопку «Показать еще».

prepare("SELECT * FROM `prods` LIMIT 3"); $sth->execute(); $items = $sth->fetchAll(PDO::FETCH_ASSOC); // Кол-во страниц $sth = $dbh->prepare("SELECT COUNT(`id`) FROM `prods`"); $sth->execute(); $total = $sth->fetch(PDO::FETCH_COLUMN); $amt = ceil($total / 3); ?> 
Показать еще

При клике на кнопку отправляется AJAX-запрос на скрипт ajax.php с GET-параметром page=2 (при следующим клике – page=3 и т.д.), скрипт возвращает следующие три записи, далее они вставляются в конец списка товаров методом jquery append() . Когда все записи показаны, кнопка скрывается.

Код ajax.php

prepare("SELECT * FROM `prods` LIMIT , "); $sth->execute(); $items = $sth->fetchAll(PDO::FETCH_ASSOC); foreach ($items as $row) < ?>

CSS-стили:

/* Кнопка */ .showmore-bottom < text-align: center; >.showmore-bottom a < padding: 20px 30px; display: inline-block; border: 1px solid #3f2aff; border-radius: 100px; color: #fff; font-weight: 500; font-size: 16px; text-align: center; vertical-align: top; background-color: #3f2aff; text-decoration: none; margin-bottom: 20px; >/* Вывод товаров */ .prod-list < overflow: hidden; margin: 0 0 20px 0; >.prod-item < width: 174px; height: 230px; float: left; border: 1px solid #ddd; padding: 20px; margin: 0 20px 20px 0; text-align: center; border-radius: 6px; >.prod-item-img < width: 100%; >.prod-item-name < font-size: 13px; line-height: 16px; >.prod-list .prod-item:nth-child(3n)

Пример в действии:

Второй вариант: обработчик «Пагинатор»

Во втором примере, AJAX-запрос отправляется сам на себя. Скрипт выводит записи в зависимости от значения переменной $_GET[‘page’] , которое содержит номер страницы (скрипт основан на пагинаторе).

Стоит отметить, что данный пример избавляет от дублирования кода, но работает медленнее, т.к. через AJAX идет полный HTML-код страницы.

prepare("SELECT SQL_CALC_FOUND_ROWS * FROM `prods` LIMIT , "); $sth->execute(); $items = $sth->fetchAll(PDO::FETCH_ASSOC); // Узнаем сколько всего записей в БД $sth = $dbh->prepare("SELECT FOUND_ROWS()"); $sth->execute(); $total = $sth->fetch(PDO::FETCH_COLUMN); $amt = ceil($total / $limit); ?> 
Показать еще

Результат:

Комментарии 2

Здравствуйте!Очень благодарен за Ваш пост!Я использую второй вариант Вашего кода. Архитектура моего приложения — MVC, работа с базой данных через ORM RedBeans. Кнопка Показать еще пропадает при полном выводе данных из таблицы.
Но есть вопрос: подгруженные данные приклике не выводятся в виде. Т.е. они выводятся, курсор их видит и при клике на их место происходит переход по их ссылке (в данном случае на страницу карточки товара).Я не сильно какой кодер. Всю голову сломал, но так и не понял причину.Запрос к DB — $products = \R::find(‘product’, «LIMIT $start, $perpage»);Если нетрудно поделитесь соображениями по этому поводу.Спасибо!Виталий.

Авторизуйтесь, чтобы добавить комментарий.

Другие публикации

Примеры использования PDO MySQL

В статье приведены основные примеры работы с расширением PHP PDO. Такие как подключение к БД, получение, изменение и.

Примеры отправки AJAX JQuery

AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.

После отправки формы сохранить позицию скролла

В больших формах, с несколькими кнопками «Отправить/сохранить» есть одна проблема – после ее отправки браузер обновит.

Источник

How to Implement a “Load More” Button With Vanilla JavaScript

Jemima Abu

Jemima Abu Last updated Jul 29, 2022

We’ve covered Pagination and Infinite Scrolling in previous tutorials. On this occasion, we’ll be looking at another method of controlling how content is displayed on a page: using a “Load More” button.

A “Load More” button adds more content to a page when clicked by a user. This is a common approach for blogs as it allows the user to decide how and when information is displayed.

Here’s a look at the final product we’ll work on today—scroll to the bottom of the pen and click the button to add more content to the page:

1. Card Container and Button HTML

We’ll start by placing the container for our cards on the page. We’ll be adding the cards to the container using JavaScript so the div will be empty.

Our implementation includes a “load more” button and also displays the current number of cards being shown and the total number of cards available. We’ll include these features in a card-actions div. The content in card-count and card-total will be added with JavaScript.

2. Styling the Cards and Button

The cards we’ll be adding to the card-container div will have a classname of “card”.

transition: all 200ms ease-in-out; 
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); 

We’ll style our load-more button in a similar manner to the cards and add a disabled pseudo-selector to show when the end of the cards have been reached.

justify-content: space-between; 
transition: all 200ms ease-in-out; 
box-shadow: 0 1px 9px rgba(0, 0, 0, 0.2); 
background-color: #eaeaea !important; 

3. Adding Functionality With JavaScript

This is what the functional implementation for the load more button will look like:

  1. Define a number of cards to be added to the page each time the user clicks the button.
  2. Detect when the total number of cards have been added and disable the button.

Defining Constants

First, get all the elements we’ll need from our DOM:

const cardContainer = document.getElementById("card-container"); 
const loadMoreButton = document.getElementById("load-more"); 
const cardCountElem = document.getElementById("card-count"); 
const cardTotalElem = document.getElementById("card-total"); 

Now we need to define our global variables.

We’ll need a value for the max number of cards to be added to the page. If you’re getting your data from a server, this value is the length of the response from the server. Let’s initialise a card limit of 99.

The cardTotalElem is the element for displaying the max number of cards on the page so we can set the innerHTML to the cardLimit value;

cardTotalElem.innerHTML = cardLimit; 

Then we’ll define a variable for how many cards we want to increase the page by:

Much like with our infinite scrolling tutorial, we’ll want to know how many “pages” we’ll have i.e. how many times can we increase the content till we reach the max limit. For example, with our defined cardLimit and cardIncrease variables, we can increase the content 10 times (assuming we’ve already loaded the first 9 elements) until we reach the limit. We’ll do this by dividing the cardLimit by the cardIncrease .

const pageCount = Math.ceil(cardLimit / cardIncrease); 

Then we’ll define a value to determine which page we’re on:

Creating a New Card

Now we have all our constants, let’s make a function to add a new card to the card container. We’ll set the innerHTML of our cards to the index value so we can keep track of the number of cards we’re adding.

A fun feature in this demo is that each card has a randomly generated background color.

const h = Math.floor(Math.random() * 360); 
const card = document.createElement("div"); 
card.style.backgroundColor = getRandomColor(); 
cardContainer.appendChild(card); 

We can also apply this function to our load-more button on page load to give it a random background color as well:

loadMoreButton.style.backgroundColor = getRandomColor(); 

Adding Cards to the Container

We’ll add our cards to our container using a similar functionality to what we used in the Infinite Scrolling tutorial.

First, determine the range of cards to be added to the page. The addCards function will accept a pageIndex parameter, which will update the global currentPage value. If we’re on page 1, we’ll add cards 1 to 9. If we’re on page 2, we’ll add cards 10 to 18 and so on.

We can define that mathematically as:

const addCards = (pageIndex) =>  
const startRange = (pageIndex - 1) * cardIncrease; 
const endRange = pageIndex * cardIncrease; 
for (let i = startRange + 1; i  endRange; i++)  

In this function, our start range will always be one less than the value we’re trying to get (i.e. on page 1, the start range is 0, on page 2, the start range is 9) so we’ll account for that by setting the value of our for loop index to startRange + 1 .

Detecting When Card Limit is Reached

A limit we’ll have to look out for is the endRange number. If we’re on the last page, we’ll want our end range to be the same as the cardLimit . For instance, if we have a cardLimit of 75 and a cardIncrease of 10 and we’re on page 8, our startRange will be 70 and our endRange value should be 75.

We’ll modify our addCards function to account for this:

const addCards = (pageIndex) =>  

Источник

Открытие и закрытие контента на jQuery

Открытие и закрытие контента на jQuery

По своей сути «показать полностью» и «показать еще» это одно и тоже, но для каждого варианта в этой заметке используются разные решения.

В интернете масса различных примеров, как показать и скрыть контент, нажав на кнопку, но все они, как правило, реализованы для одного конкретного блока. В данной теме оба примера можно применять к неограниченному их числу.

Скрипты используемые в этих примерах сделаны для библиотеки jQuery

Кнопка «показать еще»

В этом примере часть контента с классом hide-content скрывается и показывается нажатием на кнопку или любой другой элемент с классом show-more

Каждая кнопка и скрытый текст должны находиться в контейнере content-block

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

CSS в этом примере не выкладываю, т.к. оформление тут индивидуальное, но если кому нравится эта кнопка, ее код представлен ниже.

Источник

Как реализовать кнопку «Показать еще »?

Есть блок с отзывами, по нажатию на кнопку «Показать еще» нужно сделать чтобы появлялись следующих два отзыва и так до последнего отзыва, после этого кнопка скрывалась.
Библиотеки не советовать.

Простой 2 комментария

Vlad_IT

Пробуйте что-то сделать. Мы не знаем в каком виде у вас данные, в каком виде разметка. Что не получается, спрашивайте. Это нужно писать, за вас никто не сделает.

Maksclub

Что вы хотите услышать?
Напишите код, который подгружает по аяксу два отзыва, если нет больше ответа — скрывайте кнопку

webinar

webinar

Anubis

1) Грузим первые N записей и получаем признак есть ли ещё записи после них
2) Запоминаем id последней загруженной и признак есть ли ещё
3) Если есть ещё, показываем кнопку «Загрузить ещё», на нет и суда нет, return;
4) При нажатии кнопки «Загрузить ещё» передаём сохранённый id, чтобы бэкенд грузил следующие с id меньше, чем мы передали
Повторить пока не юзер не загрузит все оставшиеся записи

Войдите, чтобы написать ответ

Браузерное расширение перестает работать после перезагрузки страницы?

Источник

Читайте также:  Сколько учить язык программирования python
Оцените статью