javascriptlaravelfancyboxsimplemodal

How to create a fancybox from cero and append a content to it


I'm using the FancyBox library, version:5, to create modals, and everything works fine when I use the basic approach mentioned in the documentation by adding the "data-fancybox" attribute to an tag. So far, so good. Now I'm trying to create a new modal from zero depending if the session has success or not, and need to add the conten.

I've tried the following code, and it works... partially, it creates an empty modal. I can't seem to add the desired content to it. According to the documentation, I should use the setContent() function and pass it an HTMLElement.

Here's my code:

@if(session('success'))
    <script>
      // Crear el elemento div
      var modalDiv = document.createElement('div');
      modalDiv.id = 'modal';
      // Establecer el contenido del div
      modalDiv.textContent = 'Contenido del Modal';
      // Agregar el div al documento
      // document.body.appendChild(modalDiv);
      var options = {};
      var slide = {
        "isDom": false,
        "transition": false,
        "src": "#modal",
        "type": "inline",
      };
      var fancy = Fancybox.show(slide, options);
      console.dir(typeof modalDiv)
      console.dir(fancy)
      fancy.setContent(modalDiv)
    </script>
@endif

For some reason, the modalDiv variable is an object. What am I doing wrong?

By the way, I'm in a Laravel project and this code is in a blade file, although I don't think this matters too much.

Thank you in advance.


Solution

  • Here is an example of how to change the content on a slide:

    const fancyboxInstance = Fancybox.getInstance();
    const currentFancyboxSlide = Fancybox.getSlide(); 
    
    fancyboxInstance.clearContent(currentFancyboxSlide);
    fancyboxInstance.setContent(currentFancyboxSlide, "Another content", false);
    

    https://jsfiddle.net/j6hnbd4w/

    But in your case, maybe simply change contents of element having id modal.