JavaScript: The functionality of calling functions through buttons ceases to function once the page is updated without reloading

I am trying to create a program that consists of one HTML page, where I can dynamically update and populate it with different elements using JavaScript. The main feature of the program is a button that remains constant in every version and displays a modal box when clicked. My initial implementation includes a simple setup with two navigation buttons (next and last) for moving through the pages, as well as a button to trigger the modal display. Additionally, there is a counter that increments or decrements based on the page version.

var counter = 1;

function setUp(){
    var container = document.getElementById("container");
    var mainDiv = document.createElement("div");
    mainDiv.setAttribute("id", "main");
    mainDiv.innerHTML = counter;

    var nextBtn = document.createElement("button");
    var backBtn = document.createElement("button");
    var modalBtn = document.createElement("button");

    nextBtn.innerText = ">";
    backBtn.innerText = "<";
    modalBtn.innerText = "Show Modal";

    nextBtn.setAttribute("onclick", "nextPage()");
    backBtn.setAttribute("onclick", "lastPage()");
    modalBtn.setAttribute("onclick", "showModal()");

    mainDiv.appendChild(backBtn);
    container.appendChild(mainDiv);
    mainDiv.appendChild(nextBtn);
    mainDiv.appendChild(modalBtn);
}
function showModal(){
    var modal = document.getElementById("modal");
    modal.style.display = "block";
}
function closeModal(){
    var modal = document.getElementById("modal");
    modal.style.display = "none";
}
function nextPage(){
    var container = document.getElementById("container");
    container.innerHTML = "";
    counter++;
    setUp();
}
function lastPage(){
    var container = document.getElementById("container");
    container.innerHTML = "";
    counter--;
    setUp();
}

setUp();
*{
    padding: 0;
    margin: 0;
}
#modal{
    position: absolute;
    width: 500px;
    height: 300px;
    background-color: black;
    display: none;
}
#main{
    background-color: aliceblue;
    height: 500px;
    width: 800px;
}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="tryout.css">
    <script src="tryout.js" defer></script>
    <title>Document</title>
</head>
<body>
    <div id="container">
        <div id="modal"><button id="closeButton" onclick="closeModal()">Close</button></div>
    </div>
</body>
</html>

Answer №1

When using the "nextPage" and "lastPage" functions, the entire content (including the modal) is being removed from the div associated with the container class. This results in the absence of an element with the modal id in the DOM when calling the "showModal" function, leading to a null reference error.

To address this issue, you can either follow Sakil's suggestion in the comments or modify both the nextPage and lastPage functions to remove the div with the main id and then add it back in the "setUp" function. Below is a code snippet illustrating this:

function nextPage() {

    // Grab the div with the "main" id
    let main = document.getElementById("main");

    // Remove it from the document
    main.remove();

    counter++;

    // Add it again; essentially resetting it up
    setUp();
}

function lastPage() {
    
    // Grab the div with the "main" id
    let main = document.getElementById("main");

    // Remove it from the document
    main.remove();

    counter--;

    // Add it again; essentially resetting it up
    setUp();
}

It is recommended to refactor the code base as there is excessive copy-pasting present, but that task is left for your discretion.

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

After making an AJAX call, the table data can be found in page 1 under the tbody

Can anyone help me with this issue? I've gone through all the guides related to this problem and followed them step by step, but still no success. After populating the table using an AJAX call, all the data appears on a single page only. I attempted ...

Using JavaScript and the Firefox browser, learn how to easily highlight an element with Selenium-WebDriver

I am struggling with creating a valid function to highlight specific elements on a webpage. As a beginner in coding, I suspect that the issue may either be related to my environment setup or a lack of knowledge about JavaScript/Selenium features. I am wri ...

Decoding a changeable JSON structure

As I am working on parsing a JSON and looking for a specific key within the JSON object, I am facing an issue due to the changing structure of the JSON. It is not feasible to hard code the path for searching. Are there any alternative methods to parse this ...

Is there a way to manually stop a file upload (stream) using a XMLHttpRequest on the server?

Utilizing XMLHttpRequest (Level 2) to transfer a file to a node.js server, I am currently examining the file-stream for valid headers on the server side. The goal now is to halt the upload if any errors are encountered during streaming. My XMLHttpRequest c ...

Add a class to a button in an Angular btn-group if a specific string is found within an

I am currently working on a project where I have multiple buttons that need to toggle an active class when selected in order to change their color. Below is a snippet of what I have: In the array called 'selected', I have: this.selected = [&ap ...

Sending an array of objects in JavaScript to a controller

I have a dynamic form that I'm trying to submit to my Controller. Instead of sending just a string or an array with data, I need to pass an array of objects using ajax request after building the Javascript Array. The challenge is that when I send only ...

Cypress: Uncovering the method invoked by a button click

I'm currently utilizing Vue3 with Vite and Cypress. My Vue3 component utilizes the script setup SFC syntax. Below is the code snippet for my component: <template> <div> <button data-cy="testBtn" @click="btnClick()&q ...

Change the visibility of a div's content when a radio button is selected with only CSS

When the radio buttons are on the same div level as "content1" and "content2", it works properly. But how can I make it work if I move the radio buttons to another div outside of the "second" div? For example, if toggle1 is checked then content1 should be ...

BOOTSTRAP: changing the layout of panels in various sizes for mobile devices

I'm struggling with how to reorganize my panels on mobile devices. Each panel has a different size. Please refer to the attached screenshot for the page layout on large screens (col-lg): EDIT: The layout on large screens looks fine, as I prefer not t ...

Troubleshooting issues with drawing images on HTML5 canvas: experiencing unexpected outcomes

As I am diving into learning how to use the HTML5 canvas element, I have had success in drawing rectangles, utilizing getImageData, manipulating pixels, and then using putImageData to witness the color changes of the rectangles, among other capabilities. ...

What are the steps for skipping, sorting, and limiting with dynamoose?

After being familiar with MongoDB and mongoose, I am now exploring dynamoose for my app. In order to replicate the below-shown mongoose query using dynamoose, how can I write it? Specifically, I want to achieve the same functionality as the following mong ...

The clash between Kendo UI and jQuery UI

I implemented Kendo UI for the date picker, and I'm looking to incorporate jQuery UI for the autocomplete feature. Upon adding the jQuery auto complete to my code, I encountered the following error: Uncaught TypeError: Cannot read property 'e ...

PHP and mysqli combine to create a versatile image slider with changing images

I am looking to implement an image slider that can be updated by the admin using php and mysqli. The admin should have the ability to easily add or remove images as needed. ...

Looking for a way to locate any elements in jQuery that do not contain a certain CSS class?

I am looking to target all form elements that do not contain a specific CSS class. For example: <form> <div> <input type="text" class="good"/> <input type="text" class="good"/> <input type="text" class="bad"/> ...

Transforming an array of JSON objects into a Knockout observable array containing observable properties

My application utilizes an ajax call to fetch a JSON array. [ {"ID":2,"Name":"Name 1","CreatedOn":"/Date(1432892160000)/"}, {"ID":7,"Name":"Name 2","CreatedOn":"/Date(1432892160000)/"}, {"ID":8,"Name":"Name 3","CreatedOn":"/Date(1432892160000)/"}, {"ID":9 ...

Verify that a minimum of one checkbox has been ticked according to JavaScript guidelines, with appropriate notifications in case

Need help with displaying a message when no checkbox is checked. Currently implementing JavaScript rules and messages <form method="post" enctype="multipart/form-data name="english_registration_form" id="english_registration_form" > <div cl ...

Tips for establishing a fixed point at which divs cease to shrink as the browser size decreases

There are numerous dynamically designed websites where divs or images shrink as the browser size decreases. A great example of this is http://en.wikipedia.org/wiki/Main_Page The div containing the text shrinks proportionally to the browser size until it ...

Performing an API request and saving the response data into a

I’m struggling to figure out how to make an API call with request in MongoDB using Mongoose. I’m new to this topic and could really use some help! Here is my test.js file, does anyone have any ideas on how to solve this issue? My goal is to save the AP ...

Execute script when the awaited promise is fulfilled

I am looking to retrieve the URL of a cat image using the Pexels API through a script, and then set that image link as the source of an actual image element. I attempted to include some loading text to keep things interesting while waiting for the image l ...

Adding objects to an existing array in Vue.js can be a seamless and

Struggling to populate my existing array with elements from a JSON response using a button click. The issue lies in properly adding these elements to the array. I have an empty array named results where I store the data from the response. export default ...