The JavaScript-rendered HTML button is unresponsive

I have a JavaScript function that controls the display of a popup window based on its visibility. The function used to work perfectly, with the close button effectively hiding the window when clicked. However, after making some changes to the code, the close button no longer functions as intended. I have included both the previous and current versions of the function, along with the 'overlay' div it interacts with and the CSS styles for the div. Any assistance in identifying what went wrong and how to fix it would be highly appreciated. I am struggling to pinpoint the exact cause of the issue.

Previous (working) function:

<script>
function overlay(descrip, name) {
    var descripBox = "<div><h3>"+name+"</h3><p>"+ descrip +"</p></br><input type='button' onclick='overlay()' value='Close'></input></div>";
    var el = document.getElementById("overlay");
    el.innerHTML = descripBox;
    el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
</script>

Current (not working) function:

<script>
function overlay(descrip, name, req) {
    if(req != ''){
        var obj = new Array();
        obj = req.split("|");
        var reqHtml = "Requirements:</br><ul>";
        for(var i = 0; i < obj.length; i++)
        {
            reqHtml += "<li>"+obj[i]+"</li>";
        }
        reqHtml+= "</ul></br>";
    }
    else
        var reqHtml = '';
    var descripBox = "<div><h3>"+name+"</h3><p>"+ descrip +"</p></br>"+
        reqHtml +"<center><input type='button' onclick='overlay()' value='Close'></input></center></div>";
    var el = document.getElementById("overlay");
    el.innerHTML = descripBox;
    el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
</script>

Overlay div:

<div id="overlay">
     <div>
          </br>
          <input type="button" onclick="overlay()" value="Close"></input>
     </div>
</div>

CSS:

#overlay {
     visibility: hidden;
     position: absolute;
     left: 0px;
     top: 500px;        
     width:100%;
     height:100%;
     z-index: 1000;
}

#overlay div {
     width:300px;
     margin: 100px auto;
     background-color: #ebebeb;
     border:2px solid #c7c7c7;
     padding:15px;   
}

Answer №1

Initially, the code you have written appears quite peculiar.

    if(req != ''){
        var obj = new Array();
        obj = req.split("|");
        var reqHtml = "Requirements:</br><ul>";
        for(var i = 0; i < obj.length; i++)
        {
            reqHtml += "<li>"+obj[i]+"</li>";
        }
        reqHtml+= "</ul></br>";
    }

The section will be executed as you are invoking your function without any parameters :

 onclick="overlay()"

This results in 'req' being undefined. However, in JavaScript, undefined is treated as an empty string (your ''). Also, it is equal to 0 or false unless you use "!==" which signifies strictly not equal, indicating a requirement of an empty string.

Moreover, this part:

   else
        var reqHtml = '';

is problematic. It's ambiguous whether you forgot the brackets or not, but always enclose if/else statements within brackets to prevent errors when adding instructions between the lines. Additionally, using 'var' here confines the 'reqHTML' variable only within the "else" scope and renders it inaccessible outside.

Hence, it's advisable to declare it at the beginning of the function, resulting in the following code structure:

var reqHtml = '';
if(req != ''){
        var obj = new Array();
        obj = req.split("|");
        var reqHtml = "Requirements:</br><ul>";
        for(var i = 0; i < obj.length; i++)
        {
            reqHtml += "<li>"+obj[i]+"</li>";
        }
        reqHtml+= "</ul></br>";
}
var descripBox = "<div><h3>"+name+"</h3><p>"+ descrip +"</p></br>"+
        reqHtml +"<center><input type='button' onclick='overlay()' value='Close'></input></center></div>";
var el = document.getElementById("overlay");

Furthermore, relying on detecting the CSS state for decision-making might not be ideal since it could lead to undefined values. Instead, defining a variable like "boxVisibility" to manage such aspects would prove more efficient and organized.

Lastly, all the function parameters seem to be undefined regardless. Thus, it's better to maintain them as global variables or retrieve them from another source before commencing the function. Refer to the example below for a potential working solution:

var descrip = "Test desc";
var name = "Test name";
var req = "test req";
var boxVisibility = true;

function updateBox() {
    var reqHtml = '';
    if(req != ''){
            var obj = new Array();
            obj = req.split("|");
            var reqHtml = "Requirements:</br><ul>";
            for(var i = 0; i < obj.length; i++)
            {
                reqHtml += "<li>"+obj[i]+"</li>";
            }
            reqHtml+= "</ul></br>";
        }
        var descripBox = "<div><h3>"+name+"</h3><p>"+ descrip +"</p></br>"+
            reqHtml +"<center><input type='button' onclick='overlay()' value='Close'></input></center></div>";
        var el = document.getElementById("overlay");
        el.style.visibility = (boxVisibility) ? "hidden" : "visible";
}
function overlay() {
    boxVisibility = !boxVisibility; // Toggle the box visibility variable
    updateBox(); // Update box display
}

You should then modify 'desc', 'name', and 'req' based on the requirements of your application.

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

Reduce the text of the link

Trying to simplify a task, but I'm struggling with the solution. What I want to achieve is shortening a link to 30 characters and adding ... at the end if it's longer. Also, I'd like to make it possible to see the full link on hover similar ...

Is there a glitch in Safari's CSS involving max-height?

Currently, I am in the process of developing a popup for a registration form. The CSS rules have been configured accordingly and after testing on various browsers, it has come to my attention that Safari is displaying an additional white space between elem ...

Ways to retrieve and upload a blob from a file object

After receiving a file object via an HTML input on-change event in my component.html: onFileSelected(event) { this.selectedFile = event.target.files[0]; } Now, I need to send a POST request to upload the image to the database. The database only acc ...

Are there any reliable sources for a complete list of browser CSS properties?

Is there a way to easily access a comprehensive list of CSS properties supported by specific browsers, particularly IE8? Any suggestions on where I can find this information? ...

Adding elements in increasing order based on the array values

I am implementing selectize.js, where the data is added through an array. My goal is to display the dropdown list in the order of DISPLAYORDER defined within the object. The code below generates the lists: option: function(item, escape) { var popular ...

Failure to trigger AJAX Success or Error Events

I'm struggling to understand why this code isn't working or find any relevant resources. When I check the json object in Firebug, it either returns success: false or success: true from the post request, so I'm confused as to why the function ...

What is the process for accessing the mesh in Aframe when a 3D object is loaded dynamically?

Is there a way to access mesh information of a 3D object loaded at runtime in Aframe? My method for loading the 3D model is as follows: targetObj = document.createElement('a-obj-model'); targetObj.setAttribute('gltf-model', '#wha ...

Ways to specify the specific option within a select field

Here is my question: <select name="currency" id="currency"> <option value="AUD"&lgt;AUD</option> <option value="BDT"&lgt;BDT</option> <option value="EUR"&lgt;EUR</option> & ...

Adapting CSS according to input selection

Forgive me for asking what may seem like a simple question. I am currently using the CSS code below to modify the background color of a label when its associated checkbox is checked: #project input[id="button1"]:checked + label {background-color:red;} Is ...

Streamlining the process of formatting URLs?

I was pondering if there is a more efficient method to accomplish this task. I extract links from a webpage, but many of them are relative. for example /index.html for instance /home.index.html Currently, my approach involves adding the home URL to compe ...

Tips for updating the class of a button upon clicking it

I have a dilemma with my two buttons - one is green and the other has no background. I want them to change appearance when clicked, from green to one with a dashed border-bottom style. Below is the HTML code for these buttons: <div class="btns"> ...

When I apply position: absolute; to my navigation bar, the anchor tags and links do not seem to function properly, especially with a video playing in the background

How can I make my anchor tags/links work properly on a header with a video in the "background" and a menu on top? HTML <nav class="menu"> <a href="#" target="_blank">ABOUT</a> <a href="#" target="_blank">PRICES</a&g ...

Utilizing jQuery to establish various AJAX requests through functions on page load and button click

Utilizing a basic ajax call both on page load and click events, where I have defined separate functions for each. Despite using different URLs and parameters in the function, the JSON data from the previous call is still being displayed when clicked. Bel ...

AngularJS implementation that disables a button when the input field is empty

As I delve into learning angular JS, I am facing a challenge. I want to disable the button using the "ng-disabled" attribute while my input fields for "login" and "password" are empty. However, the default text in the login input is "LOGIN" and in the pass ...

Optimizing loading times for mobile banners through media queries

I currently have a standard size banner that loads when my page is accessed on a computer. However, I would like to optimize the loading speed by having a smaller version specifically for mobile devices using a media query. My main question is how does t ...

Steps to simulate a TouchEvent programmatically using TypeScript

Is there a way to manually trigger the touch event in TypeScript? In JavaScript, it was possible but I am struggling to achieve the same in TypeScript. For example: let touchStart: TouchEvent = document.createEvent('TouchEvent'); touchStart.i ...

Saving changes to mesh vertices in r67 of Three.js

I've encountered an issue with saving a mesh to a text file after manipulating vertices in my plane model. While the rendering on screen works as expected, the updates are not reflected in the saved file. Interestingly, if I move a vertex before the ...

What are the steps to execute Mike Bostock's D3 demonstrations?

I've been attempting to run Mike Bostock's See-Through Globe demonstration, but I encountered issues with the correct referencing of his json files when attempting to replicate it locally. The problem stems from this particular line of code: d3. ...

Insert a fresh item into the existing unordered list

Every time I enter something in the prompt, it shows up as "undefined". What I actually want is for whatever I type into the prompt to be added as a new list item. For instance, if I type "Food" in the prompt, I expect to see "Food" appear on the second li ...

The Keyup Filter in the FromEvent function is malfunctioning and not behaving as anticipated

I have created a simple search function for my app using the FromEvent KeyUp and debounceTime features as shown in the code below: <input matInput #inputSearch> @ViewChild('inputSearch', { static: false }) input: ElementRef; fromEvent(th ...