skip to Main Content

I’m using the native HTML dialog element as a modal in my Vue 3 app and I’ve successfully displayed a button to the side/outside of the modal by using absolute positioning. However, due to the nature of dialog elements and how they’re placed in the top layer, I’m unable to trigger a click event (displayNextModal) when I click on the button outside of the dialog element. Adjusting the z-index of either element doesn’t have an effect as the dialog is always on the top layer by default. I’m wondering if there are any workarounds to this or if the only way to trigger this click event is if I put the button inside of the dialog element.

<template>
  <dialog class="modal-post" ref="postModalRef">
    <div>Modal screen</div>
  </dialog>
  <button class="next-modal-button" @click="displayNextModal">Next</button>
</template>
.modal-post {
  width: 500px;
  height: 600px;
}

.next-modal-button {
  position: absolute;
  width: 60px;
  height: 30px;
  color: black;
  top: 50%;
  right: 10px;
  z-index: 1000;
}

2

Answers


  1. Although it might not place the button in the exact spot you want, you can always set the dialog’s border and background to transparent. Then have a div inside of there that you style to look like a dialog. And have the button inside the dialog itself. That will make the button look like its outside of the dialog and still give you access to it. And you will need to mess with the sizes and absolute positioning though.

    const favDialog = document.querySelector('.modal-post');
    const showButton = document.querySelector('#showButton');
    const nextButton = document.querySelector('.next-modal-button');
    
    
    showButton.addEventListener('click', () => {
        favDialog.showModal();
    });
    
    nextButton.addEventListener('click', () => {
        console.log("NEXT");
    });
    .modal-post {
      border:0;
      background:transparent;
      height:100%
    }
    
    .next-modal-button {
      position: absolute;
      width: 60px;
      height: 30px;
      color: black;
      bottom: 20px;
      right: 10px;
      z-index: 1000;
    }
    
    .modal-body{
      background:#fff;
      border:1px solid #000;
      padding:10px;
      width: 500px;
      height: 280px;
    }
    <dialog class="modal-post" ref="postModalRef">
        <div class="modal-body">Modal screen</div>
        <button class="next-modal-button" @click="displayNextModal">Next</button>
      </dialog>  
      <button id="showButton">Show</button>
    Login or Signup to reply.
  2. Put the button inside the modal and position it from there. Make the parent relatively positioned then fine tune top and right values to get it where you want. No need to change anything else on the dialog class except position:

    .modal-post {
      position: relative;
      /* … */
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search