Looking for a more efficient method to code this dynamic jQuery pagination loader?

Currently, my website uses a pager that loads the page when you click on the page numbers. The code shows the closest 10 pages along with arrows to navigate to the first, previous, next, and last pages.

I am aiming to develop jQuery code that can update the content of the #pages div dynamically with the correct page numbers and remove the navigation arrows if the user is on the first or last page.

HTML

<div id="pages">
    <a href="1" class="first">&laquo;</a>
    <a href="1" class="previous">&lsaquo;</a>    
    <span class="current">2</span>  
    <a href="3">3</a>
    <a href="4">4</a>
    <a href="5">5</a>
    <a href="6">6</a>
    <a href="7">7</a>
    <a href="8">8</a>
    <a href="9">9</a>
    <a href="10">10</a>
    <a href="11">11</a>   
    <a href="3" class="next">&rsaquo;</a>
    <a href="128" class="last">&raquo;</a>
</div>

Sample jQuery for highest number click event

//change page numbers if highest number clicked
$(document).on("click", "#pages a", function(){
    if($(this).index() == 11){
        $("#pages :nth-child(3)").remove();
        $("#pages a:nth-child(11)").after('<a href="'+ (parseInt($(this).text()) + 1) + '" rel="nofollow" class="current">'+ (parseInt($(this).text()) + 1) + '</a>');
    }
});

Check out this jFiddle link for a live demonstration:

http://jsfiddle.net/84NaC/5/

In the jFiddle example, clicking the lower arrow or lowest number removes the lowest number and inserts a new higher number. The provided comments explain how this functionality works.

The Challenge

The current implementation has some bugs and does not meet my satisfaction in terms of functionality. I'm exploring better alternatives to achieve what I have envisioned. Is there a more reliable method to accomplish my goal?

Answer №1

After experimenting with your JSFiddle, I made adjustments to the HTML code:

<div id="content">Default</div>
<div id="pages">
    <a href="1" class="goto-first-page">&laquo;</a>
    <a href="#" class="goto-previous-page">&lsaquo;</a>
    <a href="1" class="goto-page">1</a>
    <a href="2" class="goto-page current-page">2</a>
    <a href="3" class="goto-page">3</a>
    <a href="4" class="goto-page">4</a>
    <a href="5" class="goto-page">5</a>
    <a href="6" class="goto-page">6</a>
    <a href="7" class="goto-page">7</a>
    <a href="8" class="goto-page">8</a>
    <a href="9" class="goto-page">9</a>
    <a href="10" class="goto-page">10</a>
    <a href="11" class="goto-page">11</a>
    <a href="#" class="goto-next-page">&rsaquo;</a>
    <a href="128" class="goto-last-page">&raquo;</a>
</div>

I also introduced some new functions:

function update_page_content(n)
{
    $('#content').html('Page ' + n + ' Content');
}

function update_page_range(lower_bound)
{
    var range = range_last_page - range_first_page;
    range_first_page = lower_bound;
    range_last_page = lower_bound + range;
    $('.goto-page').each(function(index) {
        $(this).attr('href', lower_bound + index).text(lower_bound + index);
    });

}

function goto_page(n) {
    // adjust current page
    var current = $('.goto-page[href="' + n + '"]');
    if (current.length == 0) {
        if (n <  range_first_page) {
            if (n >= first_page) {
                var lower_bound = Math.max(first_page, n - 5);
                update_page_range(lower_bound);
                current = $('.goto-page[href="' + n + '"]');
            }
        } else if (n > range_last_page) {
            if (n <= last_page) {
                var upper_bound = Math.min(last_page, n + 5);
                update_page_range(upper_bound - 10);
                current = $('.goto-page[href="' + n + '"]');
            }
        }
    }

    if (current.length > 0) {
        // set content
        update_page_content(n);

        $('.goto-page').removeClass('current-page');
        current.addClass('current-page');
    }
}

Lastly, I individually configured the click() events for each element:

$('.goto-previous-page').click(function () {
    var n = $('.current-page').attr('href');
    goto_page(+n - 1);
    return false;
});
$('.goto-next-page').click(function () {
    var n = $('.current-page').attr('href');
    goto_page(+n + 1);
    return false;
});
$('.goto-first-page, .goto-last-page, .goto-page').click(function () {
    var n = $(this).attr('href');
    goto_page(+n);
    return false;
});

You can view the updated version on JSFiddle

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

Tips on successfully transferring a JavaScript variable from PHP to JavaScript

I am struggling with how to manipulate a JavaScript variable in my HTML script and then pass it to a PHP file for incrementing by 1. However, I am unsure of how to return this modified variable back to the HTML file for display. Additionally, I am uncertai ...

html safeguarding user accounts

function Authenticate() { loggedIn = false; username = ""; password = ""; username = prompt("Please enter your username:", ""); username = username.toLowerCase(); password = prompt("Please enter your password:", ""); password = ...

When the button is clicked, two forms will be sent simultaneously and the PHP script will be

I have successfully set up my website with PayFast integration. Now, I need to run another PHP script when the user clicks on the place order button to save details in the database. Unfortunately, my code is quite long and I am not familiar with Ajax or Ja ...

Obtain data using a REST request from a webpage or web server

Is it possible to extract the last status value from a delivery courier's webpage by sending a tracking number request using PHP? I have found some helpful information, but I am unsure if it is possible to extract only specific values from the result ...

Identify the externally-sourced element of interest

I'm attempting to apply a ScrollReveal effect to an element loaded from a separate html file called "header.html". Unfortunately, the ScrollReveal animation is not working on this particular element, while other elements within my index.html are funct ...

Adjust the height value of each element to match the maximum height within a single line using only CSS

There are 3 divs styled with display:inline-block. I aim to adjust their height values so they match the highest one. The desired effect is demonstrated visually below. Is it doable using only CSS? ----- ----- ----- ----- ----- ---- ...

Troubleshooting issue: PHP script displaying an HTML table containing PHP code results in a syntax

I have a piece of code that I want to use to output an HTML table with PHP embedded in it. EDIT: Apologies, I realized that I didn't provide the entire code. Maybe this will make a difference. <!doctype html> <html> <head> & ...

Unable to access the ajaxComplete function while using .ajaxComplete with a datepicker change function

I'm facing an issue with my datepicker where I need to trigger a query as soon as a date is selected. I've been trying to implement the functionality using .ajaxComplete but seem to be unable to access it properly. Any suggestions on how to resol ...

Continuous horizontal columns

Is there a way to create horizontal columns with inline-blocks, like the method described here, without having vertical gaps between items on the second line due to different heights? I want to eliminate the vertical gaps between the tiles using only CSS. ...

Incorporate a dialogue box utilizing jQuery with dynamically created HTML elements using jQuery

Is it possible to add a jQuery dialog using a string containing HTML code stored in a variable? I have tried out some code, and you can view it here. $("#remove-post").dialog({ autoOpen: false, height: 'auto', width: 'auto&a ...

Is there a way to identify the ID of a button using Javascript specifically in Internet Explorer and Safari browsers?

Within my code, there lies a directive that contains the attribute on-blur = blurFunc($event). Imagine this scenario: I interact with a button bearing the id "myButton" located outside of the directive. How can I determine which specific button was clicke ...

Clear information upon clicking to switch to a new controller

I have a scenario where one div contains another div. The contained div has its own controller that controls its visibility based on a variable changed by clicking an icon button in the container. The structure is as follows: <div ng-controller="BarCo ...

Enable checkboxes to be pre-selected upon page loading automatically

Although I've found a lot of code snippets for a "select all" option, what I really need is more direct. I want the WpForms checkboxes to be pre-checked by default when the page loads, instead of requiring users to press a button. My goal is to have a ...

Enhancing the Appearance of WooCommerce Product Descriptions

Having some trouble with my website . There are two descriptions on the "Product" page - one above the tabs and one inside the tabs. Trying to change the text color in the tab section to black, but when I adjust the body text color it affects both areas. I ...

Concealing divs without values in ASP.NET MVC

I am working on an AJAX call to fetch data from the back-end and populate divs with it. Below is my code for the AJAX call: $(document).ready(function() { question_block(); }); function question_block() { $.ajax({ url: '@Url.Action(" ...

Submit form results in success/error message constantly vanishing

My application, (editsessionadmin.php), allows users to input their assessment's name, date, and time. Upon submission, a confirmation message is displayed and, upon user acceptance, the system uses ajax to navigate to updatedatetime.php. Here, it upd ...

I am having trouble with $(this) in my jQuery click event handler

When I click my function, I want to change a parent element that contains this function. However, $(this) is not working. What could be the issue? function accountConfirm(message, title, yes_label, no_label, callback) { console.log($(this)); $(&qu ...

What is the standard way elements are displayed within a box that is positioned absolutely?

My current setup involves setting <body> to be absolutely positioned in order to fill the entire viewport without needing to specify a height: body { width: 100%; margin: 0; padding: 0; position: absolute; top:0; right:0; bottom: ...

Using jQuery/ajax to send a delete request in Node.js

On the server side, I have implemented the following code: router.delete('/categories/delete/:id', function(req,res){ var id = req.params.id; Category.remove({_id: id},function(err){ if(err){ ...

Implement a mouseenter event to all input elements that have specific names stored in an array, utilizing jQuery

I'm struggling to figure out how to apply my function to all input elements with a name that is included in my array. This is what I've attempted so far: var names = ["name1", "name2"]; $(document).ready(function(){ $('input[name=names[ ...