The error message "showCurrentPage is not defined" was thrown because the function was not found when the HTML button

Struggling with this one...

I'm facing an issue with a function that displays pagination buttons for each page of results in my todo app.

For example, clicking on button 2 should show page 2 of the results. Here's the function inserting the buttons using template literals:

// CREATE BUTTONS FOR EACH PAGE THAT EXISTS
function displayNumberedButtons(bookMarksArray) {
    for (let x = 0; x < bookMarksArray.length; x++)
        listArray.push(x);

    numberOfPages = Math.ceil(listArray.length / numberPerPage);

    let individualPagesArray = [];
    for (var i = 1; i <= numberOfPages; i++) {
        individualPagesArray.push(i);
    }

    // BUTTONS ARE ADDED HERE
    for (var i = 0; i < individualPagesArray.length; i++) {
        document.getElementById("numbers").innerHTML += `<button onclick=showCurrentPage(${i+1})>` + individualPagesArray[i] + `</button>`;
    }
}

But it seems like my onclick function is not being recognized by my JavaScript:

// PAGINGATION CTAS
window.showCurrentPage = (i) => {
    currentPage = i;
    paginationCountLogic(bookMarksArray);
}

Whenever I click on any button, I get this error message, even though the buttons are visible in the DOM:

index.html:1 Uncaught ReferenceError: showCurrentPage is not defined at HTMLButtonElement.onclick (index.html:1)

This issue only arises when I compile my JS files in advanced mode using the Google Closure Compiler. It works fine if the files are not compiled.

Need help resolving this.

Here's the way the code appears in my script:

function Pagination() {
    let listArray         = new Array(); 
    let pageList          = new Array();  
    const numberPerPage   = 3;
    let currentPage       = 1;  
    let numberOfPages     = 1;   
    const list            = document.querySelector('.url-list');
    let nextButton        = document.getElementById("next");
    const previousButton  = document.getElementById("previous");

    let bookMarksArray = window.localStorage.getItem('bookMarksArray') ? JSON.parse(window.localStorage.getItem('bookMarksArray')) : [];

    // CREATE BUTTONS FOR EACH PAGE THAT EXISTS
    function displayNumberedButtons(bookMarksArray) {
        for (let x = 0; x < bookMarksArray.length; x++)
            listArray.push(x);

        numberOfPages = Math.ceil(listArray.length / numberPerPage);

        let individualPagesArray = [];
        for (var i = 1; i <= numberOfPages; i++) {
            individualPagesArray.push(i);
        }

        for (var i = 0; i < individualPagesArray.length; i++) {
            document.getElementById("numbers").innerHTML += `<button id="${i+1}" onclick=showCurrentPage(${i+1})>` + individualPagesArray[i] + `</button>`;
        }
    }

    // CALCULATE WHEN PAGINATION SHOULD BEGIN AND STOP
    function paginationCountLogic(bookMarksArray) {
        let begin = ((currentPage - 1) * numberPerPage);
        let end = begin + numberPerPage;
        pageList = bookMarksArray.slice(begin, end);

        nextButton.disabled = currentPage === numberOfPages ? true : false;
        previousButton.disabled = currentPage === 1 ? true : false;
        displayBookmarks(pageList);
    }

    // DISPLAY BOOKMARKS
    function displayBookmarks(pageList) {
        list.innerHTML = "";
        for (let r = 0; r < pageList.length; r++) {
            list.innerHTML +=
            `<div>
                <form class="text animated slideInDown bookmarksForm" id=${pageList[r].name}>
                    <input class="nameItem" type="text" name="name" value=${pageList[r].name} id="name" placeholder="Name">
                    <input class="urlItem" type="url" name="url" value=${pageList[r].url} id="url" placeholder="https://example.com">
                    <button type="button" class="js-edit-url" id="edit">edit</button>
                    <button type="button" class="js-delete-url" id="delete">delete</button>
                </form>
            </div>`;
        }
    }

    // PAGINGATION CTAS
    window.showCurrentPage = (i) => {
        currentPage = i;
        paginationCountLogic(bookMarksArray);
    }

    window.nextPage = () => {
        currentPage += 1;
        paginationCountLogic(bookMarksArray);
    }

    window.previousPage = () => {
        currentPage -= 1;
        paginationCountLogic(bookMarksArray);
    }

    return {
      displayNumberedButtons,
      displayBookmarks,
      paginationCountLogic
    };
}

Answer №1

The issue may lie in the fact that the compiler is unable to recognize the function being invoked. As part of the advanced compilation process, unused code is eliminated and methods/variables are renamed.

It appears that within your js or html file, the function is not actually called because the function call is solely defined within a string value here:

for (var i = 0; i < individualPagesArray.length; i++) {
   document.getElementById("numbers").innerHTML += `<button onclick=showCurrentPage(${i+1})>` + individualPagesArray[i] + `</button>`;
}

You can easily resolve this by modifying the code as follows:

window['showCurrentPage'] = (i) => {

Refer to: https://developers.google.com/closure/compiler/docs/api-tutorial3#removal

Similar questions

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

When the web driver fails to function as expected

After installing the selenium-webdriver via npm, I downloaded the IE component from this link and added it to my path on Windows 8. Upon opening IE, I had to set all security zones to high, ensuring they were consistent. However, due to restrictions in th ...

What could be causing the absence of req.body data in a specific route in my Node JS application?

Hello, I am encountering an issue with my Node JS application: When attempting to authenticate, I am receiving an "undefined" value for "req.body.username" upon sending a POST request to that specific route. This problem seems to only occur on this parti ...

Tips for storing a JSON file with GridFS

In my possession is an extensive dataset. Utilizing mongoose schemas, each data element has a structure resembling the following: { field1: “>HWI-ST700660_96:2:1101:1455:2154#5@0/1”: field2: “GAA…..GAATG” } Reference: Re ...

All Material UI components are aligned in a single row, spanning the entire width of the page

These are the components I am currently working with: Sandbox: https://codesandbox.io/s/6ipdf?file=/demo.js:78-129 <FormControl sx={{ m: 1 }} variant="standard"> <InputLabel htmlFor="demo-customized-textbox">Age& ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

Retrieving raw PCM data from webAudio / mozAudio APIs

I have been exploring ways to store the output from the webAudio API for future reference. It seems that capturing PCM data and saving it as a file might meet my needs. I am curious to know if the webAudio or mozAudio APIs have built-in functionality for ...

Ordering dates by week in AngularJS 1

Currently, I have a list of objects: [{ name: one, date: 2017-09-18 }, { name: two, date: 2017-09-11 }, { name: three, date: 2017-09-13 }] I am looking to organize this list by week. Perhaps like the following structure: { 1week(or , m ...

UI thread was blocked due to withProgress being invoked from an external library function

Currently enhancing an extension that is almost finished, but facing a challenge in adding visual cues for lengthy operations. Initially suspected a missing async/await in the code, but struggling to identify the cause. The progress indicator isn't di ...

Parameter within onClick function that includes a dot

I'm attempting to design a table that enables an onClick function for the Change Password column's items so my system administrator can adjust everyone's password. Each onClick triggers the "ChangePassOpen" function which opens a modal with ...

Utilize JavaScript to communicate with the backend server

I'm embarking on my first Cordova application, utilizing HTML, CSS, and JavaScript. My current objective is to trigger a local server call upon button click, with the intention of logging something to confirm functionality. However, I'm encounter ...

Having trouble with the search function in my array, as it is consistently returning false instead of the expected result

Aim: I am working on creating a basic search bar that allows users to input a zip code and matches it with zip codes stored in an array. The objective is to develop a function that can determine whether the entered zip code exists in the array or not, and ...

Using Bootstrap4 to merge rows into a single column or apply rowspan in Bootstrap

Hey there, I have a specific requirement that I need help with. Check out the image here. I want to enable the LCM information box when the LCM checkbox is checked. Below is my code: <div class="panel-body "> <div class="c ...

What is the best way to delete a jQuery.bind event handler that has been created for an event

I have a div and I need to assign two scroll functions to it, but I also want to remove one of them after a certain condition is met. <div id="div1" class="mydivs"> something </div> <div id="div2">Some crap here</div> <script&g ...

Utilizing JavaScript for manipulating arrays and displaying images

After asking this question previously without a satisfactory solution, I am hoping to provide better clarification. Imagine having an array with 3 items and it lands on 0 - a code is set up to display this in a div. Now, I want the image to be shown righ ...

challenges surrounding the use of getElementByTagName

Within my webpage, I have implemented two select elements, both containing multiple options. However, I am facing an issue where I can only access the options from the first select box using getElementByTagName("options"), and unable to retrieve the option ...

"Despite being higher in position, the z-index is causing the element to be placed below

I am currently facing an issue with a dropdown menu that I am trying to add to a WordPress site using Visual Composer. The problem arises when I attempt to place the dropdown on top of a parallax section below it. Despite setting the z-index of the paralla ...

Is there a way to refresh a different webpage within the current session?

In the world of Asp.Net 4, there is a form waiting to be filled with numeric data by the customer. However, this task can sometimes prove tricky as customers may struggle to calculate and input the total figure for each of the four fields. An innovative s ...

Is there a way to initiate LiveServer or npm run dev/start over my local network?

Is it possible to access my project (npm run dev/liveServer) over my home internet network so that my iPad, phone, or iMac could also view the project live as it's being developed (all connected to the same wireless network) without the need to deploy ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

Using JavaScript to load the contents of a JSON file

I attempted to display data from a JSON file on an HTML page using jQuery / Javascript. However, each time I load the page, it remains blank. Below is the code snippet: index.html <!DOCTYPE html> <html> <head> <meta conten ...