Skip to content

How to make "Show more" feature for articles

Bugo edited this page Jan 31, 2022 · 2 revisions

First, thanks to Mick for this idea. He uses jQuery, but I decided to implement vanilla JS.

So, you need to do 4 simple steps.

  1. Open /Sources/Entities/FrontPage.php, replace $data['total'] = $article->getTotalCount(); with $data['total'] = $limit = $article->getTotalCount();:
$data['total'] = $limit = $article->getTotalCount();
  1. Open /Themes/default/FrontPage.template.php, and add this code to the end:
function show_more_button(int $num_items = 8, int $start_elem = 1)
{
	global $txt, $modSettings;

	echo '
	<div id="showMore" class="button" style="display: block; margin: 0 auto; margin-top: 1em"><i class="fas fa-plus"></i> Show more...</div>
	<script>
		window.addEventListener("DOMContentLoaded", function() {
			const el = document.querySelectorAll(".lp_frontpage_articles > div");

			if (! el) return;

			Object.values(el).slice(', $start_elem, ', ', $modSettings['lp_num_items_per_page'] +  $start_elem, ').forEach((item) => {
				item.classList.toggle("hidden")
			});

			document.getElementById("showMore").addEventListener("click", function (e) {
				const el = document.querySelectorAll(".lp_frontpage_articles > div.hidden");

				Object.values(el).slice(0, ', $num_items, ').forEach((item) => fadeIn(item, 500));

				const el2 = document.querySelectorAll(".lp_frontpage_articles > div.hidden");

				if (el2.length === 0) {
					fadeOut(document.getElementById("showMore"), 2000);
				}
			}, false);

			function fadeOut(el, ms) {
				if (ms) {
					el.style.transition = `opacity ${ms} ms`;
					el.addEventListener(\'transitionend\',
						function(event) {
							el.classList.toggle("hidden");
						},
						false
					);
				}

				el.style.opacity = \'0\';
			}

			function fadeIn(elem, ms) {
				elem.style.opacity = 0;
				elem.classList.toggle("hidden");

				if (ms) {
					let opacity = 0;
					const timer = setInterval(function() {
						opacity += 50 / ms;

						if (opacity >= 1) {
							clearInterval(timer);
							opacity = 1;
						}

						elem.style.opacity = opacity;
					}, 50);

					return;
				}

				elem.style.opacity = 1;
			}
		});
	</script>';
}
  1. Then, find this line <div class="col-xs-12 col-sm-6 col-md-', $context['lp_frontpage_num_columns'], '"> (in the template_show_articles() function), and add hidden class:
<div class="col-xs-12 col-sm-6 col-md-', $context['lp_frontpage_num_columns'], ' hidden">
  1. Finally, replace show_pagination('bottom'); with show_more_button();. That's all!

Of course, you can use show_more_button(); in other templates (in the same file).