Better way to build this snippet? Or a better chunk?

[[!Speedbump?]]

<?php
$tpl = $modx->getOption('tpl', $scriptProperties, 'default_modal');
$classTrigger = $modx->getOption('classTrigger', $scriptProperties, 'external');

$output = $modx->getChunk($tpl,array(
   'classTrigger' => $classTrigger,
));

return $output;

chunk - default_modal

<script>
const modalButton = document.querySelector(".[[+classTrigger]]");
const extra = document.createElement("div");
const modalhtml = `
<div class="modal-header">
   &#128279; You're Leaving Our Site!<span class="close-modal" onclick="closeModal()">&times</span>
</div>
<div class="modal-body">
   This is a link to an external site.<br/><br/>
   <div class="show-link"></div><br/>
   Click OK to continue to the content. Feel free to comeback again. Make Sure To Follow Instructions Properly.
</div>
<div class="modal-footer">
   <button class="close-modal" onclick="closeModal()">Close</button>
   <button class="confirm-modal">OK</>
</div>
`;
var openModal;
if (modalButton)
  {
  const getlink = modalButton.getAttribute("href");  
  modalButton.addEventListener("click", () => {
  openModal();
  });  
  openModal = function () {
  extra.classList.add("modal-content");
  extra.innerHTML = modalhtml;
  document.body.appendChild(extra);
  document.querySelector(".show-link").innerHTML = "(" + getlink + ")";  
  document.querySelector(".confirm-modal").addEventListener("click", (e) => {
    window.open(getlink, "_blank");
    extra.remove();
  });  
  };
}
function closeModal() {
  extra.remove();
}
</script>

It works, but I don’t like having the html in a script in a chuck.

Or has someone created a better solution for MODX?

You’re certainly free to do it that way, but more typically, the chunk would contain nothing but the HTML and the JS would be loaded by the snippet with one of the $modx->regClient… methods, like RegClientStartupScript.

1 Like

I assumed I would not be able to use a placeholder in a loaded script like that. It that works I will give it a shot. Thanks!

You are right. You can’t use a MODX - placeholder in a loaded script - file.
I’m not sure, why you need that placeholder at all.
Can’t you just give your modalButton onclick="openModal()" ?

1 Like

I was trying to make it more MODX like and allow the class that triggers the modal to be configurable.

I think I might settle on just using a jquery plugin and keep MODX out of it. I had seen versions for wordpress and drupal, and did not find anything for MODX.

You can’t use a placeholder in the traditional way, but you can use str_replace() to replace the placeholder and then pass the script to regClientStartupScript as a string.

2 Likes