Previewing Jquery script with live interactive effect using Javascript

Looking to create a page where a sentence can be written and displayed in a well-designed format on the right using Jquery live preview. However, currently the design only loads after writing and reloading the page. Any suggestions on how to generate the design directly upon writing?

Check out my current page here (to see the effect: write something and reload the page)
visit this updated JSFiddle by Pugazh
https://i.sstatic.net/9hkqc.jpg
Here is the JavaScript code:

$(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));
    }
}

Answer №1

When updating text content, make sure to run the wordsinblocks() function instead of just on window.pageload. Move the function call to reloadPreview to ensure it runs on text updates.

(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);
// [...]

Check out the working fiddle: https://jsfiddle.net/z0u6gtbL/3/

Answer №2

Check out the live demo here.

I think the link

http://www.o-y-o.fr/simon/writer/src/jquery.livepreview.js
serves as a cross reference.

You have the option to include the jquery.livepreview.js directly in your js file or use a local/CDN reference.

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

// Code for the LivePreview jQuery Plugin goes here

/*  Start coding below this line  */

// Additional JavaScript function
// Code for CSS styling goes here
<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>

// HTML structure for the live preview feature

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adding styles to the first and last elements of a printed page

I have created a dummy code example that generates multiple paragraph elements with some text in it. However, I need to add borders to the first and last elements to enhance the design. Here is the code snippet: <!doctype html> <html> <he ...

How can I implement BoxHelper on an Object3D containing children in Three.js?

I am exploring the possibility of using the THREE.BoxHelper to generate a bounding box for an Object3D that has children. My goal is to render a wireframe bounding box for the object while omitting diagonals on the box's faces. Upon inspecting the sou ...

The no-unused-expressions rule is triggered when an assignment or function call is expected

I'm just starting out in full stack development and I'm experimenting with coding to improve my understanding of frontend using React JS and Material UI. While working on this component, I encountered an error in the console at line 75 (this.prop ...

GET requests will not be allowed

Having an unusual issue where the GET parameters are not being passed properly. <!DOCTYPE html> <html> <body> <?php var_dump($_GET); var_dump($_POST); ?> <form action="test.php?ds=1" m ...

Executing Array.prototype.filter() results in an empty array being returned

I have a list of jQuery elements that I collected using the .siblings() method, and now I am trying to filter them. Here is the HTML code: <div> <div> <label for="username">Username</label> <input class="form ...

Exclude a specific link from a JQuery function

Check out this unique single page site that utilizes a waypoint script for navigation and highlighting nav items - The functionality works seamlessly, however, we are facing an issue where we need to modify a link to redirect to an external website. Unfor ...

Instructions on how to present a list of employee information according to the user's gender preference using a selection of three radio buttons

I have developed a view that displays a table of employees, using a json array to store their details in the component. Additionally, I have implemented 3 radio buttons: all, male, and female. My goal is to have the table show all employees when "all" is ...

Tips on extracting information from several JSON response objects

I have the following ArrayList: JSONArray JMyDataList= new JSONArray(MyDataList); JSONArray JMyProjectData = new JSONArray(MyProjectData); MyDataList: contains data retrieved from a database with column names and data. response.setConten ...

Retrieving output from a JavaScript function

When running the code, the following logs are generated: "generating my graph" myMain.js:110 "Getting credits" myMain.js:149 "debits array is 3.9,4.2,5.7,8.5,11.9,15.2,17,16.6,14.2,10.3,6.6,4.8" myMain.js:169 "Credits data = 10.7,20.5" myMain.js:156 ...

Making changes to a JSON File

I've been attempting to integrate a jQuery gantt chart into my WordPress website as a plugin. However, I've hit a roadblock when it comes to editing the data.json file. My approach involves using a PHP form to add a new item. Upon form submission ...

The issue of Next.JS fetch not caching data within the same request

I am faced with a straightforward setup where a Next.JS server-side component is responsible for fetching and displaying a post. The challenge lies in setting the page title to reflect the title of the post, requiring me to call my posts API endpoint twice ...

Morris.js tutorial: Enhancing bar charts with data labels

I have this: https://i.sstatic.net/GXjur.png But I want this instead: https://i.sstatic.net/spcS2.png Does morris.js support this feature? If not, what would be the most effective method to implement it? ...

Javascript's callback mechanism allows functions to be passed as arguments

I am currently delving into the intricacies of the callback mechanism in javascript, particularly typescript. If I have a function that expects a callback as an input argument, do I need to explicitly use a return statement to connect it with the actual ca ...

Tips for invoking the ajax method repeatedlyWould you like to learn

I am facing an issue with my ajax call. In the code snippet below, the pageReload() function is automatically triggered when the page loads, subsequently calling the ajaxCall() function every 10 seconds. I am trying to invoke a method in a Grails control ...

Is the accuracy of the in-situ convolution filter guaranteed?

After analyzing my simple box blur function, I have come to the realization that it may be incorrect. The current implementation edits the ImageData object in place, leading to convolution filters depending on surrounding pixels that have already been ch ...

Controller is not being triggered by Ajax method when there is a decimal value

I am currently working on implementing a time registration feature in my web application. Users can select the project they worked on and enter the number of hours spent on that project. Everything is functioning properly until users start adding half-hou ...

The response contains a JSON object with the values [object, Object]

I am attempting to showcase JSON data in an HTML table. Here is the code I have been using: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ ...

What is the best way to integrate a basic jQuery script into WordPress?

After reading through the Codex and various blog posts on implementing jQuery in WordPress, I find it quite frustrating. I managed to successfully load jQuery in the functions.php file, but the available guides are not very helpful as they seem to assume a ...

Displaying each character of text individually with jQuery

I am trying to display the text within a ul tag one by one when hovering over some text. However, I am encountering an error. How can I resolve this issue? You can view the code for mouseover functionality by hovering over the "hover here hover again" lin ...

What strategies can be implemented to enhance the performance of this jQuery slider?

I have successfully created an image carousel. https://i.sstatic.net/CbypXxRr.png Encountered Challenges: The last slide is displayed, but the counter shows the first slide. How can I resolve this issue? When clicking play, it continues to advance ...