How to use modal box using javascript and asp.net? - javascript

Basically i tried creating a modal box that will appear after clicking a button for submission. It will either display upload successful or upload failed. Now, I have two problems that i have encountered that i am hoping that you guys can help me out. Here are the questions:
After clicking the submit button, it will appear roughly for 3 seconds and then it will postback. After that, the modal box is gone. What i want to happen is, the modal box should not disappear unless i clicked the x button. Then after that, the webpage can now do postback. If possible, how to achieve this?
Also, i have noticed that the modal box that i have integrated in my website cannot distinguish if the upload is successful or fail. I can see that it will still display upload successful even if the submission is failed. As of now, I have only coded the upload successful because I don't know yet on how to apply the upload fail yet. It should be able to determine if the submit button is successful or failed. How to achieve this?
Here is the aspx and script:
<asp:Button ID="Button1" runat="server" CssClass="submitButton" Text="Save
Item" OnClick="Button1_Click"/>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Upload Successful</p>
</div>
</div>
<script>
var modal = document.getElementById('myModal');
var btn = document.getElementById('<%=Button1.ClientID%>');
var span = document.getElementsByClassName("close")[0];
btn.onclick = function () {
modal.style.display = "block";
}
span.onclick = function () {
modal.style.display = "none";
}
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
Here is the code-behind. Take note, i haven't really put anything inside the catch because its suppose to return an upload failed popup box:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
int item_brandId =
ConnectionClassBrands.GetIdByBrand(itemBrand.Text);
string item_model = itemModel.Text;
double item_price = Convert.ToDouble(itemPrice.Text);
string item_image1 = Session["PicturePath1"].ToString();
string item_image2 = Session["PicturePath2"].ToString();
string item_description = itemDescription.Text;
string item_necktype = itemNeckType.Text;
string item_body = itemBody.Text;
string item_fretboard = itemFretboard.Text;
string item_fret = itemFret.Text;
string item_bridge = itemBridge.Text;
string item_neckpickup = itemNeckPickup.Text;
string item_bridgepickup = itemBridgePickup.Text;
string item_hardwarecolor = itemHardwareColor.Text;
if (itemType1.Checked)
{
int item_type =
ConnectionClassBrands.GetIdByType(itemType1.Text);
ItemType = item_type;
}
else if (itemType2.Checked)
{
int item_type =
ConnectionClassBrands.GetIdByType(itemType2.Text);
ItemType = item_type;
}
var item = new instrumentItem
{
typeId = ItemType,
brandId = item_brandId,
model = item_model,
price = item_price,
itemimage1 = item_image1,
itemimage2 = item_image2,
description = item_description,
necktype = item_necktype,
body = item_body,
fretboard = item_fretboard,
fret = item_fret,
bridge = item_bridge,
neckpickup = item_neckpickup,
bridgepickup = item_bridgepickup,
hardwarecolor = item_hardwarecolor
};
ConnectionClassGuitarItems.AddStringInstrumentItems(item);
ClearTextFields2();
}
catch (Exception)
{
}
}
Here is the stylesheet if necessary:
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}

Related

Delete request using box modal in MVC

I have a box modal that I created in my view using HTML that is called when the user presses a button called delete if they wanted to delete a request. From here the user sees two buttons, one to confirm the deletion and one the cancel the deletion. However when I click the delete button the box modal pops up but the buttons confirm and cancel don't delete. I am using MVC .NET core Framework for this project and I want the user to be able to delete requests but to be prompted if they are certain that they want to delete them.
#model PsSecurityRequest
<!-- The Modal -->
<button id="mybtn">Delete</button>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<h3>Are you sure you want to permanetly delete this request?</h3>
<span class="close">×</span>
<input type="submit" class="btn btn-primary" value="Confirm" asp-controller="AdminPage" asp-action="Delete" asp-route-id="#Model.RequestId" />
<input type="submit" class="btn btn-primary" value="Cancel" asp-controller="AdminPage" asp-action="Index" />
</div>
</div>
The view that I am using for the box modal is shown here.
function AdminPage() {
//var Status = document.getElementById("ddlState");
//var Confirm = document.getElementsByClassName("Confirm");
//var Cancel = document.getElementsByClassName("Cancel");
//var _Confirm = "Confirm"
//Confirm.classList.add("hide");
//Cancel.classList.add("hide");
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("mybtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function () {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
}
This is the javascript file that I am using in this project.
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
Here is the .cs file I am using as well for the box modal.
public IActionResult Delete(int Id)
{
// var id;
//_psSecurityRequestRepository = PsSecurityRequest.GetRequest();
// PsSecurityRequest deleteRequest = _psSecurityRequestRepository.GetRequestById(Request);
PsSecurityRequest securityRequest = _psSecurityRequestRepository.GetRequestById(Id);
//PsSecurityRequest repo = new PsSecurityRequest();
// var _data = repo.Requests();
_psSecurityRequestRepository.DeleteRequests(securityRequest);
return View(securityRequest);
}
This is the action method that is called when the user will confirm to delete a request. Finally here is the repository that has the methods that are seen in the action method within the controller.
public PsSecurityRequest GetRequestById(object id)
{
throw new NotImplementedException();
}
//[HttpPost, ActionName ("Delete") ]
public void UpdateShortEmplId(PsSecurityRequest psSecurityRequest)
{
_appDbContext.Update(psSecurityRequest);
_appDbContext.SaveChanges();
}
public void FixEmplId()
{
foreach(PsSecurityRequest psSecurityRequest in psSecurityRequests)
{
if (psSecurityRequest.SecurityForEmplid.Length < 7)
{
psSecurityRequest.SecurityForEmplid = "0" + psSecurityRequest.SecurityForEmplid;
_appDbContext.Update(psSecurityRequest);
}
}
_appDbContext.SaveChanges();
}
public void DeleteRequests(PsSecurityRequest Request)
{
_appDbContext.Remove(Request);
throw new NotImplementedException();
}

How to make konami code open a modal that enables/disables dark mode (and has a close button)? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So I tried to make a Modal that opens up typing in the Konami code(↑↑↓↓←→←→BA). This is what I have tried so far(I'm a newbie to JS so plz don't be mean. btw I have the code set but I need the modal. Look into code for more details.):
var pattern = ['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowLeft', 'ArrowRight', 'b', 'a'];
var current = 0;
var keyHandler = function (event) {
// If the key isn't in the pattern, or isn't the current key in the pattern, reset
if (pattern.indexOf(event.key) < 0 || event.key !== pattern[current]) {
current = 0;
return;
}
// Update how much of the pattern is complete
current++;
// If complete, alert and reset
if (pattern.length === current) {
current = 0;
// Modal with dark mode option and light mode (if dark mode is already turned on(optional)).
}
};
// Listen for keydown events
document.addEventListener('keydown', keyHandler, false);
<h1> Enter the Konami code. (↑↑↓↓←→←→BA) for a surprise.
Taken directly from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal
No credit to me just a copy and paste
var pattern = [
"ArrowUp",
"ArrowUp",
"ArrowDown",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"ArrowLeft",
"ArrowRight",
"b",
"a"
];
var current = 0;
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
var keyHandler = function (event) {
// If the key isn't in the pattern, or isn't the current key in the pattern, reset
if (pattern.indexOf(event.key) < 0 || event.key !== pattern[current]) {
current = 0;
return;
}
// Update how much of the pattern is complete
current++;
// If complete, alert and reset
if (pattern.length === current) {
modal.style.display = "block";
current = 0;
// Modal with dark mode option and light mode (if dark mode is already turned on(optional)).
}
};
span.onclick = function () {
modal.style.display = "none";
};
// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
};
// Listen for keydown events
document.addEventListener("keydown", keyHandler, false);
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<h1> Enter the Konami code. (↑↑↓↓←→←→BA) for a surprise.</h1>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>

modal pop up box dissapears immediately

I'm a beginner in web development and I have a form where you enter your name and surname . Then by clicking submit , a modal box has to pop up in the screen saying that your purchase is complete and by clicking an ok button it has you move to another html page . In my form I have a function that when you submit the form it checks if the name and surname are strings . If they are you have to open the modal box using a function , else return false and enter again . In my page the modal box pops up for a single second and then the page justs reloads . Basically I'm trying to call a function that pops up a modal box after name and surname are validated .
I would appreciate your help with guiding me to solve this task.
Thank you in advance .
My code :
function validateStrings(){
var x = document.getElementById("first");
var y = document.getElementById("last");
if(!(/\d/.test(x.value)) && !(/\d/.test(y.value))){
}
else{
alert('no submit');
return false;
}
popbox(); //after checking if inputs are strings pop up the box
}
function popbox(){
var btn = document.getElementById("submit");
var modal = document.getElementById("mymodal");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick=function(){
modal.style.display="none";
}
//when user clicks on window outside of box close the modal
window.onclick=function(){
if (event.target == modal) {
modal.style.display = "none";
}
}
}
#ondel{
position:relative;
margin:10px auto 0px;
width:500px;
height:250px;
box-sizing:border-box;
background:rgb(0,0,0,0.5);
padding:40px;
border-radius:50px;
}
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
footer{
font-size:10px;
}
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<div class = "on-delivery-container" id = "ondel">
<form class = "pay">
<label for "First-name"> First Name </label>
<input type = "text" name = "fname" id="first" required>
<label for "Last-name"> Last Name </label>
<input type = "text" name = "sname" id="last" required>
<button type = "button" class = "cancelbtn" onclick = "returntostep2()">Go back</button>
<button type = "submit" class = "submitbtn" onclick= "return validateStrings()">Submit</button> //valideStrings() checks my input
</form>
//my modal box
<div class = "modal" id = "mymodal">
<div class = "modal-content" id = "mymodalcontent">
<span class="close">×</span>
<p> Your purchase is complete ! </p>
<button class = "submitbtn" type = "button" onclick = "window.location.href='Start_page.html';"> OK </button>
</div>
<footer> © BookHouse All Rights Reserved. </footer>
</div>
</div>
Pass the click event to your validateStrings() and use e.preventDefault() to stop the submit button from refreshing the page. Alternatively name the button something other then submit and manually submit your form when you're are ready inside the pop up or validateStrings function

How to edit array item using javascript

I am pretty new to js. I am trying to complete a todo sort of app. I have been able to create, render and delete an array item, but I am having trouble editing.
All these operations are done with the uuidv4 library to generate an id for each array item created.
With an individual id selected for an array item, I am generating dynamic buttons, one for deleting the array item, the other one for editing.
Upon clicking edit, I want to open up a modal that contains the content of the selected array item. After making the changes, the edit button inside the modal should call upon an edit function to update the changes and then rerender the array.
My issue is that I can't open up the modal dialog box when clicking the edit button.
This is the code to create the necessary structure, the code for creating, rendering and deleting is not included as they are working properly.
// Generate the DOM structure for a todo
const generateTodoDOM = function(todo) {
const todoEl = document.createElement("div");
const checkbox = document.createElement("input");
const label = document.createElement("label");
checkbox.appendChild(label);
todoEl.setAttribute("id", "myTodos");
const textEl = document.createElement("p");
const editButton = document.createElement("button");
editButton.setAttribute("id", "modal-btn");
const removeButton = document.createElement("button");
const createDate = document.createElement("p");
createDate.textContent = `Created: ${dateCreated}`;
createDate.style.color = "#956E93";
// Setup the todo text
textEl.textContent = todo.text;
todoEl.appendChild(textEl);
// Setup the remove button
removeButton.textContent = "x";
todoEl.appendChild(removeButton);
removeButton.addEventListener("click", function() {
removeTodo(todo.id);
saveTodos(todos);
renderTodos(todos, filters);
});
// TODO: Setup the edit note button
editButton.textContent = "Edit Todo";
todoEl.appendChild(editButton);
editButton.addEventListener("click", function() {
//Launch the modal
editModal(todo.id);
});
// Setup todo checkbox
checkbox.setAttribute("type", "checkbox");
checkbox.checked = todo.completed;
todoEl.appendChild(checkbox);
checkbox.addEventListener("change", function() {
toggleTodo(todo.id);
saveTodos(todos);
renderTodos(todos, filters);
});
todoEl.appendChild(createDate);
return todoEl;
};
The code for the modal is the following:
//Edit modal todo by id
const editModal = function(id) {
const todoIndex = todos.findIndex(function(todo) {
return todo.id === id;
});
if (todoIndex > -1) {
const modal = document.querySelector("#my-modal");
const modalBtn = document.querySelector("#modal-btn");
const editTodoContentBtn = document.querySelector("#submitEditTodo")
const closeBtn = document.querySelector(".close");
// Events
modalBtn.addEventListener("click", openModal);
closeBtn.addEventListener("click", closeModal);
editTodoContentBtn.addEventListener("click", editTodo)
window.addEventListener("click", outsideClick);
// Open
function openModal() {
modal.style.display = "block";
}
// Close
function closeModal() {
modal.style.display = "none";
}
// Close If Outside Click
function outsideClick(e) {
if (e.target == modal) {
modal.style.display = "none";
}
}
//Edit the content of the textarea
function editTodo(e) {
editTodo(id)
}
}
};
When clicking the submitEditTodo button the following edit function should be fired:
//Edit todo by id
const editTodo = function(id) {
const editTodoContent = document.querySelector('#editTodo')
const todoIndex = todos.findIndex(function(todo) {
return todo.id === id;
});
if (todoIndex > -1) {
editTodoContent.value = todos.text
saveTodos(todos)
renderTodos(todos, filters);
}
};
The saveTodos and renderTodos are functioning properly with other functions for creating, rendering and deleting.
This is the HTML code:
<!-- Edit modal -->
<div id="my-modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Edit Todo</h2>
</div>
<div class="modal-body">
<textarea name="" class="editTextArea" id="editTodo" rows="10"></textarea>
<button class="button" id="submitEditTodo">Edit Todo</button>
</div>
<div class="modal-footer">
<!-- <h3>Modal Footer</h3> -->
</div>
</div>
<!-- End modal -->
and this is the CSS for the modal:
/*
Edit todo modal start
*/
:root {
--modal-duration: 1s;
--modal-color: #BB8AB8;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
height: 100%;
width: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
margin: 10% auto;
width: 35%;
box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
animation-name: modalopen;
animation-duration: var(--modal-duration);
}
.editTextArea{
width:100%
}
.modal-header h2,
.modal-footer h3 {
margin: 0;
}
.modal-header {
background: var(--modal-color);
padding: 15px;
color: #fff;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.modal-body {
padding: 10px 20px;
background: #fff;
}
.modal-footer {
background: var(--modal-color);
padding: 10px;
color: #fff;
text-align: center;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
}
.close {
color: #ccc;
float: right;
font-size: 30px;
color: #fff;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#keyframes modalopen {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/*
Edit todo modal end
*/
Thanks
Below are a few pointers to where you might need adjustments to achieve what you want.
Currently you are adding new listeners to the modal every time you click an edit button for a todo. This should probably only be set once. Alternatively you should remove the listeners when the modal is closed.
Your function editModal does not actually open the modal. What it does is add a listener to the #modal-btn button which will then open the modal the next time you click the button.
You are setting id's for both the outer div and the edit button, but the id's are not based on anything related to the todo element you are creating. So effectively all those elements end up with the same id. An id (short for identifier) is usually meant to be unique. For grouping of multiple elements you should instead use the class attribute.
Your function "editTodo" calls itself. Recursing indefinitely. Beware of reusing function names.
With that said the below code is a crude way to do what I think you want to do based on the snippets you provided:
// Open
const openModal = function() {
document.querySelector("#my-modal").style.display = "block";
}
// Close
const closeModal = function() {
document.querySelector("#my-modal").style.display = "none";
}
function initModal() {
const modal = document.querySelector("#my-modal");
const closeBtn = document.querySelector(".close");
// Events
closeBtn.addEventListener("click", closeModal);
window.addEventListener("click", outsideClick);
// Close If Outside Click
function outsideClick(e) {
if (e.target == modal) {
modal.style.display = "none";
}
}
}
const filters = []; // dummy variable
// Generate the DOM structure for a todo
var todos = []
function generateTodoDOM(todo) {
todos.push(todo);
const todoEl = document.createElement("div");
const checkbox = document.createElement("input");
const label = document.createElement("label");
checkbox.appendChild(label);
todoEl.setAttribute("id", "my-todos-" + todo.id);
const textEl = document.createElement("p");
const editButton = document.createElement("button");
editButton.setAttribute("id", "modal-btn-" + todo.id);
const removeButton = document.createElement("button");
const createDate = document.createElement("p");
createDate.textContent = 'Created: ' + new Date();
createDate.style.color = "#956E93";
// Setup the todo text
textEl.textContent = todo.text;
todoEl.appendChild(textEl);
// Setup the remove button
removeButton.textContent = "x";
todoEl.appendChild(removeButton);
removeButton.addEventListener("click", function() {
removeTodo(todo.id);
saveTodos(todos);
renderTodos(todos, filters);
});
// TODO: Setup the edit note button
editButton.textContent = "Edit Todo";
todoEl.appendChild(editButton);
editButton.addEventListener("click", function() {
//Launch the modal
editModal(todo.id);
openModal();
});
// Setup todo checkbox
checkbox.setAttribute("type", "checkbox");
checkbox.checked = todo.completed;
todoEl.appendChild(checkbox);
checkbox.addEventListener("change", function() {
toggleTodo(todo.id);
saveTodos(todos);
renderTodos(todos, filters);
});
todoEl.appendChild(createDate);
return todoEl;
};
var editFn
//Edit modal todo by id
const editModal = function(id) {
const todoIndex = todos.findIndex(function(todo) {
return todo.id === id;
});
if (todoIndex > -1) {
const modal = document.querySelector("#my-modal");
const editElm = document.querySelector("#editTodo");
const editTodoContentBtn = document.querySelector("#submitEditTodo")
editElm.value = todos[todoIndex].text;
// Events
editTodoContentBtn.removeEventListener("click", editFn)
//Edit the content of the textarea
editFn = function(e) {
editTodo(id)
closeModal()
}
editTodoContentBtn.addEventListener("click", editFn)
}
};
//Edit todo by id
const editTodo = function(id) {
const editTodoContent = document.querySelector('#editTodo')
const todoIndex = todos.findIndex(function(todo) {
return todo.id === id;
});
if (todoIndex > -1) {
todos[todoIndex].text = editTodoContent.value;
saveTodos(todos)
renderTodos(todos, filters);
}
};
const saveTodos = function(todos) {
// dummy method, we're keeping it in memory for this example
}
const renderTodos = function(todosToRender) {
todos = []; // clear current in-memory array
var todoList = document.getElementById("todo-container");
while (todoList.firstChild) {
todoList.removeChild(todoList.firstChild);
}
for(var i = 0; i < todosToRender.length; i++) {
todoList.appendChild(generateTodoDOM(todosToRender[i]));
}
};
initModal();
const container = document.getElementById("todo-container");
var generatedTodos = [];
for(var i = 0; i < 10; i++) {
var todo = { text: "Todo " + (i+1), id: "todo-" + i, completed: false};
generatedTodos.push(todo);
}
renderTodos(generatedTodos);
/*
Edit todo modal start
*/
:root {
--modal-duration: 1s;
--modal-color: #BB8AB8;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
height: 100%;
width: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
margin: 10% auto;
width: 35%;
box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
animation-name: modalopen;
animation-duration: var(--modal-duration);
}
.editTextArea{
width:100%
}
.modal-header h2,
.modal-footer h3 {
margin: 0;
}
.modal-header {
background: var(--modal-color);
padding: 15px;
color: #fff;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.modal-body {
padding: 10px 20px;
background: #fff;
}
.modal-footer {
background: var(--modal-color);
padding: 10px;
color: #fff;
text-align: center;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
}
.close {
color: #ccc;
float: right;
font-size: 30px;
color: #fff;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#keyframes modalopen {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/*
Edit todo modal end
*/
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="todo-container">
</div>
<!-- Edit modal -->
<div id="my-modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Edit Todo</h2>
</div>
<div class="modal-body">
<textarea name="" class="editTextArea" id="editTodo" rows="10"></textarea>
<button class="button" id="submitEditTodo">Edit Todo</button>
</div>
<div class="modal-footer">
<!-- <h3>Modal Footer</h3> -->
</div>
</div>
</div>
<!-- End modal -->
</body>
</html>

Javascript: Avoiding multiple pop up boxes / check if div is empty

I created a pop up box that appears when a user clicks a button. Currently I am able to get the box to appear but when the user closes it and re-opens it the code is ran through again and another box is stacked on top of the old one.
What I want to do is make it so no matter how many times the user clicks the box it only shows one box... my thoughts was maybe checking if it was empty similar to How do I check if an HTML element is empty using jQuery? however that has not worked so far.
Any suggestions for a noob idiot? Appreciation for all responses in advance.
<button onclick="popup()">text</button>
<script>
var box = document.getElementById('popupbox');
function popup(){
box.style.display = "block";
var content = document.createElement('div');
content.className = 'boxstyle';
content.innerHTML = ' ...a handful of tags...';
box.appendChild(content);}
function exit(){
box.style.display = "none";}
</script>
You can create a popup using a modal as follows. I just copied code from here
<!DOCTYPE html>
<html>
<head>
<style>
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
I actually managed to solve it by simply tossing in box.innerHTML = '' right after the block appears so that it has a clean slate to work with. I was trying to go a little more elegant and seeking to use an If/Else statement but in the end it seems to work. Much appreciation for all who answered / commented, you all are awesome!
<button onclick="popup()">text</button>
<script>
var box = document.getElementById('popupbox');
function popup(){
box.style.display = "block";
box.innerHTML = '';
var content = document.createElement('div');
content.className = 'boxstyle';
content.innerHTML = ' ...a handful of tags...';
box.appendChild(content);}
function exit(){
box.style.display = "none";}

Categories