Coding Challenge | Button + Modal

Whenever I come across an interesting coding challenge, I love writing a blog post about it because it provides me an opportunity to document these milestones and its a retrospective on the code itself -- what I liked and what I could have improved. For this challenge, the user clicks a button and a modal appears.





So, as with most front-end problems, there is the structure (html), the style (css) and the behavior (javascript). The structure of this challenge is very straightforward with two elements: the button and the modal (see figures above). For the target element, I used a <button> tag and for the modal, I created a wrapper <div>  and inside that, placed the modal content which includes the text and close button.

<button id="modalBtn">Open Me</button>

<div id="wrapperEl">
  <div class="modalEl">
    <span class="closeBtn">x</span>
    <p>I am a pretty modal</p>

Now, let's look at the first element. It's located at the top left corner of our browser window. The goal is to horizontally center the button in the window. In order for this button to behave the way that I have sketched,  it needs to be a block-level element.

#modalBtn {
  display: block;
  margin: auto;

The wrapper for the modal is an overlay that spans the width and height of the browser window. The content modal is a smaller rectangle that I've decided to let take up 25% of the browser window and given a fixed height of 200px. 

.wrapperEl {
  position: absolute;
  width: 100%;
  height: 100vh;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1;

.modalEl {
  background-color: #F2F2F2;
  width: 25%;
  height: 200px;
  margin: auto;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  padding: 20px;

The elements inside the modal element include a close button and some paragraph text. I've floated this close button to the right and changed its properties using a :hover pseudo-class.

.closeBtn {
  float: right;
  font-size: 1.5em;

.closeBtn:focus {
  color: #00B16A;
  font-weignt: 700;

.modalEl p {
  text-align: center;
  text-transform: uppercase;
  font-size: 35px;

Closing out the behavior part of this problem, I use vanilla javascript to grab the button and the close button, then tell it to show/hide the modal when I click the button. I also grab the modal so the program knows what it needs to show or hide.

var btn = document.getElementById('modalBtn');
var modal = document.querySelector('.wrapperEl');
var span = document.querySelector('.closeBtn');

btn.addEventListener('click', function(e){
  e.preventDefault(); = "block";

span.addEventListener('click', function(e){
  e.preventDefault(); = "none";

So there we have it, we've successfully grabbed all the elements (button tag, span tag, and wrapper element) and added event listeners to the button which will be 'clicked' to show the modal as well as the close button, which has a hover state and hides the modal when clicked.