Home > other >  Dialog element from file
Dialog element from file

Time:12-13

I've been reading with interest about the dialog element in HTML:

  <dialog id="helpOnName">
    <p>
     The name is arbitrary. There is no validation, whatsoever.
    </p>
  </dialog>

So, that's well for this simple text. However, with growing complexity, I'd rather have something like

  <dialog url="helpOnName.html"></dialog>

In other words: Rather than embedding the dialog contents into the opening page, I'd like it to be read from another file.

Is that possible? How? (Using JQuery would be fine.)

CodePudding user response:

Here is another way of doing it with fetch():

document.addEventListener('DOMContentLoaded', function(ev) {
  document.querySelectorAll("[data-url]").forEach(el=>
   fetch(el.dataset.url).then(r=>r.text()).then(html=>el.innerHTML=html)
  )
});
<h3>First dialogue</h3>
<div data-url="https://baconipsum.com/api/?type=all-meat&paras=3&format=html">hello</div>
<h3>Second dialogue</h3>
<div data-url="https://baconipsum.com/api/?type=all-meat&paras=5&make-it-spicy=1&format=html">hello again</div>

CodePudding user response:

You may have different options to achieve the goal to have content loaded from an external resource.

  • Doing an ajax request that will return a response to embed dynamically in the dialog
  • Embedding the content inside an <iframe> tag
  • Referencing the content with an <object> tag

This is the demo for the third and most original option of those.

The content for the <dialog> is specified by an <object> element fed by an url having its content. As a fallback, I added the option that will override its content with a default template defined in the page itself.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object

document.addEventListener('DOMContentLoaded', ()=>{
  const dialog = document.getElementById('primaryDialog');
  fillDialogContent(dialog);
})

function fillDialogContent(dialog){  
  const template = dialog.querySelector(':scope > .fallback');  
  const content = template.content.cloneNode(true);  
  const objectEl = dialog.querySelector('object');  
  objectEl.append(content); 
}
<dialog id="primaryDialog" open>
    <object data="your-custom-dialog-content.html" type="text/html"></object>
    
    <template >
      <div >
        <p>This is the default dialog content</p>
        <p>An error occurred in the attempt to load the custom template</p>
      </div>
    </template>
    
</dialog>

  • Related