image-insert.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. function insertHtmlAtCursor(textarea, html) {
  2. const start = textarea.selectionStart;
  3. const end = textarea.selectionEnd;
  4. const before = textarea.value.substring(0, start);
  5. const after = textarea.value.substring(end);
  6. textarea.value = before + html + after;
  7. // move cursor after inserted block
  8. textarea.selectionStart = textarea.selectionEnd = start + html.length;
  9. }
  10. function insertSelectedImage() {
  11. const select = document.getElementById("imageSelect");
  12. const imageId = select.value;
  13. if (!imageId) {
  14. alert("Please select an image first.");
  15. return;
  16. }
  17. const html = `<div class="text-center">
  18. <img src="/api/v1/images/${imageId}" class="rounded img-fluid">
  19. </div>`;
  20. const textarea = document.getElementById("myTextarea");
  21. insertHtmlAtCursor(textarea, html);
  22. }
  23. function toggleDropdown(el) {
  24. const options = el.parentElement.querySelector('.options');
  25. const open = options.style.display === "block";
  26. document.querySelectorAll('.image-select .options').forEach(o => o.style.display = "none");
  27. options.style.display = open ? "none" : "block";
  28. }
  29. function chooseImage(optionEl, id) {
  30. const container = optionEl.closest('.image-select');
  31. // set visible label
  32. container.querySelector('.selected span').textContent = id;
  33. // set real select value
  34. container.querySelector('.real-select').value = id;
  35. // close dropdown
  36. container.querySelector('.options').style.display = "none";
  37. }
  38. // close dropdown when clicking outside
  39. document.addEventListener("click", function (e) {
  40. if (!e.target.closest(".image-select")) {
  41. document.querySelectorAll('.image-select .options').forEach(o => o.style.display = "none");
  42. }
  43. });
  44. function showPreview(src) {
  45. const box = document.getElementById('previewBox');
  46. box.innerHTML = `<img src="${src}">`;
  47. box.style.display = 'block';
  48. }
  49. function hidePreview() {
  50. document.getElementById('previewBox').style.display = 'none';
  51. }