Home  >  Q&A  >  body text

How can I trigger a click event when I click a button displayed outside the dialog element?

<p>I'm using a native HTML dialog element as a modal in my Vue 3 application and have successfully displayed a button to the side/outside of the modal by using absolute positioning. However, due to the nature of the dialog elements and the way they are placed on the top level, I am unable to fire the click event (displayNextModal) when I click a button outside the dialog element. Adjusting the z-index of either element has no effect because the dialog box is always on top by default. I'm wondering if there is any workaround or the only way to trigger this click event is to put the button inside the dialog element. </p> <pre class="brush:php;toolbar:false;"><template> <dialog class="modal-post" ref="postModalRef"> <div>Modal screen</div> </dialog> <button class="next-modal-button" @click="displayNextModal">Next</button> </template></pre> <pre class="brush:php;toolbar:false;">.modal-post { width: 500px; height: 600px; } .next-modal-button { position: absolute; width: 60px; height: 30px; color: black; top: 50%; right: 10px; z-index: 1000; }</pre></p>
P粉116654495P粉116654495437 days ago566

reply all(1)I'll reply

  • P粉986028039

    P粉9860280392023-09-01 18:38:39

    Although it may not place the button exactly where you want, you can always set the dialog box's borders and background to be transparent. Then inside there is a div that you set to look like a dialog box. and place the button inside the dialog itself. This will make the button appear to be outside the dialog box, but still allow you to access it. You'll need to mess with size 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>

    reply
    0
  • Cancelreply