django-markdownx
django-markdownx copied to clipboard
How can I init a preview / textarea dynamically after page has finished loading?
I'd like to dynamically add a markdown preview and textarea to a form. From what I can tell, the Javascript looks out for markdownx fields on DOMContentLoaded. My problem is that the inputs I'd like to dynamically insert likely take place after the DOMContentLoaded event.
Is there a way I can do this without altering the Javascript already in the project?
Right, so you want to reinitialise MarkdownX then.
Here's the code that initialises the process when DOM has loaded.
My understanding is that you want to reinitialise this, which means you want to run this part again:
docReady(() => {
const ELEMENTS = document.getElementsByClassName('markdownx');
return Object.keys(ELEMENTS).map(key => {
let element = ELEMENTS[key],
editor = element.querySelector('.markdownx-editor'),
preview = element.querySelector('.markdownx-preview');
// Only add the new MarkdownX instance to fields that have no MarkdownX instance yet.
if (!editor.hasAttribute('data-markdownx-init'))
return new MarkdownX(element, editor, preview)
});
});
I'd also like to do this. When I've tried to replicate something similar to the above I've struggled because MarkdownX isn't available globally when I import static('markdownx/js/markdownx.js') - I think this is due to the way the exports are compiled from typescript.
I've tried everything I can think of to import MarkdownX from markdownx.js into another file and can't get it to work.
~~One option could be to set "module": "es2015" or similar in the tsconfig.json but not sure if this would have knock on effects elsewhere.~~ See next comment
Just done some playing around on a fork of the repository. What worked for me to be able to import MarkdownX was to add -o markdownx to the browserify flags as part of the npm run build:js command. This adds the ability to import as markdownx, with globals.markdownx added if no other import option is available.
I found I could then include static('markdownx/js/markdownx.min.js') and use return new markdownx.MarkdownX(element, editor, preview) to initialise a markdownx field after the DOM had loaded.
I'll do a pull request for the change to the build step - but not sure if this is the right approach.
Thanks @xenatisch that approach makes sense :+1: