JavaScript || How To Make Change – Display The Total Sales Amount In Dollars & Cents Using Modulus

The following is a module with functions which demonstrates the use of the modulus (%) operator to make change.

So for example, given the value of 2.34, this function would return the result of 2 dollars, 1 quarters, 1 nickels, and 4 pennies.

1. Make Change

The example below demonstrates how to make change.

``` 1. Make Change JavaScript // Make change <script> (() => { let values = [ 19.87, 11.93, 187.91, 3, 20.19, 1991 ]; values.forEach(value => { // Make change let change = Utils.makeChange(value); console.log(`\n\$\${value} is made up of: `); for (let amount of change) { console.log(`\t\${amount.denomination.description}: x\${amount.quantity}`); } }); })(); </script> // expected output: /* \$19.87 is made up of: Ten-Dollar Bill: x1 Five-Dollar Bill: x1 One-Dollar Bill: x4 Quarter: x3 Dime: x1 Penny: x2 \$11.93 is made up of: Ten-Dollar Bill: x1 One-Dollar Bill: x1 Quarter: x3 Dime: x1 Nickel: x1 Penny: x3 \$187.91 is made up of: Hundred-Dollar Bill: x1 Fifty-Dollar Bill: x1 Twenty-Dollar Bill: x1 Ten-Dollar Bill: x1 Five-Dollar Bill: x1 One-Dollar Bill: x2 Quarter: x3 Dime: x1 Nickel: x1 Penny: x1 \$3 is made up of: One-Dollar Bill: x3 \$20.19 is made up of: Twenty-Dollar Bill: x1 Dime: x1 Nickel: x1 Penny: x4 \$1991 is made up of: Hundred-Dollar Bill: x19 Fifty-Dollar Bill: x1 Twenty-Dollar Bill: x2 One-Dollar Bill: x1 */ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 // Make change <script>(() => {    let values = [        19.87,        11.93,        187.91,        3,        20.19,        1991    ];    values.forEach(value => {        // Make change        let change = Utils.makeChange(value);                   console.log(`\n\$\${value} is made up of: `);        for (let amount of change) {            console.log(`\t\${amount.denomination.description}: x\${amount.quantity}`);        }        });    })();</script> // expected output:/*    \$19.87 is made up of:         Ten-Dollar Bill: x1          Five-Dollar Bill: x1         One-Dollar Bill: x4         Quarter: x3         Dime: x1         Penny: x2      \$11.93 is made up of:          Ten-Dollar Bill: x1         One-Dollar Bill: x1         Quarter: x3          Dime: x1         Nickel: x1          Penny: x3       \$187.91 is made up of:         Hundred-Dollar Bill: x1         Fifty-Dollar Bill: x1         Twenty-Dollar Bill: x1          Ten-Dollar Bill: x1         Five-Dollar Bill: x1         One-Dollar Bill: x2         Quarter: x3         Dime: x1          Nickel: x1         Penny: x1     \$3 is made up of:          One-Dollar Bill: x3       \$20.19 is made up of:          Twenty-Dollar Bill: x1          Dime: x1          Nickel: x1          Penny: x4       \$1991 is made up of:          Hundred-Dollar Bill: x19          Fifty-Dollar Bill: x1         Twenty-Dollar Bill: x2          One-Dollar Bill: x1*/ ```

2. Utils Namespace

The following is the Utils.js Namespace. Include this in your project to start using!

``` Utils.js Namespace JavaScript // ============================================================================ // Author: Kenneth Perkins // Date: Aug 29, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.js // Description: Javascript that handles general utility functions // ============================================================================ /** * NAMESPACE: Utils * USE: Handles general utility functions. */ var Utils = Utils || {}; (function(namespace) { 'use strict'; // Property to hold public variables and functions let exposed = namespace; /** * FUNCTION: makeChange * USE: Makes change out of a given dollar amount. * @param amount: The dollar amount of the change to make. * @return: An array of Denomination info that makes up the given amount. */ exposed.makeChange = (amount) => { let denominations = exposed.Denomination.get(); let remainingCents = exposed.Denomination.convert(amount); let change = []; for (const denomination of denominations) { let quantity = Math.floor(remainingCents / denomination.cents()); remainingCents %= denomination.cents(); if (quantity > 0) { change.push({ quantity: quantity, denomination: denomination, }); } } return change } exposed.Denomination = class { constructor(dollars, description) { this.dollars = dollars; this.description = description; } cents() { return exposed.Denomination.convert(this.dollars); } static convert(dollars) { return dollars * 100; } static get() { let denominations = [ new exposed.Denomination(100, 'Hundred-Dollar Bill'), new exposed.Denomination(50, 'Fifty-Dollar Bill'), new exposed.Denomination(20, 'Twenty-Dollar Bill'), new exposed.Denomination(10, 'Ten-Dollar Bill'), new exposed.Denomination(5, 'Five-Dollar Bill'), new exposed.Denomination(1, 'One-Dollar Bill'), new exposed.Denomination(.25, 'Quarter'), new exposed.Denomination(.10, 'Dime'), new exposed.Denomination(.05, 'Nickel'), new exposed.Denomination(.01, 'Penny'), ]; return denominations; } } (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 // ============================================================================//    Author: Kenneth Perkins//    Date:   Aug 29, 2020//    Taken From: http://programmingnotes.org///    File:  Utils.js//    Description: Javascript that handles general utility functions    // ============================================================================/*** NAMESPACE: Utils* USE: Handles general utility functions.*/var Utils = Utils || {};(function(namespace) {    'use strict';       // Property to hold public variables and functions    let exposed = namespace;        /**    * FUNCTION: makeChange    * USE: Makes change out of a given dollar amount.    * @param amount: The dollar amount of the change to make.    * @return: An array of Denomination info that makes up the given amount.    */    exposed.makeChange = (amount) => {        let denominations = exposed.Denomination.get();        let remainingCents = exposed.Denomination.convert(amount);        let change = [];                for (const denomination of denominations) {            let quantity = Math.floor(remainingCents / denomination.cents());            remainingCents %= denomination.cents();            if (quantity > 0) {                change.push({                    quantity: quantity,                    denomination: denomination,                });            }                    }        return change    }         exposed.Denomination = class {        constructor(dollars, description) {            this.dollars = dollars;            this.description = description;        }        cents() {            return exposed.Denomination.convert(this.dollars);        }        static convert(dollars) {            return dollars * 100;        }        static get() {            let denominations = [                new exposed.Denomination(100, 'Hundred-Dollar Bill'),                new exposed.Denomination(50, 'Fifty-Dollar Bill'),                new exposed.Denomination(20, 'Twenty-Dollar Bill'),                new exposed.Denomination(10, 'Ten-Dollar Bill'),                new exposed.Denomination(5, 'Five-Dollar Bill'),                new exposed.Denomination(1, 'One-Dollar Bill'),                new exposed.Denomination(.25, 'Quarter'),                new exposed.Denomination(.10, 'Dime'),                new exposed.Denomination(.05, 'Nickel'),                new exposed.Denomination(.01, 'Penny'),            ];            return denominations;        }    }           (function (factory) {        if (typeof define === 'function' && define.amd) {            define([], factory);        } else if (typeof exports === 'object') {            module.exports = factory();        }    }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

JavaScript || Swap Two HTML Element Locations In Dom Tree Using Vanilla JavaScript

The following is a module with functions that demonstrates a simple way how to swap two HTML element locations in the Dom tree using JavaScript.

This method retains any existing event listeners.

1. Swap Element Locations

The example below demonstrates how to swap two HTML element locations.

``` 1. Swap Element Locations XHTML <!-- // Swap Element Locations. --> <div class="container"> <p>some irrelevant text 1</p> <p>some irrelevant text 2</p> <p class="first">I'm first</p> <div> <p class="second">I'm second</p> <p>some irrelevant text outside 1</p> <p>some irrelevant text outside 2</p> </div> </div> <script> (() => { let first = document.querySelector('.first'); let second = document.querySelector('.second'); let container = document.querySelector('.container'); console.log('=== Before Swap ==='); console.log(container.innerHTML); // Swap the two locations Utils.swapLocations(first, second); console.log('=== After Swap ==='); console.log(container.innerHTML); })(); </script> <!-- // expected output: /* === Before Swap === <p>some irrelevant text 1</p> <p>some irrelevant text 2</p> <p class="first">I'm first</p> <div> <p class="second">I'm second</p> <p>some irrelevant text outside 1</p> <p>some irrelevant text outside 2</p> </div> === After Swap === <p>some irrelevant text 1</p> <p>some irrelevant text 2</p> <p class="second">I'm second</p> <div> <p class="first">I'm first</p> <p>some irrelevant text outside 1</p> <p>some irrelevant text outside 2</p> </div> */ --> 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 <!-- // Swap Element Locations. --> <div class="container">    <p>some irrelevant text 1</p>    <p>some irrelevant text 2</p>    <p class="first">I'm first</p>    <div>        <p class="second">I'm second</p>        <p>some irrelevant text outside 1</p>        <p>some irrelevant text outside 2</p>    </div></div>     <script>(() => {     let first = document.querySelector('.first');    let second = document.querySelector('.second');        let container = document.querySelector('.container');     console.log('=== Before Swap ===');    console.log(container.innerHTML);        // Swap the two locations    Utils.swapLocations(first, second);        console.log('=== After Swap ===');    console.log(container.innerHTML);  })();</script> <!--// expected output:/*    === Before Swap ===           <p>some irrelevant text 1</p>        <p>some irrelevant text 2</p>        <p class="first">I'm first</p>        <div>            <p class="second">I'm second</p>            <p>some irrelevant text outside 1</p>            <p>some irrelevant text outside 2</p>        </div>      === After Swap ===          <p>some irrelevant text 1</p>        <p>some irrelevant text 2</p>        <p class="second">I'm second</p>        <div>            <p class="first">I'm first</p>            <p>some irrelevant text outside 1</p>            <p>some irrelevant text outside 2</p>        </div>*/--> ```

2. Utils Namespace

The following is the Utils.js Namespace. Include this in your project to start using!

``` Utils.js Namespace JavaScript // ============================================================================ // Author: Kenneth Perkins // Date: Aug 28, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.js // Description: Javascript that handles general utility functions // ============================================================================ /** * NAMESPACE: Utils * USE: Handles general utility functions. */ var Utils = Utils || {}; (function(namespace) { 'use strict'; // Property to hold public variables and functions let exposed = namespace; /** * FUNCTION: swapLocations * USE: Swaps two Javascript element locations in the DOM tree. * @param elementX: The first Javascript element to swap. * @param elementY: The second Javascript element to swap. * @return: N/A. */ exposed.swapLocations = (elementX, elementY) => { let parentY = elementY.parentNode; let nextY = elementY.nextSibling; if (nextY === elementX) { parentY.insertBefore(elementX, elementY); } else { elementX.parentNode.insertBefore(elementY, elementX); if (nextY) { parentY.insertBefore(elementX, nextY); } else { parentY.appendChild(elementX); } } } (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 // ============================================================================//    Author: Kenneth Perkins//    Date:   Aug 28, 2020//    Taken From: http://programmingnotes.org///    File:  Utils.js//    Description: Javascript that handles general utility functions    // ============================================================================/*** NAMESPACE: Utils* USE: Handles general utility functions.*/var Utils = Utils || {};(function(namespace) {    'use strict';       // Property to hold public variables and functions    let exposed = namespace;        /**    * FUNCTION: swapLocations    * USE: Swaps two Javascript element locations in the DOM tree.    * @param elementX: The first Javascript element to swap.    * @param elementY: The second Javascript element to swap.    * @return: N/A.    */    exposed.swapLocations = (elementX, elementY) => {        let parentY = elementY.parentNode;        let nextY = elementY.nextSibling;        if (nextY === elementX) {            parentY.insertBefore(elementX, elementY);        } else {            elementX.parentNode.insertBefore(elementY, elementX);            if (nextY) {                parentY.insertBefore(elementX, nextY);            } else {                parentY.appendChild(elementX);            }        }    }          (function (factory) {        if (typeof define === 'function' && define.amd) {            define([], factory);        } else if (typeof exports === 'object') {            module.exports = factory();        }    }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

JavaScript || Check If An Element Comes Before Or After Another Element In Dom Tree Using Vanilla JavaScript

The following is a module with functions that demonstrates a simple way how to check if an element comes before or after another element in the Dom tree using JavaScript.

1. Check If Before / After

The example below demonstrates how to check if an element is before or after another element.

``` 1. Check Before / After XHTML <!-- // Check before / after. --> <div class="container"> <p>some irrelevant text 1</p> <p>some irrelevant text 2</p> <p class="first">I'm first</p> <div> <p class="second">I'm second</p> <p>some irrelevant text outside 1</p> <p>some irrelevant text outside 2</p> </div> </div> <script> (() => { let first = document.querySelector('.first'); let second = document.querySelector('.second'); console.log(Utils.isBefore(first, second)); console.log(Utils.isAfter(first, second)); })(); </script> <!-- // expected output: /* true false */ --> 123456789101112131415161718192021222324252627282930 <!-- // Check before / after. --> <div class="container">    <p>some irrelevant text 1</p>    <p>some irrelevant text 2</p>    <p class="first">I'm first</p>    <div>        <p class="second">I'm second</p>        <p>some irrelevant text outside 1</p>        <p>some irrelevant text outside 2</p>    </div></div>     <script>(() => {     let first = document.querySelector('.first');    let second = document.querySelector('.second');        console.log(Utils.isBefore(first, second));    console.log(Utils.isAfter(first, second));   })();</script> <!--// expected output:/*    true    false*/--> ```

2. Refined Search

The example below demonstrates how to check if an element is before or after another element by refining the search by a specific container.

``` 2. Refined Search XHTML <!-- // Refined Search. --> <div class="container"> <p>some irrelevant text 1</p> <p>some irrelevant text 2</p> <p class="first">I'm first</p> <div> <p class="second">I'm second</p> <p>some irrelevant text outside 1</p> <p>some irrelevant text outside 2</p> </div> </div> <script> (() => { let first = document.querySelector('.first'); let second = document.querySelector('.second'); let container = document.querySelector('.container'); console.log(Utils.isBefore(first, second, container)); console.log(Utils.isAfter(first, second, container)); })(); </script> <!-- // expected output: /* true false */ --> 12345678910111213141516171819202122232425262728293031 <!-- // Refined Search. --> <div class="container">    <p>some irrelevant text 1</p>    <p>some irrelevant text 2</p>    <p class="first">I'm first</p>    <div>        <p class="second">I'm second</p>        <p>some irrelevant text outside 1</p>        <p>some irrelevant text outside 2</p>    </div></div>     <script>(() => {     let first = document.querySelector('.first');    let second = document.querySelector('.second');    let container = document.querySelector('.container');       console.log(Utils.isBefore(first, second, container));    console.log(Utils.isAfter(first, second, container)); })();</script> <!-- // expected output:/*    true    false*/--> ```

3. Utils Namespace

The following is the Utils.js Namespace. Include this in your project to start using!

``` Utils.js Namespace JavaScript // ============================================================================ // Author: Kenneth Perkins // Date: Aug 28, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.js // Description: Javascript that handles general utility functions // ============================================================================ /** * NAMESPACE: Utils * USE: Handles general utility functions. */ var Utils = Utils || {}; (function(namespace) { 'use strict'; // Property to hold public variables and functions let exposed = namespace; /** * FUNCTION: isBefore * USE: Determines if 'elementX' comes before 'elementY' in the DOM tree. * @param elementX: The first Javascript element to compare. * @param elementY: The second Javascript element to compare. * @param container: Optional. The container to limit the search. * @return: True if 'elementX' comes before 'elementY', false otherwise. */ exposed.isBefore = (elementX, elementY, container = null) => { container = container || (elementX.parentNode === elementY.parentNode ? elementX.parentNode : null) || document; let items = container.querySelectorAll('*'); let result = false; for (const item of items) { if (item === elementX) { result = true; break; } else if (item === elementY) { result = false; break; } } return result; } /** * FUNCTION: isAfter * USE: Determines if 'elementX' comes after 'elementY' in the DOM tree. * @param elementX: The first Javascript element to compare. * @param elementY: The second Javascript element to compare. * @param container: Optional. The container to limit the search. * @return: True if 'elementX' comes after 'elementY', false otherwise. */ exposed.isAfter = (elementX, elementY, container = null) => { return !exposed.isBefore(elementX, elementY, container); } (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 // ============================================================================//    Author: Kenneth Perkins//    Date:   Aug 28, 2020//    Taken From: http://programmingnotes.org///    File:  Utils.js//    Description: Javascript that handles general utility functions    // ============================================================================/*** NAMESPACE: Utils* USE: Handles general utility functions.*/var Utils = Utils || {};(function(namespace) {    'use strict';       // Property to hold public variables and functions    let exposed = namespace;        /**    * FUNCTION: isBefore    * USE: Determines if 'elementX' comes before 'elementY' in the DOM tree.    * @param elementX: The first Javascript element to compare.    * @param elementY: The second Javascript element to compare.    * @param container: Optional. The container to limit the search.        * @return: True if 'elementX' comes before 'elementY', false otherwise.    */        exposed.isBefore = (elementX, elementY, container = null) => {        container = container || (elementX.parentNode === elementY.parentNode ? elementX.parentNode : null) || document;                let items = container.querySelectorAll('*');        let result = false;        for (const item of items) {            if (item === elementX) {                result = true;                break;            } else if (item === elementY) {                result = false;                break;            }                    }        return result;    }        /**    * FUNCTION: isAfter    * USE: Determines if 'elementX' comes after 'elementY' in the DOM tree.    * @param elementX: The first Javascript element to compare.    * @param elementY: The second Javascript element to compare.    * @param container: Optional. The container to limit the search.        * @return: True if 'elementX' comes after 'elementY', false otherwise.    */          exposed.isAfter = (elementX, elementY, container = null) => {        return !exposed.isBefore(elementX, elementY, container);    }         (function (factory) {        if (typeof define === 'function' && define.amd) {            define([], factory);        } else if (typeof exports === 'object') {            module.exports = factory();        }    }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

JavaScript || How To Get The Next & Previous Multiple Of A Number Using Vanilla JavaScript

The following is a module with functions that demonstrates how to get the next and previous multiple of a number using Vanilla JavaScript.

If a number is already a multiple, there is a parameter that allows you to specify if it should be rounded or not.

1. Get Next Multiple – Include Existing

The example below demonstrates how to round up a number to the next multiple. In this example, if a number is already a multiple, it will not be rounded up to the next multiple.

``` 1. Get Next - Include Existing JavaScript // Get next multiple - include if already a multiple. <script> (() => { let multiple = 5; for (let index = 1; index <= 10; ++index) { console.log(index, '=>', Utils.getNextMultiple(index, multiple)); } })(); </script> // expected output: /* 1 => 5 2 => 5 3 => 5 4 => 5 5 => 5 6 => 10 7 => 10 8 => 10 9 => 10 10 => 10 */ 123456789101112131415161718192021222324 // Get next multiple - include if already a multiple.  <script>(() => {     let multiple = 5;    for (let index = 1; index <= 10; ++index) {      console.log(index, '=>', Utils.getNextMultiple(index, multiple));    }   })();</script> // expected output:/*    1 => 5     2 => 5     3 => 5     4 => 5     5 => 5     6 => 10     7 => 10     8 => 10     9 => 10     10 => 10*/ ```

2. Get Next Multiple – Skip Existing

The example below demonstrates how to round up a number to the next multiple. In this example, if a number is already a multiple, it will be rounded up to the next multiple.

``` 2. Get Next - Skip Existing JavaScript // Get next multiple - skip if already a multiple. <script> (() => { let multiple = 5; // Set 3rd parameter to true to skip numbers that are already a // multiple to the next value for (let index = 1; index <= 10; ++index) { console.log(index, '=>', Utils.getNextMultiple(index, multiple, true)); } })(); </script> // expected output: /* 1 => 5 2 => 5 3 => 5 4 => 5 5 => 10 6 => 10 7 => 10 8 => 10 9 => 10 10 => 15 */ 123456789101112131415161718192021222324252627 // Get next multiple - skip if already a multiple.  <script>(() => {     let multiple = 5;     // Set 3rd parameter to true to skip numbers that are already a     // multiple to the next value    for (let index = 1; index <= 10; ++index) {      console.log(index, '=>', Utils.getNextMultiple(index, multiple, true));    }    })();</script> // expected output:/*    1 => 5     2 => 5     3 => 5      4 => 5     5 => 10      6 => 10      7 => 10      8 => 10      9 => 10      10 => 15*/ ```

3. Get Previous Multiple – Include Existing

The example below demonstrates how to round down a number to the previous multiple. In this example, if a number is already a multiple, it will not be rounded down to the previous multiple.

``` 3. Get Previous - Include Existing JavaScript // Get previous multiple - include if already a multiple. <script> (() => { let multiple = 5; for (let index = 10; index >= 1; --index) { console.log(index, '=>', Utils.getPreviousMultiple(index, multiple)); } })(); </script> // expected output: /* 10 => 10 9 => 5 8 => 5 7 => 5 6 => 5 5 => 5 4 => 0 3 => 0 2 => 0 1 => 0 */ 123456789101112131415161718192021222324 // Get previous multiple - include if already a multiple.  <script>(() => {     let multiple = 5;    for (let index = 10; index >= 1; --index) {      console.log(index, '=>', Utils.getPreviousMultiple(index, multiple));    }  })();</script> // expected output:/*    10 => 10     9 => 5     8 => 5     7 => 5     6 => 5     5 => 5     4 => 0     3 => 0     2 => 0     1 => 0*/ ```

4. Get Previous Multiple – Skip Existing

The example below demonstrates how to round down a number to the previous multiple. In this example, if a number is already a multiple, it will be rounded down to the previous multiple.

``` 4. Get Previous - Skip Existing JavaScript // Get previous multiple - skip if already a multiple. <script> (() => { let multiple = 5; // Set 3rd parameter to true to skip numbers that are already a // multiple to the previous value for (let index = 10; index >= 1; --index) { console.log(index, '=>', Utils.getPreviousMultiple(index, multiple, true)); } })(); </script> // expected output: /* 10 => 5 9 => 5 8 => 5 7 => 5 6 => 5 5 => 0 4 => 0 3 => 0 2 => 0 1 => 0 */ 123456789101112131415161718192021222324252627 // Get previous multiple - skip if already a multiple.  <script>(() => {     let multiple = 5;     // Set 3rd parameter to true to skip numbers that are already a     // multiple to the previous value    for (let index = 10; index >= 1; --index) {      console.log(index, '=>', Utils.getPreviousMultiple(index, multiple, true));    } })();</script> // expected output:/*    10 => 5     9 => 5     8 => 5      7 => 5     6 => 5     5 => 0     4 => 0     3 => 0     2 => 0     1 => 0*/ ```

5. Utils Namespace

The following is the Utils.js Namespace. Include this in your project to start using!

``` Utils.js Namespace JavaScript // ============================================================================ // Author: Kenneth Perkins // Date: Aug 8, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.js // Description: Javascript that handles general utility functions // ============================================================================ /** * NAMESPACE: Utils * USE: Handles general utility functions. */ var Utils = Utils || {}; (function(namespace) { 'use strict'; // Property to hold public variables and functions let exposed = namespace; /** * FUNCTION: getNextMultiple * USE: Returns the next multiple of a given number. Unless specified, * it will not round up numbers which are already multiples * @param number: The given number to find the next multiple * @param multiple: The multiple number * @param skipAlreadyMultiple: Boolean that specifies if input numbers which * are already multiples should be skipped to the next multiple or not * @return: The next multiple of the given number */ exposed.getNextMultiple = (number, multiple, skipAlreadyMultiple = false) => { let result = 0; if (multiple !== 0) { let remainder = (Math.abs(number) % multiple); if (!skipAlreadyMultiple && remainder === 0) { result = number; } else if (number < 0 && remainder !== 0) { result = -(Math.abs(number) - remainder); } else { result = number + (multiple - remainder); } } return result; } /** * FUNCTION: getPreviousMultiple * USE: Returns the previous multiple of a given number. Unless specified, * it will not round down numbers which are already multiples * @param number: The given number to find the previous multiple * @param multiple: The multiple number * @param skipAlreadyMultiple: Boolean that specifies if input numbers which * are already multiples should be skipped to the previous multiple or not. * @return: The previous multiple of the given number */ exposed.getPreviousMultiple = (number, multiple, skipAlreadyMultiple = false) => { return exposed.getNextMultiple(number, multiple, !skipAlreadyMultiple) - multiple; } (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 // ============================================================================//    Author: Kenneth Perkins//    Date:   Aug 8, 2020//    Taken From: http://programmingnotes.org///    File:  Utils.js//    Description: Javascript that handles general utility functions    // ============================================================================/*** NAMESPACE: Utils* USE: Handles general utility functions.*/var Utils = Utils || {};(function(namespace) {    'use strict';       // Property to hold public variables and functions    let exposed = namespace;        /**    * FUNCTION: getNextMultiple    * USE: Returns the next multiple of a given number. Unless specified,    *   it will not round up numbers which are already multiples    * @param number: The given number to find the next multiple    * @param multiple: The multiple number    * @param skipAlreadyMultiple: Boolean that specifies if input numbers which    *   are already multiples should be skipped to the next multiple or not    * @return: The next multiple of the given number    */    exposed.getNextMultiple = (number, multiple, skipAlreadyMultiple = false) => {        let result = 0;        if (multiple !== 0) {            let remainder = (Math.abs(number) % multiple);            if (!skipAlreadyMultiple && remainder === 0) {                result = number;            } else if (number < 0 && remainder !== 0) {                result = -(Math.abs(number) - remainder);            } else {                result = number + (multiple - remainder);            }        }        return result;    }     /**    * FUNCTION: getPreviousMultiple    * USE: Returns the previous multiple of a given number. Unless specified,    *   it will not round down numbers which are already multiples    * @param number: The given number to find the previous multiple    * @param multiple: The multiple number    * @param skipAlreadyMultiple: Boolean that specifies if input numbers which    *   are already multiples should be skipped to the previous multiple or not.    * @return: The previous multiple of the given number    */    exposed.getPreviousMultiple = (number, multiple, skipAlreadyMultiple = false) => {        return exposed.getNextMultiple(number, multiple, !skipAlreadyMultiple) - multiple;    }     (function (factory) {        if (typeof define === 'function' && define.amd) {            define([], factory);        } else if (typeof exports === 'object') {            module.exports = factory();        }    }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

JavaScript || How To Scroll To An Element & Add Automatic Anchor Scroll Using Vanilla JavaScript

The following is a module with functions that demonstrates how to scroll to a specific HTML element, as well as setting anchors to have a smooth scroll effect on button click.

1. Scroll To Element

The example below demonstrates how to scroll to a specific element.

``` 1. Scroll To Element JavaScript // Scroll to a specific element <script> (() => { Utils.scrollToElement("#examples"); })(); </script> 1234567 // Scroll to a specific element <script>(() => { Utils.scrollToElement("#examples");})();</script> ```

The ‘Utils.scrollToElement‘ function accepts either a JavaScript element or a string selector of the element to scroll to.

2. Add Scroll To Anchor Target

The example below demonstrates how to automatically add a scrolling effect to an anchor target.

``` 2. Scroll To Anchor Target JavaScript // Scroll to anchor target <script> (() => { Utils.registerAnchorScroll(); })(); </script> 1234567 // Scroll to anchor target <script>(() => { Utils.registerAnchorScroll();})();</script> ```

The ‘Utils.registerAnchorScroll‘ function gets all the anchor links on a page and registers smooth scrolling on button click using ‘Utils.scrollToElement‘.

3. Utils Namespace

The following is the Utils.js Namespace. Include this in your project to start using!

``` Utils.js Namespace JavaScript // ============================================================================ // Author: Kenneth Perkins // Date: Aug 7, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.js // Description: Javascript that handles general utility functions // ============================================================================ /** * NAMESPACE: Utils * USE: Handles general utility functions. */ var Utils = Utils || {}; (function(namespace) { 'use strict'; // Property to hold public variables and functions let exposed = namespace; /** * FUNCTION: registerAnchorScroll * USE: Gets all the anchor links on a page and registers smooth scrolling * on button click. * @return: N/A. */ exposed.registerAnchorScroll = () => { let anchorLinks = document.querySelectorAll('a[href^="#"]'); for (let link of anchorLinks) { link.addEventListener('click', (e) => { let hashval = link.getAttribute('href'); let target = document.querySelector(hashval) || document.querySelector(`[name='\${hashval.slice(1)}']`); if (target) { exposed.scrollToElement(target); history.pushState(null, null, hashval); e.preventDefault(); } }); } } /** * FUNCTION: scrollToElement * USE: Scrolls the page to the given element. * @param target: A JavaScript element or a string selector of the * element to scroll to. * @param behavior: The scroll behavior. Defaut is 'smooth' * @return: N/A. */ exposed.scrollToElement = (target, behavior = 'smooth') => { if (typeof target === 'string') { target = document.querySelector(target); } target.scrollIntoView({ behavior: behavior, block: 'start' }); } (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 // ============================================================================//    Author: Kenneth Perkins//    Date:   Aug 7, 2020//    Taken From: http://programmingnotes.org///    File:  Utils.js//    Description: Javascript that handles general utility functions    // ============================================================================/*** NAMESPACE: Utils* USE: Handles general utility functions.*/var Utils = Utils || {};(function(namespace) {    'use strict';        // Property to hold public variables and functions    let exposed = namespace;        /**    * FUNCTION: registerAnchorScroll    * USE: Gets all the anchor links on a page and registers smooth scrolling    *    on button click.     * @return: N/A.    */         exposed.registerAnchorScroll = () => {        let anchorLinks = document.querySelectorAll('a[href^="#"]');        for (let link of anchorLinks) {            link.addEventListener('click', (e) => {                let hashval = link.getAttribute('href');                 let target = document.querySelector(hashval)                     || document.querySelector(`[name='\${hashval.slice(1)}']`);                if (target) {                    exposed.scrollToElement(target);                    history.pushState(null, null, hashval);                     e.preventDefault();                }            });        }    }     /**    * FUNCTION: scrollToElement    * USE: Scrolls the page to the given element.    * @param target: A JavaScript element or a string selector of the      *   element to scroll to.        * @param behavior: The scroll behavior. Defaut is 'smooth'     * @return: N/A.    */     exposed.scrollToElement = (target, behavior = 'smooth') => {        if (typeof target === 'string') {            target = document.querySelector(target);        }        target.scrollIntoView({            behavior: behavior,            block: 'start'        });    }         (function (factory) {        if (typeof define === 'function' && define.amd) {            define([], factory);        } else if (typeof exports === 'object') {            module.exports = factory();        }    }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ ```

4. More Examples

Below are more examples demonstrating the use of ‘Utils.js‘. Don’t forget to include the module when running the examples!

``` More Examles XHTML <!-- // ============================================================================ // Author: Kenneth Perkins // Date: Aug 7, 2020 // Taken From: http://programmingnotes.org/ // File: scrollDemo.html // Description: Demonstrates the use of Utils.js // ============================================================================ --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>My Programming Notes Utils.js Demo</title> <style> .space {margin-top: 1000px;} </style> <!-- // Include module --> <script type="text/javascript" src="./Utils.js"></script> </head> <body> <blockquote><code> <a href="#basicUsage">1. Basic Usage</a> <a href="#examples">2. Examples</a> </code></blockquote> <div class="space"></div> <h3 id="basicUsage"> 1. Basic Usage </h3> <div class="space"></div> <h3 id="examples"> 2. Examples </h3> <div class="space"></div> <script> document.addEventListener("DOMContentLoaded", function(eventLoaded) { Utils.registerAnchorScroll(); //Utils.scrollToElement("#examples"); }); </script> </body> </html> <!-- http://programmingnotes.org/ --> 123456789101112131415161718192021222324252627282930313233343536373839404142434445 <!-- // ============================================================================//    Author: Kenneth Perkins//    Date:   Aug 7, 2020//    Taken From: http://programmingnotes.org///    File:  scrollDemo.html//    Description: Demonstrates the use of Utils.js// ============================================================================ --><!DOCTYPE html><html><head><meta charset="utf-8"/><title>My Programming Notes Utils.js Demo</title><style>.space {margin-top: 1000px;}</style> <!-- // Include module --> <script type="text/javascript" src="./Utils.js"></script> </head><body> <blockquote><code><a href="#basicUsage">1. Basic Usage</a><a href="#examples">2. Examples</a></code></blockquote> <div class="space"></div><h3 id="basicUsage"> 1. Basic Usage </h3> <div class="space"></div><h3 id="examples"> 2. Examples </h3> <div class="space"></div> <script>document.addEventListener("DOMContentLoaded", function(eventLoaded) {    Utils.registerAnchorScroll();    //Utils.scrollToElement("#examples");});</script></body></html> <!-- http://programmingnotes.org/ --> ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

JavaScript/CSS/HTML || TablePagination.js – Simple Add Pagination To Any Table Using Vanilla JavaScript

The following is a module which allows for simple yet fully customizable table pagination in vanilla JavaScript.

With multiple options, as well as multiple callback functions to modify the pagination buttons and information text, almost all the ways you can think of pagination is supported by this module. It’s look and feel can also be adjusted via CSS.

Contents

```1. Basic Usage 2. Available Options 3. Only Show Page Numbers 4. Mini - Only Show Arrow Buttons 5. Show All Pages 6. Only Show Go Input 7. Format Navigation Text 8. Button Click Event 9. Navigation Position 10. Specify Initial Page 11. Navigation Binding Area 12. Remove Pagination 13. TablePagination.js & CSS Source 14. More Examples ```

1. Basic Usage

Syntax is very straightforward. The following demonstrates adding pagination to a table.

Calling ‘TablePagination.page‘ with no options will add pagination with all of the default options applied to it. It accepts one or more HTMLTableElement.

``` 1. Add Pagination JavaScript // Add table pagination. <script> (() => { // Adds table pagination to the table elements with the default options TablePagination.page(document.querySelectorAll('table')); })(); </script> 12345678 // Add table pagination.  <script>(() => {    // Adds table pagination to the table elements with the default options    TablePagination.page(document.querySelectorAll('table'));})();</script> ```

Sample:

2. Available Options

The options supplied to the ‘TablePagination.page‘ function is an object that is made up of the following properties.

``` 2. Available Options JavaScript // Available options TablePagination.page({ table: document.querySelector('table'), // One or more Javascript elements of the tables to page. rowsPerPage: 4, // Optional. The number of rows per page. Default is 5 initialPage: null, // Optional. The initial page to display. Possible values: Numeric value or 'first/last'. Default is page 1 navigationPosition: 'bottom', // Optional. The navigation position. Possible values: 'top/bottom'. Default is 'bottom' showFirstPageButton: true, // Optional. Specifies if the first page button is shown. Default is true showLastPageButton: true, // Optional. Specifies if the last page button is shown. Default is true showPreviousPageButton: true, // Optional. Specifies if the previous page button is shown. Default is true showNextPageButton: true, // Optional. Specifies if the next page button is shown. Default is true showPageNumberButtons: true, // Optional. Specifies if the page number buttons are shown. Default is true showNavigationInput: true, // Optional. Specifies if the 'Go' search functionality is shown. Default is true showNavigationInfoText: true, // Optional. Specifies if the navigation info text is shown. Default is true visiblePageNumberButtons: 4, // Optional. The maximum number of visible page number buttons. Default is 3. Set to null to show all buttons onButtonClick: (pageNumber, event) => { // Optional. Function that allows to do something on button click //window.location.href = "#page=" + pageNumber; }, onButtonTextRender: (text, desc) => { // Optional. Function that allows to format the button text //console.log(`Button Text: \${text}`); //console.log(`Button Description: \${desc}`); return text; }, onButtonTitleRender: (title, desc) => { // Optional. Function that allows to format the button title //console.log(`Button Text: \${text}`); //console.log(`Button Description: \${desc}`); return title; }, onNavigationInfoTextRender: (text, rowInfo) => { // Optional. Function that allows to format the navigation info text //console.log(`Navigation Text: \${text}`); //console.log(`Row Info:`, rowInfo); return text; }, navigationBindTo: null, // Optional. Javascript element of the container where the navigation controls are bound to. // If not specified, default destination is above or below the table element, depending on // the 'navigationPosition' value }); 12345678910111213141516171819202122232425262728293031323334353637 // Available options TablePagination.page({    table: document.querySelector('table'), // One or more Javascript elements of the tables to page.    rowsPerPage: 4,                         // Optional. The number of rows per page. Default is 5    initialPage: null,                      // Optional. The initial page to display. Possible values: Numeric value or 'first/last'. Default is page 1    navigationPosition: 'bottom',           // Optional. The navigation position. Possible values: 'top/bottom'. Default is 'bottom'    showFirstPageButton: true,              // Optional. Specifies if the first page button is shown. Default is true    showLastPageButton: true,               // Optional. Specifies if the last page button is shown. Default is true    showPreviousPageButton: true,           // Optional. Specifies if the previous page button is shown. Default is true    showNextPageButton: true,               // Optional. Specifies if the next page button is shown. Default is true    showPageNumberButtons: true,            // Optional. Specifies if the page number buttons are shown. Default is true    showNavigationInput: true,              // Optional. Specifies if the 'Go' search functionality is shown. Default is true    showNavigationInfoText: true,           // Optional. Specifies if the navigation info text is shown. Default is true            visiblePageNumberButtons: 4,            // Optional. The maximum number of visible page number buttons. Default is 3. Set to null to show all buttons    onButtonClick: (pageNumber, event) => { // Optional. Function that allows to do something on button click        //window.location.href = "#page=" + pageNumber;    },    onButtonTextRender: (text, desc) => {   // Optional. Function that allows to format the button text        //console.log(`Button Text: \${text}`);        //console.log(`Button Description: \${desc}`);        return text;    },    onButtonTitleRender: (title, desc) => { // Optional. Function that allows to format the button title        //console.log(`Button Text: \${text}`);        //console.log(`Button Description: \${desc}`);        return title;    },      onNavigationInfoTextRender: (text, rowInfo) => { // Optional. Function that allows to format the navigation info text        //console.log(`Navigation Text: \${text}`);        //console.log(`Row Info:`, rowInfo);        return text;    },              navigationBindTo: null, // Optional. Javascript element of the container where the navigation controls are bound to.                             // If not specified, default destination is above or below the table element, depending on                             // the 'navigationPosition' value}); ```

Supplying different options to ‘TablePagination.page‘ can change its appearance. The following examples below demonstrate this.

3. Only Show Page Numbers

The following example demonstrates pagination with only page numbers.

``` 3. Only Show Page Numbers JavaScript // Pagination with only page numbers. <script> (() => { // Only show page numbers TablePagination.page({ table: document.querySelectorAll('table'), rowsPerPage: 2, showFirstPageButton: false, showLastPageButton: false, showNavigationInput: false, }); })(); </script> 1234567891011121314 // Pagination with only page numbers.  <script>(() => {    // Only show page numbers    TablePagination.page({        table: document.querySelectorAll('table'),        rowsPerPage: 2,         showFirstPageButton: false,        showLastPageButton: false,        showNavigationInput: false,    });})();</script> ```

Sample:

4. Mini – Only Show Arrow Buttons

The following example demonstrates pagination with only arrow buttons.

``` 4. Mini - Only Show Arrow Buttons JavaScript // Pagination with only arrow buttons. <script> (() => { // Only show arrow buttons TablePagination.page({ table: document.querySelectorAll('table'), rowsPerPage: 2, showFirstPageButton: false, showLastPageButton: false, showPageNumberButtons: false, showNavigationInput: false, }); })(); </script> 123456789101112131415 // Pagination with only arrow buttons.  <script>(() => {    // Only show arrow buttons    TablePagination.page({        table: document.querySelectorAll('table'),        rowsPerPage: 2,         showFirstPageButton: false,        showLastPageButton: false,        showPageNumberButtons: false,        showNavigationInput: false,    });})();</script> ```

Sample:

5. Show All Pages

The following example demonstrates pagination showing all page numbers.

``` 5. Show All Pages JavaScript // Pagination showing all page numbers. <script> (() => { // Show all page numbers TablePagination.page({ table: document.querySelectorAll('table'), rowsPerPage: 8, showFirstPageButton: false, showLastPageButton: false, showPreviousPageButton: false, showNextPageButton: false, showNavigationInput: false, visiblePageNumberButtons: null }); })(); </script> 1234567891011121314151617 // Pagination showing all page numbers.  <script>(() => {    // Show all page numbers    TablePagination.page({        table: document.querySelectorAll('table'),        rowsPerPage: 8,         showFirstPageButton: false,        showLastPageButton: false,         showPreviousPageButton: false,        showNextPageButton: false,        showNavigationInput: false,        visiblePageNumberButtons: null    });})();</script> ```

Sample:

6. Only Show Go Input

The following example demonstrates pagination with only showing the “Go” user input option.

``` 6. Only Show Go Input JavaScript // Pagination with only showing go input. <script> (() => { // Only showing go input TablePagination.page({ table: document.querySelectorAll('table'), rowsPerPage: 2, showFirstPageButton: false, showLastPageButton: false, showPreviousPageButton: false, showNextPageButton: false, showPageNumberButtons: false, }); })(); </script> 12345678910111213141516 // Pagination with only showing go input.  <script>(() => {    // Only showing go input    TablePagination.page({        table: document.querySelectorAll('table'),        rowsPerPage: 2,         showFirstPageButton: false,        showLastPageButton: false,         showPreviousPageButton: false,        showNextPageButton: false,        showPageNumberButtons: false,    });})();</script> ```

Sample:

The following example demonstrates pagination formatting the navigation text. This allows to alter the navigation text without having to modify the pagination code!

``` 7. Format Navigation Text JavaScript // Pagination formatting the navigation text. <script> (() => { // Pagination formatting the navigation text TablePagination.page({ table: document.querySelectorAll('table'), rowsPerPage: 2, onButtonTextRender: (text, desc) => { switch (desc) { case TablePagination.settings.onRenderDescFirstPage: break case TablePagination.settings.onRenderDescPrevPage: break case TablePagination.settings.onRenderDescPageNumber: text += ' - Test'; break; case TablePagination.settings.onRenderDescNextPage: break case TablePagination.settings.onRenderDescLastPage: break case TablePagination.settings.onRenderDescGoInput: break } return text; }, onButtonTitleRender: (title, desc) => { switch (desc) { case TablePagination.settings.onRenderDescFirstPage: break case TablePagination.settings.onRenderDescPrevPage: break case TablePagination.settings.onRenderDescPageNumber: title += ' - Test'; break; case TablePagination.settings.onRenderDescNextPage: break case TablePagination.settings.onRenderDescLastPage: break case TablePagination.settings.onRenderDescGoInput: break } return title; }, onNavigationInfoTextRender: (text, rowInfo) => { text += ' - Test' return text; }, }); })(); </script> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 // Pagination formatting the navigation text.  <script>(() => {    // Pagination formatting the navigation text    TablePagination.page({        table: document.querySelectorAll('table'),        rowsPerPage: 2,         onButtonTextRender: (text, desc) => {            switch (desc) {                                  case TablePagination.settings.onRenderDescFirstPage:                    break                 case TablePagination.settings.onRenderDescPrevPage:                    break                 case TablePagination.settings.onRenderDescPageNumber:                    text += ' - Test';                    break;                 case TablePagination.settings.onRenderDescNextPage:                    break                 case TablePagination.settings.onRenderDescLastPage:                    break                 case TablePagination.settings.onRenderDescGoInput:                     break                              }            return text;        },          onButtonTitleRender: (title, desc) => {             switch (desc) {                case TablePagination.settings.onRenderDescFirstPage:                    break                 case TablePagination.settings.onRenderDescPrevPage:                    break                 case TablePagination.settings.onRenderDescPageNumber:                    title += ' - Test';                    break;                 case TablePagination.settings.onRenderDescNextPage:                    break                 case TablePagination.settings.onRenderDescLastPage:                    break                 case TablePagination.settings.onRenderDescGoInput:                     break             }             return title;        },        onNavigationInfoTextRender: (text, rowInfo) => {             text += ' - Test'            return text;        },          });})();</script> ```

Sample:

8. Button Click Event

The following example demonstrates pagination with the button click callback. This allows you to do something on button click

``` 8. Button Click Event JavaScript // Pagination onButtonClick callback. <script> (() => { // onButtonClick callback allows you to do something on button click TablePagination.page({ table: document.querySelectorAll('table'), rowsPerPage: 2, onButtonClick: (pageNumber, event) => { alert(pageNumber); window.location.href = "#page=" + pageNumber; }, }); })(); </script> 123456789101112131415 // Pagination onButtonClick callback.  <script>(() => {    // onButtonClick callback allows you to do something on button click    TablePagination.page({        table: document.querySelectorAll('table'),        rowsPerPage: 2,         onButtonClick: (pageNumber, event) => {            alert(pageNumber);            window.location.href = "#page=" + pageNumber;                   },          });})();</script> ```

Sample:

The following example demonstrates formatting the navigation position. The position options can be on top, or bottom. Bottom is the default position.

``` 9. Navigation Position - Top JavaScript // Pagination navigation position. <script> (() => { // Navigation position - top TablePagination.page({ table: document.querySelectorAll('table'), rowsPerPage: 2, navigationPosition: 'top' }); })(); </script> 123456789101112 // Pagination navigation position.  <script>(() => {    // Navigation position - top    TablePagination.page({        table: document.querySelectorAll('table'),        rowsPerPage: 2,         navigationPosition: 'top'    });})();</script> ```

Sample:

10. Specify Initial Page

The following example demonstrates pagination setting the initial default page.

``` 10. Specify Initial Page JavaScript // Pagination with initial page set. <script> (() => { // Set initial page TablePagination.page({ table: document.querySelectorAll('table'), rowsPerPage: 2, initialPage: 3 }); })(); </script> 123456789101112 // Pagination with initial page set.  <script>(() => {    // Set initial page    TablePagination.page({        table: document.querySelectorAll('table'),        rowsPerPage: 2,         initialPage: 3    });})();</script> ```

Sample:

By default, the navigation controls are placed either above or below the table element, depending on the ‘navigationPosition’ value. You can override this placement by specifying the container where the controls should be bound to.

The following example demonstrates specifying the element where the controls are bound to.

``` 11. Navigation Binding Area JavaScript // Navigation Binding Area. <script> (() => { // Navigation Binding Area TablePagination.page({ table: document.querySelectorAll('table'), rowsPerPage: 2, navigationPosition: 'bottom', navigationBindTo: document.querySelector('#binding-section') }); })(); </script> 12345678910111213 // Navigation Binding Area.  <script>(() => {    // Navigation Binding Area    TablePagination.page({        table: document.querySelectorAll('table'),        rowsPerPage: 2,         navigationPosition: 'bottom',        navigationBindTo: document.querySelector('#binding-section')    });})();</script> ```

Sample:

12. Remove Pagination

The following example demonstrates how to remove pagination from a table.

TablePagination.remove‘ will remove pagination. It accepts one or more HTMLTableElement.

``` 12. Remove Pagination JavaScript // Remove table pagination. <script> (() => { // Removes table pagination from the table elements TablePagination.remove(document.querySelectorAll('table')); })(); </script> 12345678 // Remove table pagination.  <script>(() => {    // Removes table pagination from the table elements    TablePagination.remove(document.querySelectorAll('table'));})();</script> ```

13. TablePagination.js & CSS Source

The following is the TablePagination.js Namespace & CSS Source. Include this in your project to start using!

``` TablePagination.js Namespace JavaScript // ============================================================================ // Author: Kenneth Perkins // Date: Aug 5, 2020 // Taken From: http://programmingnotes.org/ // File: TablePagination.js // Description: Namespace which handles html table pagination // Example: // // Add Pagination to a table // TablePagination.page({ // table: document.querySelector('table'), // rowsPerPage: 10 // }); // ============================================================================ /** * NAMESPACE: TablePagination * USE: Handles html table pagination. */ var TablePagination = TablePagination || {}; (function(namespace) { 'use strict'; // -- Public data -- // Property to hold public variables and functions let exposed = namespace; // Set class names and other shared data const settings = { // Misc settings defaultRowsPerPage: 5, defaultPosition: 'bottom', defaultVisibleButtons: 3, onRenderDescFirstPage: 'first_page', onRenderDescPrevPage: 'previous_page', onRenderDescPageNumber: 'page_number', onRenderDescNextPage: 'next_page', onRenderDescLastPage: 'last_page', onRenderDescGoInput: 'go_input', buttonOptionFirst: 'first', buttonOptionPrevious: 'previous', buttonOptionNext: 'next', buttonOptionLast: 'last', navigationPositionTop: 'top', navigationPositionBottom: 'bottom', onTextRender: (text) => text, // Element class names classNameHide: '.pagination-hide', classNameButton: 'pagination-btn', classNameButtonActive: 'active', classNameButtonFirst: 'first', classNameButtonPrevious: 'previous', classNameButtonPageNumber: 'page-number', classNameButtonNext: 'next', classNameButtonLast: 'last', classNameButtonGo: 'go', classNameButtonHide: 'hide', classNameNavigation: 'pagination-navigation', classNameNavigationTop: 'top', classNameNavigationBottom: 'bottom', classNameNavigationInfoSection: 'pagination-navigation-info-section', classNameNavigationControlSection: 'pagination-navigation-control-section', classNameNavigationButtonSection: 'pagination-navigation-button-section', classNameNavigationInputSection: 'pagination-navigation-input-section', classNameNavigationInput: 'pagination-navigation-input', // Element data names dataNamePageNumber: 'data-pageNumber', dataNameTotalPages: 'data-totalPages', dataNameRowsPerPage: 'data-rowsPerPage', dataNameCurrentPageNumber: 'data-currentPageNumber', dataNameNavigationId: 'data-navigationId', dataNameNavigationInfoId: 'data-navigationInfoId', dataNameNavigationInputId: 'data-navigationInputId', dataNameNavigationButtonsId: 'data-navigationButtonsId', dataNameVisiblePageButtons: 'data-visiblePageButtons', cleanClassName: (str) => { return str ? str.trim().replace('.', '') : ''; }, }; exposed.settings = settings; /** * FUNCTION: page * USE: Initializes & renders pagination for the given table elements * @param options: An object of initialization options. * Its made up of the following properties: * { * table: One or more Javascript elements of the tables to page. * rowsPerPage: Optional. The number of rows per page. Default is page 5 * initialPage: Optional. The initial page to display. Posible values: Numeric value * or 'first/last'. Default is page 1 * navigationPosition: Optional. The navigation position. Posible values: 'top/bottom'. * Default is 'bottom' * showFirstPageButton: Optional. Boolean that indicates if the first page * button should be displayed. Default is true * showLastPageButton: Optional. Boolean that indicates if the last page * button should be displayed. Default is true * showPreviousPageButton: Optional. Boolean that indicates if the previous page * button should be displayed. Default is true * showNextPageButton: Optional. Boolean that indicates if the next page * button should be displayed. Default is true * showPageNumberButtons: Optional. Boolean that indicates if the page number buttons * should be displayed. Default is true * showNavigationInput: Optional. Specifies if the 'Go' search functionality is shown. * Default is true * showNavigationInfoText: Optional. Specifies if the navigation info text is shown. * Default is true * visiblePageNumberButtons: Optional. The maximum number of visible page number buttons. * Default is 3. Set to null to show all buttons * onButtonClick(pageNumber, event): Optional. Function that allows to do something on * button click * onButtonTextRender(text, desc): Optional. Function that allows to format the button text * onButtonTitleRender(title, desc): Optional. Function that allows to format the button title * onNavigationInfoTextRender(text, rowInfo): Optional. Function that allows to format * the navigation info text * navigationBindTo: Optional. Javascript element of the container where the navigation controls * are bound to. If not specified, default destination is above or below the table element, * depending on the 'navigationPosition' value * } * @return: N/A. */ exposed.page = (options) => { // Make sure the required options are valid if (isNull(options)) { // Check to see if there are options throw new TypeError('There are no options specified.'); } else if (typeof options !== 'object' || isElement(options) || isArrayLike(options)) { // Check to see if a table is specified let table = options; options = {}; options.table = table; } // Make sure the table is an array if (!isArrayLike(options.table)) { options.table = [options.table]; } // Make sure additional options are valid if (!isNull(options.rowsPerPage) && !isNumeric(options.rowsPerPage)) { // Check to see if a rowsPerPage is valid throw new TypeError(`Unable to process rowsPerPage of type: \${typeof options.rowsPerPage}. Reason: '\${options.rowsPerPage}' is not a numeric value.`); } else if (!isNull(options.navigationBindTo) && !isElement(options.navigationBindTo)) { // Check to see if the navigation bind to element is an HTMLElement throw new TypeError(`Unable to process navigationBindTo of type: \${typeof options.navigationBindTo}. Reason: '\${options.navigationBindTo}' is not an HTMLElement.`); } else if (!isNull(options.onButtonTitleRender) && !isFunction(options.onButtonTitleRender)) { // Check to see if callback is a function throw new TypeError(`Unable to call onButtonTitleRender of type: \${typeof options.onButtonTitleRender}. Reason: '\${options.onButtonTitleRender}' is not a function.`); } else if (!isNull(options.onButtonTextRender) && !isFunction(options.onButtonTextRender)) { // Check to see if callback is a function throw new TypeError(`Unable to call onButtonTextRender of type: \${typeof options.onButtonTextRender}. Reason: '\${options.onButtonTextRender}' is not a function.`); } else if (!isNull(options.onButtonClick) && !isFunction(options.onButtonClick)) { // Check to see if callback is a function throw new TypeError(`Unable to call onButtonClick of type: \${typeof options.onButtonClick}. Reason: '\${options.onButtonClick}' is not a function.`); } else if (!isNull(options.visiblePageNumberButtons) && !isNumeric(options.visiblePageNumberButtons)) { // Check to see if a visiblePageNumberButtons is valid throw new TypeError(`Unable to process visiblePageNumberButtons of type: \${typeof options.visiblePageNumberButtons}. Reason: '\${options.visiblePageNumberButtons}' is not a numeric value.`); } else if (!isNull(options.onNavigationInfoTextRender) && !isFunction(options.onNavigationInfoTextRender)) { // Check to see if callback is a function throw new TypeError(`Unable to call onNavigationInfoTextRender of type: \${typeof options.onNavigationInfoTextRender}. Reason: '\${options.onNavigationInfoTextRender}' is not a function.`); } // Get the tables and remove the property from the object let tables = options.table; delete options.table; // Page the tables for (let index = 0; index < tables.length; ++index) { // Get the table and make sure its valid let table = tables[index]; if (!isTable(table)) { // Check to see if the table is an HTMLTableElement throw new TypeError(`Unable to process \${getTableDisplayName(table)} of type: \${typeof table}. Reason: '\${table}' is not an HTMLTableElement.`); } // Build the table navigation controls buildNavigation(table, options) // Add click events for the navigation controls addClickEvents(table, options); // Show the initial page showPage(table, {pageNumber: getInitialPage(table, options.initialPage), pageOptions: options}); } } /** * FUNCTION: remove * USE: Removes the rendered table pagination * @param table: JavaScript elements of the paged tables. * @return: True if table pagination controls were removed from all tables, false otherwise. */ exposed.remove = (tables) => { if (isNull(tables)) { return false; } else if (!isArrayLike(tables)) { tables = [tables]; } let allRemoved = true; for (let index = 0; index < tables.length; ++index) { let table = tables[index]; if (!isTable(table)) { // Check to see if the table is an HTMLTableElement throw new TypeError(`Unable to process \${getTableDisplayName(table)} of type: \${typeof table}. Reason: '\${table}' is not an HTMLTableElement.`); } if (!removeNavigation(table)) { allRemoved = false; } } return allRemoved; } // -- Private data -- let getRows = (table) => { let rows = table.rows; let results = []; // Only return data rows for (let indexRow = 0; indexRow < rows.length; ++indexRow) { let row = rows[indexRow]; let isTDRow = true; for (let indexCell = 0; indexCell < row.cells.length; ++indexCell) { let cell = row.cells[indexCell]; if (cell.tagName.toLowerCase() !== 'td') { isTDRow = false; break; } } if (isTDRow) { results.push(row); } } return results; } let buildNavigation = (table, options) => { // Remove the previous navigation removeNavigation(table); // Set the max rows per page let rowsPerPage = options.rowsPerPage || settings.defaultRowsPerPage; setRowsPerPage(table, rowsPerPage); // Calculate the number of pages needed and set its value let totalPages = calculateTotalPagesRequired(table); setTotalPages(table, totalPages); if (totalPages < 1) { throw new Error(`\${totalPages} pages calculated in order to page the table. Exiting...`); } // Get the current options let position = (options.navigationPosition || settings.defaultPosition).trim().toLowerCase(); let showNavigationInfoText = !isNull(options.showNavigationInfoText) ? options.showNavigationInfoText : true; let navigationBindTo = options.navigationBindTo || table.parentNode; let isCustomBinding = !isNull(options.navigationBindTo); // Add the navigation controls to the page let navigationContainer = attachNavigation({ table: table, container: navigationBindTo, isCustomBinding: isCustomBinding, position: position, classes: getNavigationClasses(position), data: [{key: 'tabindex', value: 0}] }); // Show page info if (showNavigationInfoText) { attachNavigationInfo({ table: table, container: navigationContainer, classes: [settings.classNameNavigationInfoSection] }); } // Add navigation buttons attatchNavigationButtons({ table: table, pageOptions: options, container: navigationContainer, classes: [settings.classNameNavigationControlSection] }); } let addClickEvents = (table, options) => { let paginationButtons = getNavigationButtons(table); let inputButton = getInputButton(table); let inputTextbox = getInputTextbox(table); let navigation = document.querySelector(`#\${getNavigationId(table)}`); // Make sure there are visible navigation buttons let navigationVisible = (!isNull(paginationButtons) && paginationButtons.length > 0) || (!isNull(inputButton) && !isNull(inputTextbox)); // Throw an error if there are no visible navigation buttons if (!navigationVisible) { throw new Error(`The settings chosen on \${getTableDisplayName(table)} do not allow for any visible navigation buttons!`); } // Function to go to a page let navigateToPage = (pageNumber, event) => { pageNumber = translatePageNumber(table, pageNumber); if (!isNumeric(pageNumber)) { return false; } // Show the page showPage(table, {pageNumber: pageNumber, pageOptions: options}); // Call the on click function if specified if (options.onButtonClick) { options.onButtonClick.call(this, pageNumber, event); } return true; } // Add click events for the navigation buttons if (!isNull(paginationButtons)) { paginationButtons.forEach((paginationButton, index) => { // Add button click paginationButton.addEventListener('click', (event) => { event.preventDefault(); let pageNumber = getButtonPageNumber(paginationButton); navigateToPage(pageNumber, event); navigation.focus({preventScroll:true}); }); }); } // Add click event for the input button if (!isNull(inputButton)) { inputButton.addEventListener('click', (event) => { event.preventDefault(); // Get the input textbox let pageNumber = getInputValue(table, inputTextbox); navigateToPage(pageNumber, event); }); } // Add click event for the input textbox if (!isNull(inputTextbox)) { inputTextbox.addEventListener('keyup', (event) => { event = event || window.event; let keyCode = event.key || event.keyCode; // Check to see if the enter button was clicked switch (String(keyCode)) { case 'Enter': case '13': inputButton.click(); break; } }); } // Add click events for the left/right keyboard buttons if (!isNull(navigation)) { navigation.addEventListener('keydown', (event) => { event = event || window.event; let keyCode = event.key || event.keyCode; let pageNumber = getCurrentPageNumber(table); // Check to see if an arrow key was clicked switch (String(keyCode)) { case 'ArrowLeft': case 'Left': case '37': --pageNumber; break; case 'ArrowRight': case 'Right': case '39': ++pageNumber; break; default: return; break; } navigateToPage(pageNumber, event); }); } } let getTableId = (table) => { let tableId = !isNull(table.id) && table.id.length > 0 ? table.id : null; return tableId; } let getTableDisplayName = (table) => { let tableId = getTableId(table); let tableName = 'Table' + (tableId ? ' id: "' + tableId + '"' : ''); return tableName; } let getInitialPage = (table, initialPage) => { let initialActivePage = 1; if (!isNull(initialPage)) { let possiblePageNumber = translatePageNumber(table, initialPage); if (isNumeric(possiblePageNumber)) { initialActivePage = possiblePageNumber; } } return initialActivePage; } let translatePageNumber = (table, pageNumber) => { if (!isNull(pageNumber) && !isNumeric(pageNumber)) { pageNumber = String(pageNumber).trim().toLowerCase(); switch (pageNumber) { case settings.buttonOptionFirst.trim().toLowerCase(): pageNumber = 1; break; case settings.buttonOptionLast.trim().toLowerCase(): pageNumber = getTotalPages(table); break; case settings.buttonOptionPrevious.trim().toLowerCase(): pageNumber = getCurrentPageNumber(table) - 1; break; case settings.buttonOptionNext.trim().toLowerCase(): pageNumber = getCurrentPageNumber(table) + 1; break; } } return pageNumber; } let getNavigationClasses = (position) => { let navigationClasses = [] navigationClasses.push(settings.classNameNavigation); if (position == settings.navigationPositionTop.trim().toLowerCase()) { navigationClasses.push(settings.classNameNavigationTop); } else { navigationClasses.push(settings.classNameNavigationBottom); } return navigationClasses; } let hideAllRows = (table) => { let totalPages = getTotalPages(table); for (let pageNumber = 1; pageNumber <= totalPages; ++pageNumber) { hidePage(table, {pageNumber: pageNumber}); } } let hidePage = (table, options) => { let pageNumber = options.pageNumber; let rowInfo = getRowInfo(table, pageNumber); let rowIndexStart = rowInfo.rowIndexStart; let rowIndexEnd = rowInfo.rowIndexEnd; hideRows(table, rowIndexStart, rowIndexEnd); } let hideRows = (table, rowIndexStart, rowIndexEnd) => { let tableRows = getRows(table); for (let index = rowIndexStart; index <= rowIndexEnd && index < tableRows.length; ++index) { let tableRow = tableRows[index]; hideRow(tableRow); } } let hideRow = (tableRow) => { addClass(tableRow, settings.classNameHide); } let showAllRows = (table) => { let totalPages = getTotalPages(table); for (let pageNumber = 1; pageNumber <= totalPages; ++pageNumber) { showPage(table, { pageNumber: pageNumber, hidePreviousRows: false }); } } let showPage = (table, options) => { if (isNull(options.hidePreviousRows) || options.hidePreviousRows) { hideAllRows(table); } let rowInfo = getRowInfo(table, options.pageNumber); let rowIndexStart = rowInfo.rowIndexStart; let rowIndexEnd = rowInfo.rowIndexEnd; let pageNumber = rowInfo.pageNumber; showRows(table, rowIndexStart, rowIndexEnd); setCurrentPageNumber(table, pageNumber); highlightButton(table, pageNumber); showPageButtons(table, pageNumber); updateInfoText(table, rowInfo, options.pageOptions); clearInputValue(table); } let showRows = (table, rowIndexStart, rowIndexEnd) => { let tableRows = getRows(table); for (let index = rowIndexStart; index <= rowIndexEnd && index < tableRows.length; ++index) { let tableRow = tableRows[index]; showRow(tableRow); } } let showRow = (tableRow) => { removeClass(tableRow, settings.classNameHide); } let clearInputValue = (table, inputTextbox = null) => { inputTextbox = inputTextbox || getInputTextbox(table); if (!isNull(inputTextbox)) { inputTextbox.value = null; } } let getInputValue = (table, inputTextbox = null) => { inputTextbox = inputTextbox || getInputTextbox(table); return !isNull(inputTextbox) ? inputTextbox.value : null; } let updateInfoText = (table, rowInfo, pageOptions) => { let navigationInfo = getNavigationInfo(table); if (isNull(navigationInfo)) { return; } let text = `Showing \${rowInfo.itemCountStart} to \${rowInfo.itemCountEnd} of \${rowInfo.totalItems} entries.`; text += `<br />`; text += `Page \${rowInfo.pageNumber} of \${rowInfo.totalPages}`; let onNavigationInfoTextRender = settings.onTextRender; if (!isNull(pageOptions) && !isNull(pageOptions.onNavigationInfoTextRender)) { onNavigationInfoTextRender = pageOptions.onNavigationInfoTextRender; } navigationInfo.innerHTML = onNavigationInfoTextRender.call(this, text, rowInfo); } let showPageButtons = (table, pageNumber) => { let visibleButtons = getTotalVisiblePageButtons(table); if (!isNumeric(visibleButtons)) { return; } let totalPages = getTotalPages(table); let firstVisiblePage = Math.max(0, getPreviousMultiple(pageNumber, visibleButtons)) + 1; let lastVisiblePage = Math.min(totalPages, getNextMultiple(pageNumber, visibleButtons)); // Make sure there are at least 'visibleButtons' total buttons shown let difference = (visibleButtons - 1) - (lastVisiblePage - firstVisiblePage); if (difference > 0) { firstVisiblePage -= difference; } getNavigationButtons(table).forEach((btn, index) => { let buttonPageNumber = getButtonPageNumber(btn); if (isNumeric(buttonPageNumber)) { buttonPageNumber = Number(buttonPageNumber); addClass(btn, settings.classNameButtonHide); if (buttonPageNumber >= firstVisiblePage && buttonPageNumber <= lastVisiblePage) { removeClass(btn, settings.classNameButtonHide); } } }); } let getRowInfo = (table, pageNumber) => { let totalPages = getTotalPages(table); let rows = getRows(table); // Make sure the page number is within valid range [1 to last page number] pageNumber = Math.max(1, Math.min(pageNumber, totalPages)); let totalItems = rows.length; let rowsPerPage = getRowsPerPage(table); let rowIndexStart = (pageNumber - 1) * rowsPerPage; let rowIndexEnd = Math.min(rowIndexStart + (rowsPerPage - 1), totalItems - 1); let rowInfo = { rowIndexStart: rowIndexStart, rowIndexEnd: rowIndexEnd, pageNumber: pageNumber, totalPages: totalPages, totalItems: totalItems, rowsPerPage: rowsPerPage, itemCountStart: rowIndexStart + 1, itemCountEnd: rowIndexEnd + 1, }; return rowInfo; } let getCurrentPageNumber = (table) => { let pageNumber = getData(table, settings.dataNameCurrentPageNumber); return isNull(pageNumber) ? 0 : Number(pageNumber); } let setCurrentPageNumber = (table, pageNumber) => { addData(table, {key: settings.dataNameCurrentPageNumber, value: pageNumber}); } let highlightButton = (table, pageNumber) => { let paginationButton = null; let paginationButtons = getNavigationButtons(table); if (isNull(paginationButtons)) { return; } // Reset the previous page button colors resetButtonColors(paginationButtons); // Mark the selected button as active paginationButtons.forEach((btn, index) => { let buttonPageNumber = getButtonPageNumber(btn); if (isNumeric(buttonPageNumber) && Number(pageNumber) === Number(buttonPageNumber)) { paginationButton = btn; return false; } }); if (!isNull(paginationButton)) { addClass(paginationButton, settings.classNameButtonActive); } } let resetButtonColors = (paginationButtons) => { if (isNull(paginationButtons)) { return; } paginationButtons.forEach((paginationButton, index) => { let buttonPageNumber = getButtonPageNumber(paginationButton); if (isNumeric(buttonPageNumber)) { removeClass(paginationButton, settings.classNameButtonActive); } }); } let getButtonPageNumber = (btn) => { let pageNumber = getData(btn, settings.dataNamePageNumber); return String(!isNull(pageNumber) ? pageNumber : 0); } let setNavigationId = (table, navigationId) => { addData(table, {key: settings.dataNameNavigationId, value: navigationId}); } let getNavigationId = (table) => { return getData(table, settings.dataNameNavigationId); } let setNavigationInfoId = (table, navigationInfoId) => { addData(table, {key: settings.dataNameNavigationInfoId, value: navigationInfoId}); } let getNavigationInfoId = (table) => { return getData(table, settings.dataNameNavigationInfoId); } let setNavigationInputId = (table, navigationInputId) => { addData(table, {key: settings.dataNameNavigationInputId, value: navigationInputId}); } let getNavigationInputId = (table) => { return getData(table, settings.dataNameNavigationInputId); } let getNavigationButtons = (table) => { let selector = `#\${getNavigationButtonsId(table)} a`; return document.querySelectorAll(selector); } let getInputButton = (table) => { let selector = `#\${getNavigationInputId(table)} a`; return document.querySelector(selector); } let getInputTextbox = (table) => { let selector = `#\${getNavigationInputId(table)} input`; return document.querySelector(selector); } let getNavigationInfo = (table) => { let selector = `#\${getNavigationInfoId(table)}`; return document.querySelector(selector); } let setNavigationButtonsId = (table, navigationButtonsId) => { addData(table, {key: settings.dataNameNavigationButtonsId, value: navigationButtonsId}); } let getNavigationButtonsId = (table) => { return getData(table, settings.dataNameNavigationButtonsId); } let getTotalVisiblePageButtons = (table) => { let value = getData(table, settings.dataNameVisiblePageButtons); return !isNull(value) ? Number(value) : value; } let setTotalVisiblePageButtons = (table, visiblePageButtons) => { addData(table, {key: settings.dataNameVisiblePageButtons, value: visiblePageButtons}); } let setRowsPerPage = (table, rowsPerPage) => { addData(table, {key: settings.dataNameRowsPerPage, value: rowsPerPage}); } let getRowsPerPage = (table) => { let value = getData(table, settings.dataNameRowsPerPage); return !isNull(value) ? Number(value) : value; } let setTotalPages = (table, totalPages) => { addData(table, {key: settings.dataNameTotalPages, value: totalPages}); } let getTotalPages = (table) => { let value = getData(table, settings.dataNameTotalPages); return !isNull(value) ? Number(value) : value; } let calculateTotalPagesRequired = (table) => { let rowsPerPage = getRowsPerPage(table); let totalRows = getRows(table).length; let totalPages = totalRows / rowsPerPage; if (totalRows % rowsPerPage !== 0) { totalPages = Math.floor(++totalPages); } return totalPages; } let addClass = (element, cssClass) => { cssClass = settings.cleanClassName(cssClass); let modified = false; if (cssClass.length > 0 && !hasClass(element, cssClass)) { element.classList.add(cssClass) modified = true; } return modified; } let removeClass = (element, cssClass) => { cssClass = settings.cleanClassName(cssClass); let modified = false; if (cssClass.length > 0 && hasClass(element, cssClass)) { element.classList.remove(cssClass); modified = true; } return modified; } let hasClass = (element, cssClass) => { cssClass = settings.cleanClassName(cssClass); return element.classList.contains(cssClass); } let isNull = (item) => { return isUndefined(item) || null === item; } let isUndefined = (item) => { return undefined === item; } let isFunction = (item) => { return 'function' === typeof item } let isTable = (item) => { return isElement(item) && item instanceof HTMLTableElement; } let isElement = (item) => { let value = false; try { value = item instanceof HTMLElement || item instanceof HTMLDocument; } catch (e) { value = (typeof item==="object") && (item.nodeType===1) && (typeof item.style === "object") && (typeof item.ownerDocument ==="object"); } return value; } let randomFromTo = (from, to) => { return Math.floor(Math.random() * (to - from + 1) + from); } let isNumeric = (n) => { return !isNaN(parseFloat(n)) && isFinite(n); } let generateNavigationId = (table) => { let tableId = getTableId(table); return 'tablePaginationNavigation_' + (tableId ? tableId : randomFromTo(1271991, 7281987)); } let removeNavigation = (table) => { let modified = false; let previousNavigationId = getNavigationId(table); // Remove the previous table navigation if (!isNull(previousNavigationId)) { let previousElement = document.querySelector(`#\${previousNavigationId}`); if (!isNull(previousElement)) { previousElement.parentNode.removeChild(previousElement); showAllRows(table); modified = true; } } return modified; } let attachNavigation = (options) => { // Create the table navigation control div let navigationContainer = document.createElement('div'); navigationContainer.id = generateNavigationId(options.table); // Determine the navigation position let position = options.position.trim().toLowerCase(); if (!options.isCustomBinding) { if (position === settings.navigationPositionTop) { // Insert navigation before the table options.container.insertBefore(navigationContainer, options.table); } else { // Insert navigation after the table options.container.insertBefore(navigationContainer, options.table.nextSibling); } } else { if (position === settings.navigationPositionTop) { // Insert navigation at the beginning of the container options.container.insertBefore(navigationContainer, options.container.firstChild); } else { // Insert navigation ar end of the container options.container.insertBefore(navigationContainer, options.container.lastChild); } } // Add classes and data addClasses(navigationContainer, options.classes); addData(navigationContainer, options.data); // Set the current table navigation control id setNavigationId(options.table, navigationContainer.id); setNavigationInfoId(options.table, null); return navigationContainer; } let attachButton = (options) => { let btn = document.createElement('a'); btn.href = '#'; addClasses(btn, options.classes); addData(btn, options.data); btn.insertAdjacentHTML('beforeend', options.text); btn.title = options.title; options.container.appendChild(btn); return btn; } let attatchNavigationButtons = (options) => { let pageOptions = options.pageOptions; let table = options.table; // Create the table navigation info control div let navigationButtonSection = document.createElement('div'); navigationButtonSection.id = options.container.id + '_control_section'; options.container.appendChild(navigationButtonSection); // Add classes and data addClasses(navigationButtonSection, options.classes); addData(navigationButtonSection, options.data); let showFirstPageButton = !isNull(pageOptions.showFirstPageButton) ? pageOptions.showFirstPageButton : true; let showLastPageButton = !isNull(pageOptions.showLastPageButton) ? pageOptions.showLastPageButton : true; let showPreviousPageButton = !isNull(pageOptions.showPreviousPageButton) ? pageOptions.showPreviousPageButton : true; let showNextPageButton = !isNull(pageOptions.showNextPageButton) ? pageOptions.showNextPageButton : true; let showPageNumberButtons = !isNull(pageOptions.showPageNumberButtons) ? pageOptions.showPageNumberButtons : true; let showNavigationInput = !isNull(pageOptions.showNavigationInput) ? pageOptions.showNavigationInput : true; let onButtonTitleRender = pageOptions.onButtonTitleRender || settings.onTextRender; let onButtonTextRender = pageOptions.onButtonTextRender || settings.onTextRender; let defaultVisibleButtons = !isUndefined(pageOptions.visiblePageNumberButtons) ? pageOptions.visiblePageNumberButtons : settings.defaultVisibleButtons; if (isNumeric(defaultVisibleButtons) && defaultVisibleButtons < 1) { showPageNumberButtons = false; } // Set the total visible page number buttons setTotalVisiblePageButtons(table, defaultVisibleButtons); // Create the buttons div let navigationButtons = document.createElement('div'); navigationButtons.id = navigationButtonSection.id + '_buttons'; navigationButtonSection.appendChild(navigationButtons); // Set the current table navigation butons id setNavigationButtonsId(table, navigationButtons.id); addClasses(navigationButtons, [settings.classNameNavigationButtonSection]); // Add the first page button if (showFirstPageButton) { attachButton({ container: navigationButtons, classes: [settings.classNameButton, settings.classNameButtonFirst], data: {key: settings.dataNamePageNumber, value: settings.buttonOptionFirst}, text: onButtonTextRender.call(this, '⇠ First', settings.onRenderDescFirstPage), title: onButtonTitleRender.call(this, 'First Page', settings.onRenderDescFirstPage), }); } // Add the previous page button if (showPreviousPageButton) { attachButton({ container: navigationButtons, classes: [settings.classNameButton, settings.classNameButtonPrevious], data: {key: settings.dataNamePageNumber, value: settings.buttonOptionPrevious}, text: onButtonTextRender.call(this, '⮜', settings.onRenderDescPrevPage), title: onButtonTitleRender.call(this, 'Previous Page', settings.onRenderDescPrevPage), }); } // Add the page number buttons if (showPageNumberButtons) { let totalPages = getTotalPages(table); for (let index = 1; index <= totalPages; ++index) { attachButton({ container: navigationButtons, classes: [settings.classNameButton, settings.classNameButtonPageNumber], data: {key: settings.dataNamePageNumber, value: index}, text: onButtonTextRender.call(this, String(index), settings.onRenderDescPageNumber), title: onButtonTitleRender.call(this, 'Page ' + index, settings.onRenderDescPageNumber), }); } } // Add the next page button if (showNextPageButton) { attachButton({ container: navigationButtons, classes: [settings.classNameButton, settings.classNameButtonNext], data: {key: settings.dataNamePageNumber, value: settings.buttonOptionNext}, text: onButtonTextRender.call(this, '⮞', settings.onRenderDescNextPage), title: onButtonTitleRender.call(this, 'Next Page', settings.onRenderDescNextPage), }); } // Add the last page button if (showLastPageButton) { attachButton({ container: navigationButtons, classes: [settings.classNameButton, settings.classNameButtonLast], data: {key: settings.dataNamePageNumber, value: settings.buttonOptionLast}, text: onButtonTextRender.call(this, 'Last ⤑', settings.onRenderDescLastPage), title: onButtonTitleRender.call(this, 'Last Page', settings.onRenderDescLastPage), }); } // Add navigation input if (showNavigationInput) { attachNavigationInput({ table: table, pageOptions: pageOptions, container: navigationButtonSection, classes: [settings.classNameNavigationInputSection] }); } return navigationButtonSection; } let attachNavigationInfo = (options) => { // Create the table navigation info control div let navigationInfo = document.createElement('div'); navigationInfo.id = options.container.id + '_info_section'; options.container.appendChild(navigationInfo); // Add classes and data addClasses(navigationInfo, options.classes); addData(navigationInfo, options.data); // Set the current table navigation info id setNavigationInfoId(options.table, navigationInfo.id); return navigationInfo; } let attachNavigationInput = (options) => { let pageOptions = options.pageOptions; let onButtonTitleRender = pageOptions.onButtonTitleRender || settings.onTextRender; let onButtonTextRender = pageOptions.onButtonTextRender || settings.onTextRender; // Create the table navigation input control div let navigationInputContainer = document.createElement('div'); navigationInputContainer.id = options.container.id + '_input'; options.container.appendChild(navigationInputContainer); // Add classes and data addClasses(navigationInputContainer, options.classes); addData(navigationInputContainer, options.data); // Add the input textbox let navigationGoInput = document.createElement('input'); navigationGoInput.type = 'text'; navigationInputContainer.appendChild(navigationGoInput); // Add input classes addClasses(navigationGoInput, [settings.classNameNavigationInput]); // Add the Go button attachButton({ container: navigationInputContainer, classes: [settings.classNameButton, settings.classNameButtonGo], text: onButtonTextRender.call(this, 'Go', settings.onRenderDescGoInput), title: onButtonTitleRender.call(this, 'Go To Page', settings.onRenderDescGoInput), }); // Set the current table navigation input id setNavigationInputId(options.table, navigationInputContainer.id); return navigationInputContainer; } let addClasses = (element, classes) => { if (isNull(classes)) { return; } else if (!Array.isArray(classes)) { classes = [classes]; } classes.forEach(item => { addClass(element, item); }); } let removeClasses = (element, classes) => { if (isNull(classes)) { return; } else if (!Array.isArray(classes)) { classes = [classes]; } classes.forEach(item => { removeClass(element, item); }); } let addData = (element, data) => { if (isNull(data)) { return; } else if (!Array.isArray(data)) { data = [data]; } data.forEach(item => { if (!isNull(item.value)) { element.setAttribute(item.key, item.value); } else { removeData(element, item); } }); } let removeData = (element, data) => { if (isNull(data)) { return; } else if (!Array.isArray(data)) { data = [data]; } data.forEach(item => { let key = item.key || item; element.removeAttribute(key); }); } let getData = (element, data) => { if (isNull(data)) { return null; } else if (!Array.isArray(data)) { data = [data]; } let results = []; data.forEach(item => { let key = item.key || item; results.push(element.getAttribute(key)); }); return results.length == 1 ? results[0] : results; } let getNextMultiple = (number, multiple, skipAlreadyMultiple = false) => { let retVal = 0; if (multiple !== 0) { let remainder = (number % multiple); if (!skipAlreadyMultiple && remainder === 0) { retVal = number; } else { retVal = number + (multiple - remainder); } } return retVal; } let getPreviousMultiple = (number, multiple, skipAlreadyMultiple = false) => { return getNextMultiple(number, multiple, !skipAlreadyMultiple) - multiple; } // see if it looks and smells like an iterable object, and do accept length === 0 let isArrayLike = (item) => { return ( Array.isArray(item) || (!!item && typeof item === "object" && typeof (item.length) === "number" && (item.length === 0 || (item.length > 0 && (item.length - 1) in item) ) ) ); } (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } }(function() { return namespace; })); }(TablePagination)); // http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101 // ============================================================================//    Author: Kenneth Perkins//    Date:   Aug 5, 2020//    Taken From: http://programmingnotes.org///    File:  TablePagination.js//    Description: Namespace which handles html table pagination//    Example://        // Add Pagination to a table//        TablePagination.page({//            table: document.querySelector('table'), //            rowsPerPage: 10//        });// ============================================================================ /*** NAMESPACE: TablePagination* USE: Handles html table pagination.*/var TablePagination = TablePagination || {};(function(namespace) {    'use strict';       // -- Public data --    // Property to hold public variables and functions    let exposed = namespace;            // Set class names and other shared data    const settings = {        // Misc settings        defaultRowsPerPage: 5,        defaultPosition: 'bottom',        defaultVisibleButtons: 3,        onRenderDescFirstPage: 'first_page',        onRenderDescPrevPage: 'previous_page',        onRenderDescPageNumber: 'page_number',        onRenderDescNextPage: 'next_page',        onRenderDescLastPage: 'last_page',        onRenderDescGoInput: 'go_input',        buttonOptionFirst: 'first',        buttonOptionPrevious: 'previous',        buttonOptionNext: 'next',        buttonOptionLast: 'last',        navigationPositionTop: 'top',        navigationPositionBottom: 'bottom',        onTextRender: (text) => text,                // Element class names        classNameHide: '.pagination-hide',        classNameButton: 'pagination-btn',         classNameButtonActive: 'active',        classNameButtonFirst: 'first',        classNameButtonPrevious: 'previous',        classNameButtonPageNumber: 'page-number',        classNameButtonNext: 'next',        classNameButtonLast: 'last',        classNameButtonGo: 'go',        classNameButtonHide: 'hide',        classNameNavigation: 'pagination-navigation',        classNameNavigationTop: 'top',        classNameNavigationBottom: 'bottom',        classNameNavigationInfoSection: 'pagination-navigation-info-section',        classNameNavigationControlSection: 'pagination-navigation-control-section',        classNameNavigationButtonSection: 'pagination-navigation-button-section',        classNameNavigationInputSection: 'pagination-navigation-input-section',        classNameNavigationInput: 'pagination-navigation-input',                // Element data names        dataNamePageNumber: 'data-pageNumber',        dataNameTotalPages: 'data-totalPages',        dataNameRowsPerPage: 'data-rowsPerPage',        dataNameCurrentPageNumber: 'data-currentPageNumber',        dataNameNavigationId: 'data-navigationId',        dataNameNavigationInfoId: 'data-navigationInfoId',        dataNameNavigationInputId: 'data-navigationInputId',        dataNameNavigationButtonsId: 'data-navigationButtonsId',        dataNameVisiblePageButtons: 'data-visiblePageButtons',        cleanClassName: (str) => {            return str ? str.trim().replace('.', '') : '';        },    };            exposed.settings = settings;                                                                        /**    * FUNCTION: page    * USE: Initializes & renders pagination for the given table elements    * @param options: An object of initialization options.    *   Its made up of the following properties:    *   {    *       table: One or more Javascript elements of the tables to page.    *       rowsPerPage: Optional. The number of rows per page. Default is page 5    *       initialPage: Optional. The initial page to display. Posible values: Numeric value     *          or 'first/last'. Default is page 1    *       navigationPosition: Optional. The navigation position. Posible values: 'top/bottom'.    *          Default is 'bottom'      *       showFirstPageButton: Optional. Boolean that indicates if the first page     *          button should be displayed. Default is true    *       showLastPageButton: Optional. Boolean that indicates if the last page     *          button should be displayed. Default is true    *       showPreviousPageButton: Optional. Boolean that indicates if the previous page     *          button should be displayed. Default is true    *       showNextPageButton: Optional. Boolean that indicates if the next page     *          button should be displayed. Default is true     *       showPageNumberButtons: Optional. Boolean that indicates if the page number buttons     *          should be displayed. Default is true    *       showNavigationInput: Optional. Specifies if the 'Go' search functionality is shown.    *          Default is true      *       showNavigationInfoText: Optional. Specifies if the navigation info text is shown.     *          Default is true    *       visiblePageNumberButtons: Optional. The maximum number of visible page number buttons.     *          Default is 3. Set to null to show all buttons     *       onButtonClick(pageNumber, event): Optional. Function that allows to do something on      *          button click     *       onButtonTextRender(text, desc): Optional. Function that allows to format the button text     *       onButtonTitleRender(title, desc): Optional. Function that allows to format the button title     *       onNavigationInfoTextRender(text, rowInfo): Optional. Function that allows to format      *          the navigation info text     *       navigationBindTo: Optional. Javascript element of the container where the navigation controls        *          are bound to. If not specified, default destination is above or below the table element,     *          depending on the 'navigationPosition' value        *   }    * @return: N/A.    */     exposed.page = (options) => {        // Make sure the required options are valid        if (isNull(options)) {            // Check to see if there are options            throw new TypeError('There are no options specified.');        } else if (typeof options !== 'object' || isElement(options) || isArrayLike(options)) {            // Check to see if a table is specified            let table = options;            options = {};            options.table = table;        }        // Make sure the table is an array        if (!isArrayLike(options.table)) {            options.table = [options.table];        }                       // Make sure additional options are valid        if (!isNull(options.rowsPerPage) && !isNumeric(options.rowsPerPage)) {            // Check to see if a rowsPerPage is valid            throw new TypeError(`Unable to process rowsPerPage of type: \${typeof options.rowsPerPage}. Reason: '\${options.rowsPerPage}' is not a numeric value.`);                      } else if (!isNull(options.navigationBindTo) && !isElement(options.navigationBindTo)) {            // Check to see if the navigation bind to element is an HTMLElement            throw new TypeError(`Unable to process navigationBindTo of type: \${typeof options.navigationBindTo}. Reason: '\${options.navigationBindTo}' is not an HTMLElement.`);                    } else if (!isNull(options.onButtonTitleRender) && !isFunction(options.onButtonTitleRender)) {            // Check to see if callback is a function            throw new TypeError(`Unable to call onButtonTitleRender of type: \${typeof options.onButtonTitleRender}. Reason: '\${options.onButtonTitleRender}' is not a function.`);        } else if (!isNull(options.onButtonTextRender) && !isFunction(options.onButtonTextRender)) {            // Check to see if callback is a function            throw new TypeError(`Unable to call onButtonTextRender of type: \${typeof options.onButtonTextRender}. Reason: '\${options.onButtonTextRender}' is not a function.`);        } else if (!isNull(options.onButtonClick) && !isFunction(options.onButtonClick)) {            // Check to see if callback is a function            throw new TypeError(`Unable to call onButtonClick of type: \${typeof options.onButtonClick}. Reason: '\${options.onButtonClick}' is not a function.`);        } else if (!isNull(options.visiblePageNumberButtons) && !isNumeric(options.visiblePageNumberButtons)) {            // Check to see if a visiblePageNumberButtons is valid            throw new TypeError(`Unable to process visiblePageNumberButtons of type: \${typeof options.visiblePageNumberButtons}. Reason: '\${options.visiblePageNumberButtons}' is not a numeric value.`);                       } else if (!isNull(options.onNavigationInfoTextRender) && !isFunction(options.onNavigationInfoTextRender)) {            // Check to see if callback is a function            throw new TypeError(`Unable to call onNavigationInfoTextRender of type: \${typeof options.onNavigationInfoTextRender}. Reason: '\${options.onNavigationInfoTextRender}' is not a function.`);        }                // Get the tables and remove the property from the object        let tables = options.table;        delete options.table;                // Page the tables        for (let index = 0; index < tables.length; ++index) {            // Get the table and make sure its valid            let table = tables[index];            if (!isTable(table)) {                // Check to see if the table is an HTMLTableElement                throw new TypeError(`Unable to process \${getTableDisplayName(table)} of type: \${typeof table}. Reason: '\${table}' is not an HTMLTableElement.`);            }                    // Build the table navigation controls            buildNavigation(table, options)                        // Add click events for the navigation controls            addClickEvents(table, options);                        // Show the initial page            showPage(table, {pageNumber: getInitialPage(table, options.initialPage), pageOptions: options});                    }    }        /**    * FUNCTION: remove    * USE: Removes the rendered table pagination    * @param table: JavaScript elements of the paged tables.    * @return: True if table pagination controls were removed from all tables, false otherwise.    */      exposed.remove = (tables) => {        if (isNull(tables)) {            return false;        } else if (!isArrayLike(tables)) {            tables = [tables];        }        let allRemoved = true;        for (let index = 0; index < tables.length; ++index) {            let table = tables[index];                      if (!isTable(table)) {                // Check to see if the table is an HTMLTableElement                throw new TypeError(`Unable to process \${getTableDisplayName(table)} of type: \${typeof table}. Reason: '\${table}' is not an HTMLTableElement.`);            }            if (!removeNavigation(table)) {                allRemoved = false;            }        }               return allRemoved;    }    // -- Private data --      let getRows = (table) => {        let rows = table.rows;        let results = [];        // Only return data rows        for (let indexRow = 0; indexRow < rows.length; ++indexRow) {            let row = rows[indexRow];            let isTDRow = true;             for (let indexCell = 0; indexCell < row.cells.length; ++indexCell) {                let cell = row.cells[indexCell];                                if (cell.tagName.toLowerCase() !== 'td') {                    isTDRow = false;                    break;                }            }            if (isTDRow) {                results.push(row);            }        }        return results;    }     let buildNavigation = (table, options) => {        // Remove the previous navigation        removeNavigation(table);                // Set the max rows per page        let rowsPerPage = options.rowsPerPage || settings.defaultRowsPerPage;        setRowsPerPage(table, rowsPerPage);                     // Calculate the number of pages needed and set its value        let totalPages = calculateTotalPagesRequired(table);        setTotalPages(table, totalPages);        if (totalPages < 1) {            throw new Error(`\${totalPages} pages calculated in order to page the table. Exiting...`);        }                // Get the current options         let position = (options.navigationPosition || settings.defaultPosition).trim().toLowerCase();        let showNavigationInfoText = !isNull(options.showNavigationInfoText) ? options.showNavigationInfoText : true;        let navigationBindTo = options.navigationBindTo || table.parentNode;        let isCustomBinding = !isNull(options.navigationBindTo);            // Add the navigation controls to the page        let navigationContainer = attachNavigation({            table: table,             container: navigationBindTo,             isCustomBinding: isCustomBinding,            position: position,            classes: getNavigationClasses(position),            data: [{key: 'tabindex', value: 0}]        });                 // Show page info        if (showNavigationInfoText) {            attachNavigationInfo({                table: table,                 container: navigationContainer,                classes: [settings.classNameNavigationInfoSection]            });        }                       // Add navigation buttons        attatchNavigationButtons({            table: table,            pageOptions: options,            container: navigationContainer,                     classes: [settings.classNameNavigationControlSection]        });     }        let addClickEvents = (table, options) => {        let paginationButtons = getNavigationButtons(table);        let inputButton = getInputButton(table);        let inputTextbox = getInputTextbox(table);        let navigation = document.querySelector(`#\${getNavigationId(table)}`);                // Make sure there are visible navigation buttons        let navigationVisible = (!isNull(paginationButtons) && paginationButtons.length > 0)             || (!isNull(inputButton) && !isNull(inputTextbox));                // Throw an error if there are no visible navigation buttons        if (!navigationVisible) {             throw new Error(`The settings chosen on \${getTableDisplayName(table)} do not allow for any visible navigation buttons!`);        }        // Function to go to a page        let navigateToPage = (pageNumber, event) => {             pageNumber = translatePageNumber(table, pageNumber);            if (!isNumeric(pageNumber)) {                return false;            }            // Show the page            showPage(table, {pageNumber: pageNumber, pageOptions: options});                        // Call the on click function if specified            if (options.onButtonClick) {                options.onButtonClick.call(this, pageNumber, event);            }            return true;        }        // Add click events for the navigation buttons        if (!isNull(paginationButtons)) {            paginationButtons.forEach((paginationButton, index) => {                // Add button click                paginationButton.addEventListener('click', (event) => {                    event.preventDefault();                                 let pageNumber = getButtonPageNumber(paginationButton);                    navigateToPage(pageNumber, event);                    navigation.focus({preventScroll:true});                });            });        }        // Add click event for the input button        if (!isNull(inputButton)) {            inputButton.addEventListener('click', (event) => {                event.preventDefault();                // Get the input textbox                let pageNumber = getInputValue(table, inputTextbox);                navigateToPage(pageNumber, event);            });        }        // Add click event for the input textbox        if (!isNull(inputTextbox)) {            inputTextbox.addEventListener('keyup', (event) => {                event = event || window.event;                 let keyCode = event.key || event.keyCode;                // Check to see if the enter button was clicked                switch (String(keyCode)) {                    case 'Enter': case '13':                        inputButton.click();                        break;                }            });                 }        // Add click events for the left/right keyboard buttons        if (!isNull(navigation)) {            navigation.addEventListener('keydown', (event) => {                event = event || window.event;                 let keyCode = event.key || event.keyCode;                let pageNumber = getCurrentPageNumber(table);                               // Check to see if an arrow key was clicked                switch (String(keyCode)) {                    case 'ArrowLeft': case 'Left': case '37':                        --pageNumber;                        break;                    case 'ArrowRight': case 'Right': case '39':                        ++pageNumber;                        break;                    default:                        return;                        break;                }                navigateToPage(pageNumber, event);                          });                 }    }        let getTableId = (table) => {        let tableId = !isNull(table.id) && table.id.length > 0 ? table.id : null;        return tableId;    }        let getTableDisplayName = (table) => {        let tableId = getTableId(table);        let tableName = 'Table' + (tableId ? ' id: "' + tableId + '"' : '');        return tableName;    }           let getInitialPage = (table, initialPage) => {        let initialActivePage = 1;        if (!isNull(initialPage)) {            let possiblePageNumber = translatePageNumber(table, initialPage);            if (isNumeric(possiblePageNumber)) {                initialActivePage = possiblePageNumber;            }        }        return initialActivePage;    }        let translatePageNumber = (table, pageNumber) => {        if (!isNull(pageNumber) && !isNumeric(pageNumber)) {             pageNumber = String(pageNumber).trim().toLowerCase();            switch (pageNumber) {                case settings.buttonOptionFirst.trim().toLowerCase():                    pageNumber = 1;                    break;                case settings.buttonOptionLast.trim().toLowerCase():                    pageNumber = getTotalPages(table);                      break;                case settings.buttonOptionPrevious.trim().toLowerCase():                    pageNumber = getCurrentPageNumber(table) - 1;                       break;                case settings.buttonOptionNext.trim().toLowerCase():                    pageNumber = getCurrentPageNumber(table) + 1;                     break;                              }        }        return pageNumber;    }        let getNavigationClasses = (position) => {        let navigationClasses = []        navigationClasses.push(settings.classNameNavigation);        if (position == settings.navigationPositionTop.trim().toLowerCase()) {             navigationClasses.push(settings.classNameNavigationTop);        } else {             navigationClasses.push(settings.classNameNavigationBottom);        }           return navigationClasses;    }           let hideAllRows = (table) => {         let totalPages = getTotalPages(table);        for (let pageNumber = 1; pageNumber <= totalPages; ++pageNumber) {            hidePage(table, {pageNumber: pageNumber});        }    }     let hidePage = (table, options) => {          let pageNumber = options.pageNumber;        let rowInfo = getRowInfo(table, pageNumber);        let rowIndexStart = rowInfo.rowIndexStart;        let rowIndexEnd = rowInfo.rowIndexEnd;              hideRows(table, rowIndexStart, rowIndexEnd);    }     let hideRows = (table, rowIndexStart, rowIndexEnd) => {         let tableRows = getRows(table);        for (let index = rowIndexStart; index <= rowIndexEnd && index < tableRows.length; ++index) {            let tableRow = tableRows[index];            hideRow(tableRow);        }    }     let hideRow = (tableRow) => {         addClass(tableRow, settings.classNameHide);     }     let showAllRows = (table) => {         let totalPages = getTotalPages(table);        for (let pageNumber = 1; pageNumber <= totalPages; ++pageNumber) {            showPage(table, {                pageNumber: pageNumber,                hidePreviousRows: false            });        }    }     let showPage = (table, options) => {         if (isNull(options.hidePreviousRows) || options.hidePreviousRows) {            hideAllRows(table);        }                 let rowInfo = getRowInfo(table, options.pageNumber);        let rowIndexStart = rowInfo.rowIndexStart;        let rowIndexEnd = rowInfo.rowIndexEnd;        let pageNumber = rowInfo.pageNumber;         showRows(table, rowIndexStart, rowIndexEnd);        setCurrentPageNumber(table, pageNumber);        highlightButton(table, pageNumber);                showPageButtons(table, pageNumber);        updateInfoText(table, rowInfo, options.pageOptions);        clearInputValue(table);    }        let showRows = (table, rowIndexStart, rowIndexEnd) => {         let tableRows = getRows(table);        for (let index = rowIndexStart; index <= rowIndexEnd && index < tableRows.length; ++index) {            let tableRow = tableRows[index];            showRow(tableRow);        }    }     let showRow = (tableRow) => {         removeClass(tableRow, settings.classNameHide);    }        let clearInputValue = (table, inputTextbox = null) => {        inputTextbox = inputTextbox || getInputTextbox(table);        if (!isNull(inputTextbox)) {            inputTextbox.value = null;        }    }        let getInputValue = (table, inputTextbox = null) => {        inputTextbox = inputTextbox || getInputTextbox(table);        return !isNull(inputTextbox) ? inputTextbox.value : null;    }        let updateInfoText = (table, rowInfo, pageOptions) => {        let navigationInfo = getNavigationInfo(table);        if (isNull(navigationInfo)) {            return;        }        let text = `Showing \${rowInfo.itemCountStart} to \${rowInfo.itemCountEnd} of \${rowInfo.totalItems} entries.`;        text += `<br />`;        text += `Page \${rowInfo.pageNumber} of \${rowInfo.totalPages}`;        let onNavigationInfoTextRender = settings.onTextRender;        if (!isNull(pageOptions) && !isNull(pageOptions.onNavigationInfoTextRender)) {            onNavigationInfoTextRender = pageOptions.onNavigationInfoTextRender;        }        navigationInfo.innerHTML = onNavigationInfoTextRender.call(this, text, rowInfo);    }           let showPageButtons = (table, pageNumber) => {         let visibleButtons = getTotalVisiblePageButtons(table);        if (!isNumeric(visibleButtons)) {            return;        }               let totalPages = getTotalPages(table);        let firstVisiblePage = Math.max(0, getPreviousMultiple(pageNumber, visibleButtons)) + 1;        let lastVisiblePage = Math.min(totalPages, getNextMultiple(pageNumber, visibleButtons));                     // Make sure there are at least 'visibleButtons' total buttons shown         let difference = (visibleButtons - 1) - (lastVisiblePage - firstVisiblePage);         if (difference > 0) {                       firstVisiblePage -= difference;        }                getNavigationButtons(table).forEach((btn, index) => {             let buttonPageNumber = getButtonPageNumber(btn);            if (isNumeric(buttonPageNumber)) {                buttonPageNumber = Number(buttonPageNumber);                addClass(btn, settings.classNameButtonHide);                if (buttonPageNumber >= firstVisiblePage && buttonPageNumber <= lastVisiblePage) {                    removeClass(btn, settings.classNameButtonHide);                }            }        });     }     let getRowInfo = (table, pageNumber) => {        let totalPages = getTotalPages(table);        let rows = getRows(table);                // Make sure the page number is within valid range [1 to last page number]        pageNumber = Math.max(1, Math.min(pageNumber, totalPages));                let totalItems = rows.length;        let rowsPerPage = getRowsPerPage(table);        let rowIndexStart = (pageNumber - 1) * rowsPerPage;        let rowIndexEnd = Math.min(rowIndexStart + (rowsPerPage - 1), totalItems - 1);        let rowInfo = {            rowIndexStart: rowIndexStart,            rowIndexEnd: rowIndexEnd,            pageNumber: pageNumber,            totalPages: totalPages,            totalItems: totalItems,            rowsPerPage: rowsPerPage,            itemCountStart: rowIndexStart + 1,            itemCountEnd: rowIndexEnd + 1,                  };        return rowInfo;    }        let getCurrentPageNumber = (table) => {        let pageNumber = getData(table, settings.dataNameCurrentPageNumber);        return isNull(pageNumber) ? 0 : Number(pageNumber);    }     let setCurrentPageNumber = (table, pageNumber) => {         addData(table, {key: settings.dataNameCurrentPageNumber, value: pageNumber});           }        let highlightButton = (table, pageNumber) => {        let paginationButton = null;        let paginationButtons = getNavigationButtons(table);        if (isNull(paginationButtons)) {            return;        }        // Reset the previous page button colors         resetButtonColors(paginationButtons);                // Mark the selected button as active        paginationButtons.forEach((btn, index) => {             let buttonPageNumber = getButtonPageNumber(btn);            if (isNumeric(buttonPageNumber)                 && Number(pageNumber) === Number(buttonPageNumber)) {                paginationButton = btn;                return false;            }        });        if (!isNull(paginationButton)) {            addClass(paginationButton, settings.classNameButtonActive);        }           }        let resetButtonColors = (paginationButtons) => {         if (isNull(paginationButtons)) {            return;        }        paginationButtons.forEach((paginationButton, index) => {             let buttonPageNumber = getButtonPageNumber(paginationButton);            if (isNumeric(buttonPageNumber)) {                removeClass(paginationButton, settings.classNameButtonActive);            }        });     }           let getButtonPageNumber = (btn) => {        let pageNumber = getData(btn, settings.dataNamePageNumber);        return String(!isNull(pageNumber) ? pageNumber : 0);    }        let setNavigationId = (table, navigationId) => {        addData(table, {key: settings.dataNameNavigationId, value: navigationId});          }        let getNavigationId = (table) => {        return getData(table, settings.dataNameNavigationId);    }     let setNavigationInfoId = (table, navigationInfoId) => {        addData(table, {key: settings.dataNameNavigationInfoId, value: navigationInfoId});          }        let getNavigationInfoId = (table) => {        return getData(table, settings.dataNameNavigationInfoId);    }        let setNavigationInputId = (table, navigationInputId) => {        addData(table, {key: settings.dataNameNavigationInputId, value: navigationInputId});            }        let getNavigationInputId = (table) => {        return getData(table, settings.dataNameNavigationInputId);    }           let getNavigationButtons = (table) => {        let selector = `#\${getNavigationButtonsId(table)} a`;        return document.querySelectorAll(selector);    }           let getInputButton = (table) => {        let selector = `#\${getNavigationInputId(table)} a`;        return document.querySelector(selector);    }           let getInputTextbox = (table) => {        let selector = `#\${getNavigationInputId(table)} input`;        return document.querySelector(selector);    }        let getNavigationInfo = (table) => {        let selector = `#\${getNavigationInfoId(table)}`;        return document.querySelector(selector);    }        let setNavigationButtonsId = (table, navigationButtonsId) => {        addData(table, {key: settings.dataNameNavigationButtonsId, value: navigationButtonsId});            }        let getNavigationButtonsId = (table) => {        return getData(table, settings.dataNameNavigationButtonsId);    }        let getTotalVisiblePageButtons = (table) => {        let value = getData(table, settings.dataNameVisiblePageButtons);        return !isNull(value) ? Number(value) : value;    }     let setTotalVisiblePageButtons = (table, visiblePageButtons) => {        addData(table, {key: settings.dataNameVisiblePageButtons, value: visiblePageButtons});          }           let setRowsPerPage = (table, rowsPerPage) => {         addData(table, {key: settings.dataNameRowsPerPage, value: rowsPerPage});    }        let getRowsPerPage = (table) => {        let value = getData(table, settings.dataNameRowsPerPage);        return !isNull(value) ? Number(value) : value;    }     let setTotalPages = (table, totalPages) => {         addData(table, {key: settings.dataNameTotalPages, value: totalPages});          }               let getTotalPages = (table) => {        let value = getData(table, settings.dataNameTotalPages);        return !isNull(value) ? Number(value) : value;    }        let calculateTotalPagesRequired = (table) => {        let rowsPerPage = getRowsPerPage(table);        let totalRows = getRows(table).length;        let totalPages = totalRows / rowsPerPage;        if (totalRows % rowsPerPage !== 0) {            totalPages = Math.floor(++totalPages);        }        return totalPages;          }           let addClass = (element, cssClass) => {        cssClass = settings.cleanClassName(cssClass);         let modified = false;        if (cssClass.length > 0 && !hasClass(element, cssClass)) {            element.classList.add(cssClass)            modified = true;        }        return modified;    }     let removeClass = (element, cssClass) => {        cssClass = settings.cleanClassName(cssClass);         let modified = false;        if (cssClass.length > 0 && hasClass(element, cssClass)) {            element.classList.remove(cssClass);            modified = true;        }        return modified;    }     let hasClass = (element, cssClass) => {        cssClass = settings.cleanClassName(cssClass);        return element.classList.contains(cssClass);    }     let isNull = (item) => {        return isUndefined(item) || null === item;    }      let isUndefined = (item) => {        return undefined === item;    }         let isFunction = (item) => {        return 'function' === typeof item    }           let isTable = (item) => {        return isElement(item) && item instanceof HTMLTableElement;    }        let isElement = (item) => {        let value = false;        try {             value = item instanceof HTMLElement || item instanceof HTMLDocument;        }        catch (e) {            value = (typeof item==="object") &&                 (item.nodeType===1) && (typeof item.style === "object") &&                (typeof item.ownerDocument ==="object");        }        return value;    }           let randomFromTo = (from, to) => {        return Math.floor(Math.random() * (to - from + 1) + from);    }        let isNumeric = (n) => {        return !isNaN(parseFloat(n)) && isFinite(n);    }        let generateNavigationId = (table) => {        let tableId = getTableId(table);        return 'tablePaginationNavigation_' + (tableId ? tableId : randomFromTo(1271991, 7281987));    }        let removeNavigation = (table) => {        let modified = false;        let previousNavigationId = getNavigationId(table);                // Remove the previous table navigation         if (!isNull(previousNavigationId)) {            let previousElement = document.querySelector(`#\${previousNavigationId}`);            if (!isNull(previousElement)) {                             previousElement.parentNode.removeChild(previousElement);                showAllRows(table);                modified = true;            }        }        return modified;    }        let attachNavigation = (options) => {        // Create the table navigation control div        let navigationContainer = document.createElement('div');        navigationContainer.id = generateNavigationId(options.table);                // Determine the navigation position        let position = options.position.trim().toLowerCase();        if (!options.isCustomBinding) {            if (position === settings.navigationPositionTop) {                // Insert navigation before the table                options.container.insertBefore(navigationContainer, options.table);                     } else {                // Insert navigation after the table                options.container.insertBefore(navigationContainer, options.table.nextSibling);                     }        } else {            if (position === settings.navigationPositionTop) {                // Insert navigation at the beginning of the container                options.container.insertBefore(navigationContainer, options.container.firstChild);            } else {                // Insert navigation ar end of the container                options.container.insertBefore(navigationContainer, options.container.lastChild);                       }        }        // Add classes and data        addClasses(navigationContainer, options.classes);        addData(navigationContainer, options.data);                // Set the current table navigation control id        setNavigationId(options.table, navigationContainer.id);        setNavigationInfoId(options.table, null);                return navigationContainer;    }        let attachButton = (options) => {        let btn = document.createElement('a');        btn.href = '#';                addClasses(btn, options.classes);        addData(btn, options.data);                btn.insertAdjacentHTML('beforeend', options.text);        btn.title = options.title;        options.container.appendChild(btn);        return btn;    }        let attatchNavigationButtons = (options) => {        let pageOptions = options.pageOptions;        let table = options.table;                // Create the table navigation info control div        let navigationButtonSection = document.createElement('div');        navigationButtonSection.id = options.container.id + '_control_section';        options.container.appendChild(navigationButtonSection);                    // Add classes and data        addClasses(navigationButtonSection, options.classes);        addData(navigationButtonSection, options.data);                        let showFirstPageButton = !isNull(pageOptions.showFirstPageButton) ? pageOptions.showFirstPageButton : true;        let showLastPageButton = !isNull(pageOptions.showLastPageButton) ? pageOptions.showLastPageButton : true;        let showPreviousPageButton = !isNull(pageOptions.showPreviousPageButton) ? pageOptions.showPreviousPageButton : true;        let showNextPageButton = !isNull(pageOptions.showNextPageButton) ? pageOptions.showNextPageButton : true;        let showPageNumberButtons = !isNull(pageOptions.showPageNumberButtons) ? pageOptions.showPageNumberButtons : true;        let showNavigationInput = !isNull(pageOptions.showNavigationInput) ? pageOptions.showNavigationInput : true;                let onButtonTitleRender = pageOptions.onButtonTitleRender || settings.onTextRender;         let onButtonTextRender = pageOptions.onButtonTextRender || settings.onTextRender;         let defaultVisibleButtons = !isUndefined(pageOptions.visiblePageNumberButtons) ? pageOptions.visiblePageNumberButtons : settings.defaultVisibleButtons;        if (isNumeric(defaultVisibleButtons) && defaultVisibleButtons < 1) {            showPageNumberButtons = false;        }                // Set the total visible page number buttons        setTotalVisiblePageButtons(table, defaultVisibleButtons);                // Create the buttons div        let navigationButtons = document.createElement('div');        navigationButtons.id = navigationButtonSection.id + '_buttons';        navigationButtonSection.appendChild(navigationButtons);         // Set the current table navigation butons id         setNavigationButtonsId(table, navigationButtons.id);                addClasses(navigationButtons, [settings.classNameNavigationButtonSection]);                // Add the first page button        if (showFirstPageButton) {             attachButton({                container: navigationButtons,                classes: [settings.classNameButton, settings.classNameButtonFirst],                data: {key: settings.dataNamePageNumber, value: settings.buttonOptionFirst},                text: onButtonTextRender.call(this, '⇠ First', settings.onRenderDescFirstPage),                title: onButtonTitleRender.call(this, 'First Page', settings.onRenderDescFirstPage),            });        }        // Add the previous page button        if (showPreviousPageButton) {             attachButton({                container: navigationButtons,                classes: [settings.classNameButton, settings.classNameButtonPrevious],                data: {key: settings.dataNamePageNumber, value: settings.buttonOptionPrevious},                text: onButtonTextRender.call(this, '⮜', settings.onRenderDescPrevPage),                title: onButtonTitleRender.call(this, 'Previous Page', settings.onRenderDescPrevPage),            });                 }           // Add the page number buttons        if (showPageNumberButtons) {            let totalPages = getTotalPages(table);            for (let index = 1; index <= totalPages; ++index) {                attachButton({                    container: navigationButtons,                    classes: [settings.classNameButton, settings.classNameButtonPageNumber],                    data: {key: settings.dataNamePageNumber, value: index},                    text: onButtonTextRender.call(this, String(index), settings.onRenderDescPageNumber),                    title: onButtonTitleRender.call(this, 'Page ' + index, settings.onRenderDescPageNumber),                });            }                   }           // Add the next page button        if (showNextPageButton) {            attachButton({                container: navigationButtons,                classes: [settings.classNameButton, settings.classNameButtonNext],                data: {key: settings.dataNamePageNumber, value: settings.buttonOptionNext},                text: onButtonTextRender.call(this, '⮞', settings.onRenderDescNextPage),                title: onButtonTitleRender.call(this, 'Next Page', settings.onRenderDescNextPage),            });        }        // Add the last page button        if (showLastPageButton) {            attachButton({                container: navigationButtons,                classes: [settings.classNameButton, settings.classNameButtonLast],                data: {key: settings.dataNamePageNumber, value: settings.buttonOptionLast},                text: onButtonTextRender.call(this, 'Last ⤑', settings.onRenderDescLastPage),                title: onButtonTitleRender.call(this, 'Last Page', settings.onRenderDescLastPage),            });                 }           // Add navigation input        if (showNavigationInput) {            attachNavigationInput({                table: table,                 pageOptions: pageOptions,                container: navigationButtonSection,                classes: [settings.classNameNavigationInputSection]            });                     }                   return navigationButtonSection;    }           let attachNavigationInfo = (options) => {        // Create the table navigation info control div        let navigationInfo = document.createElement('div');                navigationInfo.id = options.container.id + '_info_section';        options.container.appendChild(navigationInfo);                    // Add classes and data        addClasses(navigationInfo, options.classes);        addData(navigationInfo, options.data)```