- Кнопка удаления с подтверждением
- HTML
- CSS
- JavaScript
- How TO — Delete Modal
- Delete Account
- How To Create a Delete Modal
- Example
- Delete Account
- Example
- Example
- How to Create a Delete Button in JavaScript?
- A step-by-step guide to create delete button in JavaScript
- Step 1: Set up your HTML structure
- 2. Script.js
- 3. CSS
- Another way on how to create a delete button in JavaScript
- Conclusion
- Delete button with confirmation — A step-by-step guide
- HTML
- CSS
Кнопка удаления с подтверждением
Однажды один мой товарищ попросил сделать для одного его проекта кнопку удаления, которая содержала бы внутри себя подтверждение. Т.е. как это сделано обычно? Нажимаешь удалить — выскакивает окно с вопросом «Вы уверены, что ходите удалить то-то и то-то?» — нажимаешь «Да», после чего удаляется то, что надо. Так вот, он хотел чтобы нажимаешь «Удалить», внутри кнопки меняется текст на «Вы уверены?», нажимаешь еще раз и происходит удаление.
Идея показалась мне интересной, и я решил поделиться способом простой реализации.
HTML
Это наша кнопка-ссылка, которая куда-то ведет. На нажатие подвешен javascript-обработчик. У ссылки два класса delete-link и need-to-confirm . Внутри ссылки два элемента с текстом. Первый отображается с самого начала, второй становится виден после однократного нажатия.
CSS
.delete-link < display: inline-block; padding: 3px 5px; border: 1px solid red; background-color: #edbaba; color: red; text-decoration: none; >.delete-link:hover < background-color: #fff; >.need-to-confirm .confirmation < display: none; >.confirmed .maintext
JavaScript
var confirmDelete = (function (element) < var className = element.className; if (className.indexOf('need-to-confirm') >-1) < element.className = className.replace('need-to-confirm', 'confirmed'); return false; >else < element.remove(); >>);
А вот и функция. В нее передается элемент, на который происходит нажатие, функция проверяет какой класс в данный момент у ссылки, если need-to-confirm , значит пользователя нужно спросить «Уверен ли он?», в противном случае что-то сделать. В моем примере открывается новая вкладка по адресу указанному в ссылке и кнопка «Удалить» исчезает. Но легко можно добавить какой-нибудь Ajax запрос или еще что-то.
How TO — Delete Modal
Learn how to create a delete confirmation modal with CSS.
Click on the button to open the modal:
Delete Account
Are you sure you want to delete your account?
How To Create a Delete Modal
Step 1) Add HTML:
Example
×
Delete Account
Are you sure you want to delete your account?
Step 2) Add CSS:
Example
/* Set a style for all buttons */
button background-color: #04AA6D;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
>
/* Float cancel and delete buttons and add an equal width */
.cancelbtn, .deletebtn float: left;
width: 50%;
>
/* Add a color to the cancel button */
.cancelbtn background-color: #ccc;
color: black;
>
/* Add a color to the delete button */
.deletebtn background-color: #f44336;
>
/* Add padding and center-align text to the container */
.container padding: 16px;
text-align: center;
>
/* The Modal (background) */
.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: #474e5d;
padding-top: 50px;
>
/* Modal Content/Box */
.modal-content background-color: #fefefe;
margin: 5% auto 15% auto; /* 5% from the top, 15% from the bottom and centered */
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
>
/* Style the horizontal ruler */
hr border: 1px solid #f1f1f1;
margin-bottom: 25px;
>
/* The Modal Close Button (x) */
.close position: absolute;
right: 35px;
top: 15px;
font-size: 40px;
font-weight: bold;
color: #f1f1f1;
>
.close:hover,
.close:focus color: #f44336;
cursor: pointer;
>
/* Clear floats */
.clearfix::after content: «»;
clear: both;
display: table;
>
/* Change styles for cancel button and delete button on extra small screens */
@media screen and (max-width: 300px) .cancelbtn, .deletebtn width: 100%;
>
>
Tip: You can also use the following javascript to close the modal by clicking outside of the modal content (and not just by using the «x» or «cancel» button to close it):
Example
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) if (event.target == modal) modal.style.display = «none»;
>
>
How to Create a Delete Button in JavaScript?
Today, we will explore how to create a delete button in JavaScript.
One of the dominant things we should know is creating a delete button that lets users remove unwanted elements or data from a website or application.
This article provides a step-by-step guide and code examples on how to create a delete button in JavaScript.
Let’s dive in and learn how to make a delete button using JavaScript!
A step-by-step guide to create delete button in JavaScript
Here’s a step-by-step guide on how to create a delete button in JavaScript.
Step 1: Set up your HTML structure
To start building our delete button, we need to set up the HTML structure that will hold the button and the elements we want to delete.
Here’s a basic HTML template to get started:
2. Script.js
Now that we have our HTML structure. Let’s write the JavaScript code for creating the delete button.
You can do this by using the createElement method to create a new button element and then setting its textContent property to the text you want to display on the button.
For example:
let deleteButton = document.createElement("button"); deleteButton.textContent = "Delete";
After that, you need to add an event listener to the button that will trigger a function when the button is clicked.
This function can be used to remove an element from the page.
For example:
deleteButton.addEventListener('click', function() < // code to remove an element >);
To remove an element from the page, you can use the remove method. This method is called on the element you want to remove and will remove it from the page.
Here’s an example of how you can use this method:
let elementToRemove = document.querySelector("#element-to-remove"); elementToRemove.remove();
Lastly, you will need to add the delete button to the page so that it can be clicked by the user.
You can do this by appending the button element to another element on the page using the appendChild method.
Here’s an example of how you can do this:
let containerElement = document.querySelector("#container"); containerElement.appendChild(deleteButton);
That’s it! You now have a working delete button that can be used to remove elements from the page.
Here’s the complete code:
let deleteButton = document.createElement("button"); deleteButton.textContent = "Delete"; deleteButton.classList.add("delete-button"); deleteButton.addEventListener('click', function() < let elementToRemove = document.querySelector("#element-to-remove"); elementToRemove.remove(); >); let containerElement = document.querySelector("#container"); containerElement.appendChild(deleteButton);
3. CSS
In order to enhance the visual appeal of the delete button, we can apply CSS styles to it.
body < display: flex; align-items: center; justify-content: center; height: 100vh; >#container < text-align: center; >.delete-button < background-color: red; color: white; padding: 10px 20px; border: none; cursor: pointer; display: block; margin: 0 auto; >.delete-button:hover
Here’s the final output of a simple delete button in JavaScript:
Another way on how to create a delete button in JavaScript
Here’s another example of creating a delete button.
Sample To-Do list with Delete Button const todoList = document.querySelector(".todo"); const addButton = document.querySelector(".add"); const nameInput = document.querySelector(".name"); const messageInput = document.querySelector(".message"); addButton.addEventListener("click", function() < const name = nameInput.value; const message = messageInput.value; if (name && message) < const todoItem = document.createElement("li"); todoItem.textContent = `$: $`; const deleteButton = document.createElement("button"); deleteButton.textContent = "Delete"; deleteButton.classList.add("delete-button"); deleteButton.addEventListener("click", function() < todoItem.remove(); >); todoItem.appendChild(deleteButton); todoList.appendChild(todoItem); nameInput.value = ""; messageInput.value = ""; > >);
body, html < height: 100%; >.container < display: flex; align-items: center; justify-content: center; height: 100%; >.todo_list < max-width: 400px; display: block; margin: 0 auto 40px; background-color: #1b83a3; padding: 30px; border-radius: 10px; >h1 < text-align: center; margin-top: 0; margin-bottom: 20px; color: #fff; font-size: 30px; >.create_new_todo < text-align: center; >input[type=text] < width: 376px; padding: 10px; >button < margin-top: 10px; width: 400px; padding: 10px; cursor: pointer; font-weight: bold; >.todo < padding-left: 0; >.todo li < padding: 1em; list-style-type: none; >.todo li:not(:last-child) < border-bottom: 1px solid #000000; >.delete-button
Here’s the final output of creating a delete button in JavaScript:
Conclusion
In conclusion, this article has provided a comprehensive guide on how to create a delete button in JavaScript.
The step-by-step instructions, along with code examples, demonstrate how to set up the HTML structure, create the button element, add an event listener, remove an element from the page, and append the delete button to the container.
Additionally, the article explores an alternative method of creating a delete button for a to-do list.
By following these instructions and incorporating CSS styles, you can successfully implement a functional delete button in your web applications or websites.
We are hoping that this article provides you with enough information that helps you understand on how to create delete button in JavaScript.
Thank you for reading itsourcecoders 😊.
Delete button with confirmation — A step-by-step guide

Tutorial on how to create a delete button that transforms to «Confirm delete», on click — CSS only.
HTML
For HTML, we need a button and two elements inside. First one is span element with «CONFIRM DELETE» text, and the second one is the delete svg.
CONFIRM DELETE xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"> stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
CSS
For CSS, first we’ll style the button. We’ll set position to relative and width and height to 50×50 px, which will form a circle with border radius set to 25px.
We’ll set border to red and background to white, with a little dark box shadow. Then we’ll set cursor to pointer, overflow to hidden and transition to 300 ms.
button position: relative; width: 50px; height: 50px; border-radius: 25px; border: 2px solid rgb(231, 50, 50); background-color: #fff; cursor: pointer; box-shadow: 0 0 10px #333; overflow: hidden; transition: .3s; >
On hover, we’ll change background color to light red, increase it’s size a bit, as well as box shadow and add a little transition.
button:hover background-color: rgb(245, 207, 207); transform: scale(1.2); box-shadow: 0 0 4px #111; transition: .3s; >
Now we’ll style the delete svg. We’ll set color to the same red color as button’s border and place the element in center using absolute position with transform property. Lastly, we’ll add a little transition.
svg color: rgb(231, 50, 50); position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); transition: .3s; >
On hover, svg we’ll set opacity to 0 to svg. By adding the transition, this disappearing will be nice and smooth.
button:focus svg opacity: 0; transition: .3s; >
As for our text element inside a button, we’ll set width to 150px and place it in center (same as svg — using transform property). We’ll set opacity to zero, which means that this element won’t be seen. We’ll display it on hover (when svg is hidden). We’ll set color to red (same red as svg and button’s border), font weight to 300 and transition to 300 ms.
span width: 150px; position: absolute; opacity: 0; transform: translate(-50%, -50%); color: rgb(231, 50, 50); font-weight: 600; transition: .3s; >
On focus, we’ll set button’s width to 150px (same as text element) and height to 50 px. Also, we’ll set transition to 300 ms.
button:focus width: 150px; height: 50px; transition: .3s; >
On button focus, we’ll set opacity to one on our text element.
With transition set to 300 ms, this will appear smoothly.
button:focus span opacity: 1; transition: .3s; >