Reputation: 1053
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.)
Upvotes: 0
Views: 279
Reputation: 8196
You may have different options to achieve the goal to have content loaded from an external resource.
<iframe>
tag<object>
tagThis 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.
<object>: The External Object element
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object
:scope (worth of mention)
*for selecting only starting from the direct children
https://developer.mozilla.org/en-US/docs/Web/CSS/:scope
This is an answer better covering <iframe>
<embed>
<object>
Difference between iframe, embed and object elements
And I would add I forgot to mention <link>
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 class="fallback">
<div class="container">
<p>This is the default dialog content</p>
<p>An error occurred in the attempt to load the custom template</p>
</div>
</template>
</dialog>
Upvotes: 2
Reputation: 28246
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¶s=3&format=html">hello</div>
<h3>Second dialogue</h3>
<div data-url="https://baconipsum.com/api/?type=all-meat¶s=5&make-it-spicy=1&format=html">hello again</div>
Upvotes: 0