Reputation: 1220
I am using TinyMCE and I am trying to output what the user is currently typing to a div below the TinyMCE editor. I want the user to see how there post would look like rendered.
The script I am using is this:
<script type="text/javascript">
$(function () {
$('#tinymce').keyup(function () {
$('#myDIVTag').html('<b>' + $(this).val() + '</b>');
});
});
</script>
I have placed the corresponding div in my begin form in the view:
<div id="myDIVTag">
</div>
However nothing is being rendered as I type.
Upvotes: 2
Views: 2208
Reputation: 3838
There is no fiddle, which makes thing harder - but it got pointed out in the comment that TinyMCE editor itself is hidden within <iframe>
element. This seems to be the root of the issue.
To be able to access anything within iframe
element with JavaScript, we must remember about Cross-Domain Policy. In short - if iframe has src
attribute set to another domain, and website under this source doesn't explicitly let us access its contents within iframe
- we won't be able to do it, end of the story. More: http://blog.cakemail.com/the-iframe-cross-domain-policy-problem/ .
Luckily, I'm pretty sure it won't be of any problem here - unless TinyMCE within our iframe
gets served from another domain.
Given all that, here's the snippet that should do the trick. Please alter selectors for your needs (I pointed them out with comments):
$('iframe') // iframe element
.contents()
.find('textarea') // textarea/other input *within* iframe
.keyup(function () {
$('#myDIVTag').html('<b>' + $(this).val() + '</b>');
});
EDIT:
It got suggested in the comment (thanks @charlietfl!) that the proper way to approach this problem is to use TinyMCE API event, not generic binding to textarea
element within iframe
. Here's a quick answer taking that into account:
HTML:
<textarea id="tinymce-textarea"></textarea>
<div class="text-mirror"></div>
JS:
tinymce.init({
selector: "#tinymce-textarea",
setup: function (editor) {
editor.on('change', function (e) {
var newVal = tinymce.get('tinymce-textarea').getContent();
$('.text-mirror').html(newVal);
});
}
});
JSFiddle: http://jsfiddle.net/c1zncmt8/1/ .
Basically: we're binding to TinyMCE editor "change" event, and whenever it gets triggered we get value of our input (var newVal = ...
) and put it into separate div (.text-mirror
).
Upvotes: 3