Live HTML/CSS preview from a div tag and not a text area tag

和自甴很熟 提交于 2019-12-02 04:13:53

with no success. Is there any other addEventListener() method I can replace keyup with?

Yes, blur

If you would like to add keydown events on a <div> element, you can do the following:

First, you need to set the tabindex attribute:

<div id="a-div" tabindex="1" />

Then, (2) Bind to keydown:

 $('#mydiv').bind('keydown', function(event) {
    //console.log(event.keyCode);
 });

If you would like your div to be "focused" from the start:

$(function() {
   $('#mydiv').focus();
});

You should place your preview code it within a function, then you can simply call it once the document has loaded.

https://jsfiddle.net/michaelvinall/4053oL1x/1/

The separate issue of your preview only rendering when you press the enter key, is because of the following if statement:

if(e.which == 13 && $(this).val().length > 0)

The e.which == 13 within your if is specifying that the code within the block should only be ran if the key pressed by the user was the enter key (code 13). By removing this portion of each if statement, any key pressed will execute the code within the block:

if($(this).val().length > 0)

Your function is call when keyup is trigger, but no after page load.

You must do it : Define function to call them when 2 different event are fired.

$(function() {
        function GetHtml(){
                var html = $('.html').val();
                return html;
            }

        function GetCss(){
                var Css = $('.css').val();
                return Css;
            }

        var previewRendering = function(){
                        console.log('kikou');
            var targetp = $('#previewTarget')[0].contentWindow.document;
            targetp.open();
            targetp.close();

          var html = GetHtml();
          var css = GetCss();

          $('body',targetp).append(html);
          $('head', targetp).append('<style>' + css + '</style>');

        };

        $('.innerbox').on("keyup",function(){
                previewRendering();
            });

        $(document).ready(function() {
            previewRendering();
        });

    });

This code can not work because load event is only compatible with this list of HTML tags: body, frame, iframe, img, input type="image", link, script, style

$('.innerbox').load(function()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!