fcc-challenges/markdown-previewer/markdownPreviewer.js

55 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-04-05 04:46:13 -07:00
marked.setOptions({
breaks: true
2020-04-05 04:46:13 -07:00
});
$(document).ready(function () {
2020-04-05 04:46:13 -07:00
/* if there is editorText in sessionStorage, load that into
* the editor, otherwise load the default text into the editor */
if (sessionStorage.hasOwnProperty("editorText")) {
$("#editor").val(sessionStorage.editorText);
2020-04-05 04:46:13 -07:00
} else {
$("#editor").val(defaultText);
}
2020-04-05 04:46:13 -07:00
// render the editor contents to the preview element
$("#preview").html(getMarkUp($("#editor").val()));
2020-04-05 04:46:13 -07:00
/* on every input event in the editor, store the editor
* contents in sessionStorage and also render the contents
* of the editor to the preview element */
$("#editor").on("input", function () {
sessionStorage.setItem("editorText", $(this).val());
$("#preview").html(getMarkUp($(this).val()));
scrollSync();
2020-04-05 04:46:13 -07:00
});
// handle eraseButton
$("#eraseButton").click(function () {
$("#editor").val("");
sessionStorage.setItem("editorText", $("#editor").val());
$("#preview").html(getMarkUp($("#editor").val()));
2020-04-05 04:46:13 -07:00
});
// handle reloadButton
$("#reloadButton").click(function () {
$("#editor").val(defaultText);
sessionStorage.setItem("editorText", defaultText);
$("#preview").html(getMarkUp(defaultText));
2020-04-05 04:46:13 -07:00
});
$("#editor").on("scroll", scrollSync);
2020-04-05 04:46:13 -07:00
});
const scrollSync = () => {
const editorScrollable = document.getElementById("editor").scrollHeight - $("#editor").height();
const previewScrollable = document.getElementById("preview").scrollHeight - $("#preview").height();
let editorScrollRatio = $("#editor").scrollTop() === 0 ? 0 : $("#editor").scrollTop() / editorScrollable;
if (editorScrollRatio > 0.90) { editorScrollRatio = 1.5; }
2020-04-05 04:46:13 -07:00
const previewScrollPosition = previewScrollable * editorScrollRatio;
$("#preview").scrollTop(previewScrollPosition);
2020-04-05 04:46:13 -07:00
};
const getMarkUp = (text) => {
return marked(text);
}