Design a dynamic pagination button for my project that allows users to navigate between pages effortlessly

Can anyone assist me in creating next and previous buttons? I've been struggling with my JavaScript skills. I noticed that many people use jQuery or pure JavaScript for this. Since I'm still learning JavaScript, there are a lot of concepts I'm not familiar with yet. Thank you for your help.

Requirement: Next / Previous button to navigate to the next page and go back to the previous page if users want to revisit it.

Link to my demo: https://jsfiddle.net/hioihia123/zgjswtay/3/

body {
  font-size: 18px;
  background: url("https://www.toptal.com/designers/subtlepatterns/patterns/groovepaper.png");
  font-family: 'Gelasio', serif;
}


main {
  color: black;
  font-size: 1.1rem;
  display: flex;
  flex-direction: column;
  width:100%;
  margin-left : auto;
  margin-right: auto;
}

main div {
  width: 100%;
  padding: 6rem 5rem;
}

h2 {
  text-align: center;
  font-size: 1.2rem;
  font-weight: normal;
  margin-bottom: 6rem;
}
h1 {
  font-family: 'Ibarra Real Nova', serif;
  text-align: center;
  font-weight: 400;
  font-size: 3rem;
  text-transform: uppercase;
  margin-bottom: 6rem;
  letter-spacing: .1rem;
}

.right-page {
  margin-top: 0;
  padding-top: 0;
}
.right-page p {
  line-height: 1.4;
  text-align: justify;
  text-justify: inter-word;
}

.right-page p:first-letter {
    font-family: 'Ibarra Real Nova', serif;
    font-size: 4.5rem;
    float: left;
    margin-top: .5rem;
    margin-right: 1rem;
    line-height: .7;
}

.left-page {
    text-align: center;
    padding-top: 4rem;
}

.left-page small {
  font-style: italic;
}

.left-page img {
  max-width: 90%;
  display: block;
  margin-left: auto;
  margin-right: auto;
}


@media screen and (min-width: 900px) {
  main {
    flex-direction: row;
    with: 100%;
    max-width: 1800px;
  }
  main div {
    width: 50%;
  }
  .left-page {
    padding-top: 14rem;
  }
  .right-page {
    padding-top: 6rem;
    max-height: 100vh;
    height: 100vh;
  }
}
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title> Old book Stories</title>
  <link href="https://fonts.googleapis.com/css?family=Gelasio:400,400i|Ibarra+Real+Nova&display=swap" rel="stylesheet"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="./style.css">

</head>
<body>
<!-- partial:index.partial.html -->
<main>
  <div class="left-page">
    <img src="https://www.oldbookillustrations.com/wp-content/uploads/2017/03/there-lonely.jpg"/>
    <small>But go there, lonely,<br>
At eventide,<br>
And hearken, hearken<br>
To the lisping tide.<br>
</small>
  </div>
  <div class="right-page">
    <h2>[ 1 ]</h2>
    <h1>Depender</h1>
    <p>
      En cuanto a todas las cosas que existen en el mundo, unas dependen de nosotros,
otras no dependen de nosotros. De nosotros dependen; nuestras opiniones, nuestros
movimientos, nuestros deseos, nuestras inclinaciones, nuestras aversiones; en una
palabra, todas nuestras acciones.<br>
Así, ante toda fantasía perturbadora, está presto a decir: <i>“Tu no eres sino una
      imaginación, y en absoluto eres lo que parece”</i>, enseguida examínala con atención y
ponla a prueba, para ello sírvete de las reglas que tienes, principalmente con esta
primera que es, a saber : de si la cosa que te hace penar es del número de aquellas
que dependen de nosotros o de aquellas que no están en nuestro poder. Di sin
      titubear: <i>“Esa en nada me atañe”.</i>
    </p>
  </div>
</main>
<!-- partial -->
  
</body>
</html>

Answer №1

Why not consider adding the Previous and Next buttons to the footer or any preferred location, linking them to the relevant pages? Wouldn't this method be simple and effective for your situation?

<button onclick="location.href='https://google.com';">Previous</button>
<button onclick="location.href='https://facebook.com';">Next</button>

UPDATE

If all your pages are contained within a div inside main, navigating through them can be easily achieved by identifying the visible div, hiding it, and displaying the next or previous page based on the button clicked :)

Here's an example:

function changePage(prevOrNext) {
  var pages = document.getElementsByTagName('main')[0].children;
  for (let pageIndex = 0; pageIndex < pages.length; pageIndex++) {
    if (pages[pageIndex].style.display == "block") {
      if (prevOrNext == 1 && pageIndex < pages.length - 1) {
        pages[pageIndex].style.display = "none"
        pages[pageIndex + 1].style.display = "block"
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      } else if (prevOrNext == 0 && pageIndex > 0) {
        pages[pageIndex].style.display = "none"
        pages[pageIndex - 1].style.display = "block"
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      }
    }
  }
}

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

Infinite Scrolling in React: Troubleshooting Issues with the dataLength Parameter

A function called newsFeed is utilized within the useEffect hook to make a request to an endpoint for fetching posts made by the logged in user and users they follow. The retrieved data is then saved to the state: const [posts, setPosts] = useState([]) con ...

Unable to transform object into a primitive value using imported JSON data

https://i.sstatic.net/HcY5M.png I am currently working on creating a Vuetify component dynamically within a Nuxt project, as discussed in this Stack Overflow thread (Using different text values with Vuetify component). To achieve this, I am importing and ...

React: Updating a property in an array of objects causes properties to become undefined

My intention was simply to update a property within an object inside an array and then update the state of the array. However, I encountered an issue where all properties except the one that was updated became undefined. The code in question is as follows ...

Alert iOS that the meta og:image property tag's content has been modified once the page has finished loading

For a web project, I am in the process of integrating og:image tags. The content of the tag gets updated asynchronously after the initial page load, triggered by an HTTP call response. When iOS loads the page, it seems to fetch the tag's content righ ...

What should be used for data fetching in Next.js: SWR or traditional fetch/axios along with useEffect?

I'm currently diving into the world of Next.js and I'm eager to showcase data based on user input queries. However, I'm uncertain if leveraging useSWR is the most suitable approach to tackle this challenge because I haven't come across ...

What is causing the click event handler to only function on the initial page?

Within my code for the "fnInitComplete" : function(oSettings, json), I am utilizing a selector like $('[id^=f_]').each(function (). The data for Datatables is retrieved server-side and "bProcessing":true I am aware that my selectors are only ef ...

The AngularJS factory does not hold on to its value

I have developed a basic factory to store a value from my authService: app.factory("subfactory", function() { var subValue = {}; return { set: set, get: get }; functi ...

What steps can I take to successfully utilize $index named variables in Angular?

There is a div element in my HTML file with the following code: <div ng-repeat="loss in Model.plDetails track by $index"> <div class="col-sm-2"> <div class="input-group"> <input type="text" class="form-cont ...

Using JQuery and Bootstrap, add or remove rows dynamically

For my project, I am creating tests (in English, physics, etc.) using JSTL, Bootstrap, and jQuery. I need a form to create a Test with questions and answers. However, I am facing an issue. When I try to delete a question, the answers that were added are no ...

"Internet Explorer: Unleashing the Magic of Card Fl

I'm encountering a problem that I can't seem to solve. Everything works perfectly in Chrome, FF, Safari, etc., but in Internet Explorer, I see the image on the front side instead of the text on the backside. Can anyone please assist me with this ...

Is there a way to invoke a function from a component that is neither a direct child nor parent component?

Module X let searchQuery = .... retrieveData(searchQuery); Module Y //implementing the use of Module X's parameter ...

Utilizing Angular directives to trigger functions within nested child directives

Seeking guidance on implementing a hierarchical structure in Angular, where a directive (<partition>) can trigger a method on a child directive's controller (<property-value>). Sample example provided: https://jsfiddle.net/95kjjxkh/1/ ...

jQuery does not provide the reference of a basic canvas element

I'm having trouble with a simple initialization function that is supposed to create a canvas element in the body and save its reference in a variable. No matter what I try, jQuery doesn't seem to want to return the reference. I attempted refere ...

Enhancing the appearance of list options in Autocomplete Material UI by utilizing the renderOption feature

I'm putting in a lot of effort to customize the option elements in the autocomplete list. My plan is to achieve this using the renderOptions prop, where I can create DOM elements and easily apply styles with sx or styled components. However, somethin ...

What is the best way to redirect to a specific page when logging out of a website?

To begin, let me outline the situation at hand. We have two distinct websites - website-A and website-B. Each of these websites is hosted on separate domains. A user has the ability to log in to website-B's homepage through the login page of webs ...

An easy way to showcase Wikipedia's JSON data using JQuery

I would like to showcase the information found in the "extract" section of this JSON data retrieved from Wikipedia: { "query": { "normalized": [ { "from": "india", "to": "India" } ...

Execute the command "prisma migrate dev" to update the existing database

I'm currently in the process of configuring Prisma migrate on a pre-populated MySQL database in my development environment, but I'm facing challenges getting it to function correctly. 1. After executing prisma db pull successfully to generate th ...

Iterating over each element within an array using the map method

I am facing an issue while trying to map values to a new array. The challenge lies in the fact that the property I am mapping can either be a number or an array. When it comes to arrays, I encounter a problem as my result ends up being an associative arra ...

JQuery Mobile applies X to all divs with the specified class

I am currently working on a JQuery mobile website with an image slider on 2 different pages. In order to activate the sliders, I am using the following JavaScript code: $(function () { $("#slider").excoloSlider(); }); where '#slider' refers ...

Using only THREE.Points, it is possible to dynamically calculate the camera position in three.js

My primary objective is to dynamically position the camera in such a way that my object remains visible. After researching, I came across this thread: How to Fit Camera to Object This article mentions the need for fov, height, and dist, variables which a ...