Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery live preview with javascript effect

I'm making a page where you can write a sentence, and it display well designed on the right. I use Jquery live preview.
But it seems like my design can only load itself after writing and loading again the page. Any idea of how to allow the design to be generated directly ?

Here is my page so far (to see the effect : write something and load the page again)
check this fiddle here (Updated by Pugazh)
This is what the design look like
Here is my javascript

            $(function() {
                $('textarea.source').livePreview({
                    previewElement: $('p#demo'),
                    allowedTags: ['p', 'strong', 'br', 'em', 'strike'],
                    interval: 20
                });
            });



window.onload = function wordsinblocks(self) {
    var demo = document.getElementById("demo"),
        initialText = demo.textContent,
        wordTags = initialText.split(" ").map(function(word){
          return '<span class="word">' + word + '</span>';
        });

    demo.innerHTML = wordTags.join('');
    self.disabled = true;
    fitWords();
    window.addEventListener('resize', fitWords);
}

function fitWords(){
  var demo = document.getElementById("demo"),
      width = demo.offsetWidth,
      sizes = [7.69230769230769,23.07692307692307,46.15384615384614, 100],
      calculated = sizes.map(function(size){return width*size/100}),
      node, 
      i, 
      nodeWidth,
      match,
      index;


    for (i=0;i<demo.childNodes.length;i++){
      node = demo.childNodes[i];
      node.classList.remove('size-1','size-2','size-3','size-4');

      nodeWidth = node.clientWidth;
      match = calculated.filter(function(grid){
        return grid >= nodeWidth;
      })[0];
      index = calculated.indexOf(match);


      node.classList.add( 'size-' + (index+1));
    }
}
like image 261
Yagayente Avatar asked Jan 28 '26 20:01

Yagayente


2 Answers

You run the wordsinblocks() function only on window.pageload, but you have to run them when you update the text. Just separate the function and call it on the reloadPreview.

(function($) {
    $.fn.livePreview = function(options) {
            // [...]
            textarea.reloadPreview = function() {
                // [...]
                wordsinblocks(self);
            };
            // [...]
        });
    };

   // [...]

})(jQuery);

function wordsinblocks(self) {
  var demo = document.getElementById("demo"),
      initialText = demo.textContent,
      wordTags = initialText.split(" ").map(function(word) {
        return '<span class="word">' + word + '</span>';
      });

  demo.innerHTML = wordTags.join('');
  self.disabled = true;
  fitWords();
  window.addEventListener('resize', fitWords);
}

// [...]
window.onload = wordsinblocks(self);
// [...]

Working fiddle: https://jsfiddle.net/z0u6gtbL/3/

like image 89
roNn23 Avatar answered Jan 30 '26 09:01

roNn23


Working fiddle.

I beleive http://www.o-y-o.fr/simon/writer/src/jquery.livepreview.js is a cross reference.

You can add the jquery.livepreview.js directly like below to your js or use a local/CDN reference.

/*
 * LivePreview jQuery Plugin v1.0
 *
 * Copyright (c) 2009 Phil Haack, http://haacked.com/
 * Licensed under the MIT license.
 */

(function($) {
  $.fn.livePreview = function(options) {
    var opts = $.extend({}, $.fn.livePreview.defaults, options);
    var previewMaxIndex = opts.previewElement.length - 1;

    var allowedTagsRegExp = new RegExp("&lt;(/?(" + opts.allowedTags.join("|") + ")(\\s+.*?)?)&gt;", "g");

    return this.each(function(i) {
      var textarea = $(this);
      var preview = $(opts.previewElement[Math.min(i, previewMaxIndex)]);

      textarea.handleKeyUp = function() {
        textarea.unbind('keyup', textarea.handleKeyUp);
        if (!preview.updatingPreview) {
          preview.updatingPreview = true;
          window.setTimeout(function() {
            textarea.reloadPreview()
          }, opts.interval);
        }
        return false;
      };

      textarea.htmlUnencode = function(s) {
        return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
      };

      textarea.reloadPreview = function() {
        var previewString = this.val();
        if (previewString.length > 0) {
          previewString = this.htmlUnencode(previewString);
          previewString = previewString.replace(opts.paraRegExp, "<p>$1</p><p>$2</p>");
          previewString = previewString.replace(opts.lineBreakRegExp, "$1<br />$2");
          previewString = previewString.replace(allowedTagsRegExp, "<$1>");
        }

        try {
          // Workaround for a bug in jquery 1.3.2 which is fixed in 1.4
          preview[0].innerHTML = previewString;
        } catch (e) {
          alert("Sorry, but inserting a block element within is not allowed here.");
        }

        preview.updatingPreview = false;
        this.bind('keyup', this.handleKeyUp);
      };

      textarea.reloadPreview();
    });

  };

  $.fn.livePreview.defaults = {
    paraRegExp: new RegExp("(.*)\n\n([^#*\n\n].*)", "g"),
    lineBreakRegExp: new RegExp("(.*)\n([^#*\n].*)", "g"),
    allowedTags: ['a', 'b', 'strong', 'blockquote', 'p', 'i', 'em', 'u', 'strike', 'super', 'sub', 'code'],
    interval: 80
  };

})(jQuery);


/*  Do you coding below this line  */



$(function() {
  $('textarea.source').livePreview({
    previewElement: $('p#demo'),
    allowedTags: ['p', 'strong', 'br', 'em', 'strike'],
    interval: 20
  });
});



window.onload = function wordsinblocks(self) {
  var demo = document.getElementById("demo"),
    initialText = demo.textContent,
    wordTags = initialText.split(" ").map(function(word) {
      return '<span class="word">' + word + '</span>';
    });

  demo.innerHTML = wordTags.join('');
  self.disabled = true;
  fitWords();
  window.addEventListener('resize', fitWords);
}

function fitWords() {
  var demo = document.getElementById("demo"),
    width = demo.offsetWidth,
    sizes = [7.69230769230769, 23.07692307692307, 46.15384615384614, 100],
    calculated = sizes.map(function(size) {
      return width * size / 100
    }),
    node,
    i,
    nodeWidth,
    match,
    index;


  for (i = 0; i < demo.childNodes.length; i++) {
    node = demo.childNodes[i];
    node.classList.remove('size-1', 'size-2', 'size-3', 'size-4');

    nodeWidth = node.clientWidth;
    match = calculated.filter(function(grid) {
      return grid >= nodeWidth;
    })[0];
    index = calculated.indexOf(match);


    node.classList.add('size-' + (index + 1));
  }
}
html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}
body {
  line-height: 1;
}
ol,
ul {
  list-style: none;
}
blockquote,
q {
  quotes: none;
}
blockquote:before,
blockquote:after,
q:before,
q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}
textarea {
  font-size: 2.9vw;
  font-family: "helvetica";
  resize: none;
  border: none;
}
body {
  margin: 0;
  padding: 0;
  font-size: 2.9vw;
  font-family: "helvetica";
}
h1 {
  font-family: Georgia, Times New Roman, Serif;
}
#main {
  width: 100%;
  margin: auto;
  display: table;
  float: left;
}
label {
  display: block;
  margin-top: 10px;
  margin-bottom: 4px;
}
.alltop {
  display: table;
  float: left;
  width: 100%;
  height: 2.9vw;
}
.agauche {
  display: table-cell;
  float: left;
  background-color: orange;
  width: 50%;
  height: 2.9vw;
}
.adroite {
  display: table-cell;
  float: left;
  background-color: black;
  color: orange;
  width: 50%;
  height: 2.9vw;
}
.saisi {
  width: 50%;
  display: table-cell;
  float: left;
}
.preview {
  width: 50%;
  display: table-cell;
  float: left;
  padding-top: 2.9vw;
}
.source {
  width: 100%;
  height: calc(100vh - 2.9vw);
  padding-top: 2.9vw;
}
/* Code Syntax Styles */

.csharpcode,
.csharpcode pre {
  font-size: small;
  color: black;
  font-family: Consolas, "Courier New", Courier, Monospace;
  background-color: #fff;
}
.csharpcode pre {
  margin: 0;
}
.csharpcode .rem {
  color: #008000;
}
.csharpcode .kwrd {
  color: #00f;
}
.csharpcode .str {
  color: #006080;
}
.csharpcode .op {
  color: #0000c0;
}
.csharpcode .preproc {
  color: #c63;
}
.csharpcode .asp {
  background-color: #ff0;
}
.csharpcode .html {
  color: #800000;
}
.csharpcode .attr {
  color: #f00;
}
.csharpcode .alt {
  background-color: #f4f4f4;
  width: 100%;
  margin: 0;
}
.csharpcode .lnum {
  color: #606060;
}
#demo {
  display: block;
  padding: 0 0 0 1px;
  overflow: auto;
}
#demo .word {
  float: left;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  padding: 5px;
  padding-left: 10px;
  padding-right: 10px;
  font-size: 2.9vw;
  height: 10%;
  font-family: "helvetica";
  border: 1px solid black;
}
#demo .word:hover {
  background-color: blue;
  color: white;
}
#demo .size-1 {
  width: 7.69230769230769%;
}
#demo .size-2 {
  width: 23.07692307692307%;
}
#demo .size-3 {
  width: 46.15384615384614%;
}
#demo .size-4 {
  width: 100%
}
<script src="http://www.o-y-o.fr/simon/writer/src/jquery.livepreview.js"></script>
<script src="http://code.jquery.com/jquery-1.3.2.min.js"></script>

<div class="alltop">
  <div class="agauche">

    <p style="padding-left:5px;">Write</p>
  </div>
  <div class="adroite">
    <p style="padding-left:5px;">See</p>
  </div>
</div>





<div id="main">

  <div class="saisi">
    <textarea class="source"></textarea>
  </div>


  <div class="preview">
    <p id="demo"></p>
  </div>

</div>
like image 39
Pugazh Avatar answered Jan 30 '26 09:01

Pugazh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!