Using JavaScript to create a paging system for a gallery of images with a maximum number

Let me explain my current setup: I have an image gallery on my website displaying 10 images at a time along with a pagination bar. These images are populated using a loop that iterates over a JSON file. It's all working smoothly so far!

The code looks something like this: for i=0; i <10; i++ create div with styles and images[i].image;

Now, my query is: I'm looking to show the next set of 10 images on page 2. So, when a user clicks on page 2, they should see images numbered from 11 to 20. I stumbled upon the jQuery plugin called 'Jpaginate'... Do you think this plugin can help me achieve that? Could someone guide me on how to approach this using variables, counts, and objects?

Appreciate your assistance, Mike

Answer №1

Here is an example of how you can tackle this problem. While it may not be perfect, the concept is what's important. Take some inspiration from this and work towards your goal.

var imgSrc = "https://s-media-cache-ak0.pinimg.com/236x/36/a5/7b/36a57b0f0ab16e885fcc230addb695c2.jpg";
var json = [];
for (var i = 0; i < 36; i++)
  json.push({
    Title: "Title " + (i + 1),
    Source: imgSrc
  });

/*
For simplicity, I'm creating an array with 36 objects (3x3 gallery)
with 9 images per page
*/

var pageLimit = 9;
var page = 1;

showImages();

$("#btnPrevious").click(function() {
  if (pageLimit <= 9) {
    pageLimit = 9;
    page = 1;
  } else {
    page--;
    pageLimit -= 9;
  }
  showImages();
});

$("#btnNext").click(function() {
  if (pageLimit >= json.length) {
    pageLimit = json.length;
  } else {
    page++;
    pageLimit += 9;
  }
  showImages();
});

function showImages() {
  $(".images").empty();
  for (var i = pageLimit - 9; i < pageLimit; i++) {
    var template = $("<div></div>").addClass("template");

    var img = $("<img>");
    img.attr("src", json[i].Source);
    img.attr("alt", json[i].Title);

    var br = $("<br/>");

    var title = $("<span></span>").html(json[i].Title);

    template.append(img).append(br).append(title);

    $(".images").append(template);
  }
  $("#page").html("Page " + page);
}
.gallery {
  width: 100%;
  height: 500px;
  border: 1px solid black;
  background-color: lightgray;
  text-align: center;
}
.images {
  width: 90%;
  margin: 0 auto;
  height: 100%;
  margin-bottom: 15px;
}
img {
  height: auto;
  width: 33%;
  margin: 20px 5px;
}
.template {
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gallery">
  <div class="images"></div>
  <button id="btnPrevious">
    &lt; Previous
  </button>
  <span id="page"></span>
  <button id="btnNext">
    &gt; Next
  </button>
</div>

Please ignore the CSS as it was quickly put together. If anyone skilled in CSS could improve it, that would be awesome. Maybe a question within a question?

Answer №2

To customize your pagination feature, consider developing your own plugin. Make sure to keep track of the current page and update your factory accordingly.

For instance, you can iterate through a range of items on the current page by using a loop like: for i=current_page * count_per_page; i < count_per_page * (current_page + 1); i++, generate a div with corresponding styles and images[i].image;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The event.target.x attribute on the <i /> tag element

In my code, there is an <i name="documentId" onClick={this.openDocument}/> element with the onClick method defined as follows: openDocument(event) { const { name } = event.target; console.log('name', name); console.log('target&a ...

Can you tell me what that sequence of characters is at the conclusion of a styled-component?

Technology Stack: React, Typescript I believe this question may have been asked before, but I am unsure how to search for it... I am interested in creating a wrapper for the styled-components library... Here is the API reference for the specific packag ...

Constructing an Http Post URL with form parameters using the Axios HTTP client

I need assistance in creating a postHTTP request with form parameters using axios on my node server. I have successfully implemented the Java code for constructing a URL, as shown below: JAVA CODE: HttpPost post = new HttpPost(UriBuilder.fromUri (getPro ...

Creating a 2-dimensional array using Json in C# MVC: A step-by-step guide

Presently, I am utilizing this particular class public class FooResult { public int sEcho; public Foo[] aaData; internal FooResult() { sEcho = 1; aaData = new FooRepository().GetAll().ToArray(); } } new FooRepository() ...

Is it impossible to run a node.js application as a background service using npm-windows on Windows operating system?

I am attempting to utilize node-windows for executing my script as a background service. After installing node-windows globally and linking it, I created the following script: var Service = require("node-windows").Service; console.log("ent ...

Using Fullcalendar Moment to retrieve the current time plus an additional 2 hours

Trying to tackle this seemingly simple task using moment.js in conjunction with Fullcalendar. My goal is to retrieve the current time and then add two hours to it. Within the select method (or whatever terminology you prefer), I currently have: select: f ...

Tips for creating and saving an executable file using data obtained from a server

Is there a way to properly save and write data retrieved through a request or fetch function so that it remains executable? Here is an example of what I am currently doing: require('request').get('https://github.com/harujisaku/mini-player/ ...

JavaScript error type mismatch

Currently, I am utilizing select2.js to highlight a specific li element that is received as a response. var cityCounter = -1; var sul = $('.select2-search-choice'); $(".select2-input").keyup(function (e) { // TODO CODE // console.log($( ...

There was an unhandled type error stating that "undefiened" is not a function while processing a JSON

Hey there! I'm currently using JSON to send a list of songs to populate my table. The JSON response is working fine up until the controller URL. However, when I attempt to loop through it and display the details in my table, I encounter an error. $( ...

Tabulator automatically inserted 'numrow' after retrieving the data

I have a table of undetermined information (consisting of various columns and rows). I am now at the point where I need to utilize the function table.updateData(), but this function specifically requires the column id to be present in the data structure. S ...

Retrieve the element by its Id for precise targeting on a particular webpage

I'm new here and looking for some assistance, so please help if you can :) I'm working on a web page but encountered an issue that I hope you can help me solve. Here are the 3 files involved: home.html --> Main page login.html --> Page ...

What is the method for setting the height of a CSS grid item and aligning a grid item to a specific side?

Recently, I've been working on my portfolio using a CSS grid to display cards as grid items. When viewed on mobile, the cards stack on top of each other, but on desktop, I have ensured that they are displayed next to each other. Lately, I have encoun ...

Is there a method to obtain the image path in a similar manner to item.src?

I am currently utilizing freewall.js, which can be found at The images will be generated dynamically. Therefore, the HTML structure will look like this: <div class="brick"> <img src="" width="100%"> </div> Here is the corresponding J ...

Tips on how to trigger the function upon receiving the response value by concurrently running two asynchronous functions

export default { data: () =>({ data1: [], data2: [], lastData: [] }), mounted() { asynchronous1(val, (data)=>{ return this.data1 = data }) asynchronous2(val, (data)=>{ return this.data2 = data }) f ...

Python script encounters KeyError while accessing IPify VPN Checker API

I need help with using . I am trying to retrieve the value "vpn" within the "proxy" section but can't seem to get it right. req2 = requests.get(url = VPNLink + IP) data3 = req2.json() print(data3) VPN = data3[""] print(VPN) Traceback (most recent ca ...

How can I show name and value pairs as columns in SQL Server?

My database has two tables structured like this: CREATE TABLE case_form ( id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, title VARCHAR(50) NOT NULL, description TEXT NOT NULL, PRIMARY KEY (id) ) INSERT INTO case_form (id, title, descriptio ...

The OnClick function seems to be unresponsive, however, there are no error messages displaying in

Currently delving into React to enhance my skills, I decided to craft a joke generator. After establishing a local file and successfully fetching the data (jokes) to showcase on the browser, my current goal is to implement a button that, when clicked, will ...

How to Eliminate the Hashtag from the URL in AngularJS Version 1.x

I'm currently in the process of creating a web application using Angular 1.x (not Ionic, just a regular website). My goal is to eliminate the '#' from the URLs. I've already set html5mode to true and added a base tag within the head sec ...

PHP and jQuery: Using 1 Query to Retrieve Multiple JSON Strings and Looping Through Them to Populate a Multiselect

Good day everyone. I am facing an issue with a page that utilizes jQuery to .post data back to a PHP file, which then runs a query on a MySQL database and returns results in JSON format. Depending on the query output, there could be multiple JSON strings r ...

What is the best way to make message properties accessible to the public while also being able to access them within a web

Situation Our company works with various clients, some using native apps such as iPad and Android, while others use web-based platforms like websites and SmartTVs. We have a central web project that houses common assets used by all clients, including ico ...