One of the most needed functionality of adding interactivity with Javascript is to show or hide views on demand. Last time I showed you how to do that with Alpine JS. Today I will show you how to do the same with Vanilla Javascript (Javascript without any framework). I hope you can learn a thing with this, so let’s get started!
Complete Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vanilla js delete confirmation</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="index.css">
</head>
<body>
<div>
<button id="btn-delete" class="btn btn-danger">Delete</button>
<form id="delete-form" method="post" class="my-hidden">
Are you sure you want to delete?
<button type="submit" class="btn btn-danger">Delete</button>
<button type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
<script src="index.js"></script>
</body>
</html>
Notice that there are external CSS and Javascript. The CSS are listed below
CSS Code
.my-hidden {
display: none;
}
It’s just a hidden styling to match Alpine’s mechanism to hide views.
Javascript code
(function () {
function setHidden(el) {
el.classList.add('my-hidden');
}
function unsetHidden(el) {
el.classList.remove('my-hidden');
}
const deleteBtn = document.getElementById('btn-delete');
const deleteForm = document.getElementById('delete-form');
deleteBtn.addEventListener('click', () => {
unsetHidden(deleteForm);
});
})();
It’s very simple, some of you might even ask why do I even want to use Alpine JS for this? For the sharp viewer you might notice the code isn’t complete yet, it should set hidden when cancel is clicked. I’ll just leave it as an exercise for the reader.
Insights
Alpine JS forces us to use good design by default. Arguably, you can code Vanilla JS very well and don’t need any framework. For me however, I would say I haven’t got the knowledge to achieve Alpine JS functionality. The avantages of using Alpine are:
- It forces as to model the app with MVC architecture by designing the page data first.
- It has powerful reactivity functionality which enable us to write UI quite declaratively.
- It has powerful parsing which can hook the functionality through HTML attributes.
Up Next
That’s all folks, please email me if you have any questions. Next I will publish a full example of Alpine JS and tell you about it here in my blog. Thank you!
Alpine