I use prism.js to display a block of code. I would like to be able to display the visual rendering of this code. So I create a button, to go from the code to the rendering, just below a div, empty to insert the code so that it is directly interpreted and displays the visual rendering. Then my code block. Something like this :
<button class="flip">See the code</button>
<div class="result"></div>
<div class="code">
<pre class="language-markup"><code class="language-markup"><script class="script" type="text/plain">
....here is my html code...
</script></code></pre>
</div>
As I have many code blocks like this, I thought using each and click functions, something like this :
$('.flip').each(function(){
$(this).on('click',function(){
var code = $(this).next('.code').html();//get the html code from the html block
var result = $(this).next('.result').text(code);// inject it in the result block
$(this).next('.code,.result').toggleClass('hide');// toggle to show code or result..
})
})
But it does nothing. Even If I target the pre tag, code or script tag, using html(), val(), or text() it doesn't work..
Any help would be appreciated..
EDIT: thanks to Swati answer it works. If I want to do the opposite, since the same code, it works, too. Here is my test :
$(".code").hide();
$('.flip').each(function(){
var code_block = $(this).nextAll('.code:first');
var preview_div = $(this).next('.result');
preview_div.html(code_block.find("code.language-markup").text()); //add your html in result div...
})
$(".flip").click(function() {
var code_block = $(this).nextAll('.code:first');
var preview_div = $(this).next('.result');
//run or show codes..block
if ($(this).text().trim() == "See the code") {
$(this).text('Run Code')
// preview_div.html(code_block.find("code.language-markup").text()); //add your html in result div...
preview_div.show();
code_block.hide();
} else {
$(this).text('See the code')
code_block.show();
preview_div.hide();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="
https://cdn.jsdelivr.net/npm/prismjs@1.29.0/prism.min.js
"></script>
<link href="
https://cdn.jsdelivr.net/npm/prismjs@1.29.0/themes/prism.min.css
" rel="stylesheet">
</head>
<body>
<button class="flip">Run Code</button>
<div class="result"></div>
<div class="code">
<pre class="language-markup">
<code class="language-markup">
<script class="script" type="text/plain">
<img src="https://i.pinimg.com/originals/1f/65/30/1f65303066ef5e14cad11da3c6eeef0d.jpg" width="50px" height="50px">
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</script>
</code>
</pre>
</div>
<button class="flip">Run Code</button>
<div class="result">
</div>
<div class="code">
<pre class="language-markup">
<code class="language-markup">
<script class="script" type="text/plain">
<p>XYZ..something <input type="text"/></p>
</script>
</code>
</pre>
</div>