Search code examples
jquerypreview

How can I display a preview screen and a code screen in the same HTML block?


What I'm trying to do:

In this example(adobe design system or liquid design system) we have some components examples. Each component has a visual rendering and at the click of a button, you can see the code. What I'm trying to do, instead of unfolding a div underneath, It is to display the code block and its visual rendering in the same window.

The peculiarity is that the code blocks contain all the code from the doctype tag to the footer.

What I've tried so far

I reproduce a simplified version of this concept here:

  var html = $('#code .frame').text();
      $('#preview .frame').html(html);
    
    $('#codeBtn').on('click',function(){
        $('#preview').hide();
        $('#code').show();
      })
#code{
  display:none
}
<button id="codeBtn">grab the code</button>

<div id="preview">
 <div class="frame"></div>
</div>

<div id="code">
  <div class="frame">
    <p>hello world</p>
  </div>
</div>

So I tried within an iframe, putting the code block twice, but I can't get a satisfactory result

Any help is appreciated !


Solution

  • Ok finaly, I finaly managed to make it work.

    $('#codeBtn').on('click',function(){
            $('#preview,#code').toggleClass('hide');
          
          })
    #code{
      display:none;
    }
    #code.hide{
      display:block;
    }
    #preview.hide{display:none;}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="codeBtn">grab the code</button>
    
    <div id="preview">
      <iframe  name="frame" src="myfile.html" class="frame"></iframe>
    </div>
    
    <div id="code">
      <div class="frame">
        <p>hello world</p>
      </div>
    </div>

    The code won't work here since I'm using an iframe that's supposed to call a file. This is the only solution I have found, even if it seems a little wobbly to me. What I was looking for is something like this

    jQuery('#codeBtn').on('click',function(){
                jQuery('#preview,#code').toggleClass('hide');
              
              })
    #code{
          display:none;
        }
        #code.hide{
          display:block;
        }
        #preview.hide{display:none;}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="codeBtn">grab the code</button>
    
        <div id="preview">
        <div class="frame"><p>
        hello world
        </p></div>
        </div>
    
        <div id="code">
          <div class="frame">
            &lt;p&gt;hello world&lt;/p&gt;
          </div>
        </div>