Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Create Web Text Editor using JavaScript with Editor.js

#1
Create Web Text Editor using JavaScript with Editor.js

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/10/create-web-text-editor-using-javascript-with-editor-js.jpg" width="550" height="728" title="" alt="" /></div><div><div class="modified-on" readability="7.1304347826087"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on October 20th, 2022.</div>
<p>Editor.js is a JavaScript solution to create a web text editor. It is a WYSIWYG editor that allows inline editing of web text content.</p>
<p>Online-hosted editors provide more features to create and format content in an enriched manner. The Editor.js JavaScript library helps to create our own editor in an application.</p>
<p>There are numerous online editors with advanced tools. But, having a custom editor can be sleeker to use and maintain.</p>
<p>The Editor.js has many features to embed rich text content by creating placeholders in the editor with the help of its tools. Tools are enabled by using the external libraries developed for Editor.js.</p>
<p>Those library tools enrich the capability of this web text editor plugin. The following table shows the tools enabled with this Editor.js JavaScript initiation. These tools are used to create different types of rich text content in different formats.</p>
<p>This demo allows you to experience the features of an online editor by integrating this library.</p>
<p><a class="demo" href="https://phppot.com/demo/create-web-text-editor-javascript/">View Demo</a></p>
<table class="tutorial-table">
<tbody readability="13">
<tr>
<th width="30%">Tool</th>
<th>Description</th>
</tr>
<tr readability="6">
<td>Header</td>
<td>Creates the H1, H2, H3, H4, H5 and H6 heading blocks for the web editor.</td>
</tr>
<tr readability="2">
<td>Link embeds</td>
<td>It lets pasting URL and extracts content from the link pasted into this input.</td>
</tr>
<tr readability="2">
<td>Raw HTML blocks</td>
<td>It allows embedding raw HTML codes to the web text editor.</td>
</tr>
<tr readability="3">
<td>Simple image</td>
<td>It accepts the image full path or allows to paste of copied image content to render images without server-side processing.</td>
</tr>
<tr readability="5">
<td>Image</td>
<td>It supports choosing files, pasting URLs, pasting images or dragging and dropping images to the rich text content area.</td>
</tr>
<tr readability="2">
<td>Checklist</td>
<td>It is used to create checklist items.</td>
</tr>
<tr readability="2">
<td>List</td>
<td>It adds ordered and unordered list items.</td>
</tr>
<tr readability="2">
<td>Embeds</td>
<td>It embeds content by loading iFrame to the content.</td>
</tr>
<tr readability="2">
<td>Quote</td>
<td>It creates quote blocks that have a toolbar to format rich text content and add links.</td>
</tr>
</tbody>
</table>
<p>The <a href="https://editorjs.io/getting-started" target="_blank" rel="noopener">official getting started tutorial</a> has detailed usage documentation about this JavaScript editor. The list of the above tools is described with appropriate linking to their 3-party library manual.</p>
<p><img loading="lazy" class="alignnone size-large wp-image-19795" src="https://phppot.com/wp-content/uploads/2022/10/create-web-text-editor-javascript-550x728.jpg" alt="create web text editor javascript" width="550" height="728" srcset="https://phppot.com/wp-content/uploads/2022/10/create-web-text-editor-javascript-550x728.jpg 550w, https://phppot.com/wp-content/uploads/20...27x300.jpg 227w, https://phppot.com/wp-content/uploads/20...8x1016.jpg 768w, https://phppot.com/wp-content/uploads/20...script.jpg 1000w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>How to install and initiate Editor.js</h2>
<p>The Editor.js and its libraries can be integrated by using one of the several ways listed below.</p>
<ol>
<li>Node package modules.</li>
<li>By using the available CDN URLs of this JavaScript library.</li>
<li>By including the local minified library files downloaded to the application folder.</li>
</ol>
<p>After including the required library files, the Editor.js has to be instantiated.</p>
<pre class="prettyprint"><code class="language-javascript">const editor = new EditorJS('editorjs');
</code></pre>
<p>[OR]</p>
<pre class="prettyprint"><code class="language-javascript">const editor = new EditorJS({ holder: 'editorjs'
});
</code></pre>
<p>Here, the “editorjs” is used as the holder which is referring the HTML target to render the web text editor.</p>
<h2>Fill the editor with the initial data</h2>
<p>If the editor has to display some default template, it requires creating a landing template to render into this. This web editor plugin class accepts rich text content template via a <em>data</em> property. The format will be as shown below.</p>
<pre class="prettyprint"><code>{ time: 1452714582955, blocks: [ { "type": "header", "data": { "text": "Title of the Editor", "level": 2 } } ], version: "2.10.10"
}
</code></pre>
<h2>Example: Integrate Editor.js with Raw HTML block, Image, Link embeds and more</h2>
<p>This example has the code that teaches how to configure the most used tools of the Editor.js library. It renders HTML code blocks and embeds images, and link extracts.</p>
<p>The image upload and link extract tools are configured with the server-side endpoint. It handles backend action on the upload or the extract events.</p>
<p>On saving the composing rich text content, the Editor.js data will be saved to the database. The data shown in the web editor is dynamic from the database.</p>
<pre class="prettyprint"><code class="language-php-template">&lt;?php
require_once __DIR__ . '/dbConfig.php';
$content = "''";
$sql = "SELECT * FROM editor";
$stmt = $conn-&gt;prepare($sql);
$stmt-&gt;execute();
$result = $stmt-&gt;get_result();
$row = $result-&gt;fetch_assoc();
if(!empty($row["content"])) { $content = $row["content"];
}
?&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Create Web Text Editor using JavaScript with Editor.js&lt;/title&gt;
&lt;link href="style.css" rel="stylesheet" type="text/css" /&gt;
&lt;link href="form.css" rel="stylesheet" type="text/css" /&gt;
&lt;style&gt;
#loader-icon { display: none; vertical-align: middle; width: 100px;
}
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt; &lt;div class="phppot-container"&gt; &lt;h1&gt;Create Web Text Editor using JavaScript with Editor.js&lt;/h1&gt; &lt;div id="editorjs" name="editor"&gt;&lt;/div&gt; &lt;input type="submit" onClick=save() value="save"&gt; &lt;div id="loader-icon"&gt; &lt;img src="loader.gif" id="image-size" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@editorjs/header@latest"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@editorjs/list@latest"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@editorjs/image@latest"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@editorjs/raw"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@editorjs/checklist@latest"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@editorjs/link@latest"&gt;&lt;/script&gt; &lt;script src="editor-tool.js"&gt;&lt;/script&gt; &lt;script&gt; const editor = new EditorJS({ /** * Id of Element that should contain Editor instance */ holder: 'editorjs', tools: { header: Header, list: List, raw: RawTool, image: { class: ImageTool, config: { endpoints: { byFile: 'http://localhost/phppot/javascript/create-web-text-editor-javascript/ajax-endpoint/upload.php', // Your backend file uploader endpoint byUrl: 'http://localhost/phppot/javascript/create-web-text-editor-javascript/ajax-endpoint/upload.php', // Your endpoint that provides uploading by Url } } }, checklist: { class: Checklist }, linkTool: { class: LinkTool, config: { endpoint: 'http://localhost/phppot/jquery/editorjs/extract-link-data.php', // Your backend endpoint for url data fetching, } } }, data: &lt;?php echo $row["content"]; ?&gt;, });
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>It has the ladder of six tools of Editor.js with JavaScript code. In this example, it creates images, link embeds and more types of rich text content. Some of them are basic like header, list, the default text tool and more.</p>
<p>The Image and Link embed tools depend on the PHP endpoint URL to take action on the back end.</p>
<h3>Image tool configuration keys and endpoint script</h3>
<p>The image tool requires the PHP endpoint URL to save the uploaded files to the target folder. The JavaScript editor keys to configure the endpoint are listed below.</p>
<ol>
<li>byFile – This endpoint is used while pasting the file.</li>
<li>byUrl – This endpoint is used while choosing the file, dragging and dropping files and all.</li>
</ol>
<pre class="prettyprint"><code class="language-javascript">tools: { image: { class: ImageTool, config: { endpoints: { byFile: 'http://localhost/phppot/javascript/create-web-text-editor-javascript/ajax-endpoint/upload.php', byUrl: 'http://localhost/phppot/javascript/create-web-text-editor-javascript/ajax-endpoint/upload.php' } } }
}
</code></pre>
<h3>PHP endpoint to upload file</h3>
<p>This is simple and straightforward that performs the <a href="https://phppot.com/jquery/jquery-ajax-image-upload/">image upload operation in PHP</a>. The image file is posted via JavaScript links to this server-side script.</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
$targetDir = "../uploads/";
$output = array();
if (is_array($_FILES)) { $fileName = $_FILES['image']['name']; if (is_uploaded_file($_FILES['image']['tmp_name'])) { if (move_uploaded_file($_FILES['image']['tmp_name'], $targetDir . $fileName)) { $output["success"] = 1; $output["file"]["url"] = "http://localhost/phppot/javascript/create-web-text-editor-javascript/ajax-endpoint/" . $targetDir . $fileName; } }
}
print json_encode($output);
?&gt;
</code></pre>
<h3>Extract content from link embeds</h3>
<p>This tool is configured like below to set the PHP endpoint to extract the content.</p>
<p>In this example, it extracts contents like title, image, and text description from the embedded link.</p>
<pre class="prettyprint"><code class="language-javascript">tools: { linkTool: { class: LinkTool, config: { endpoint: 'http://localhost/phppot/jquery/editorjs/extract-link-data.php', // Your backend endpoint for url data fetching, } }
}
</code></pre>
<h3>PHP endpoint to extract content from the remote file</h3>
<p>It creates a cURL post request in the endpoint <a href="https://phppot.com/php/extract-content-using-php-and-preview-like-facebook/">PHP file to extract the data from the link</a>. After getting the cURL response, the below code parses the response and creates a DOM component to render the rich text content into the WYSIWYG web editor.</p>
<p>It uses the GET method during the cURL request to extract rich text content and image from the link. In a previous tutorial, we used the <a href="https://phppot.com/php/php-curl-post/">GET and POST methods on PHP cURL requests</a>.</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
$output = array();
$ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $_GET["url"]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $data = curl_exec($ch);
curl_close($ch); $dom = new DOMDocument();
@$dom-&gt;loadHTML($data); $nodes = $dom-&gt;getElementsByTagName('title');
$title = $nodes-&gt;item(0)-&gt;nodeValue; $metas = $dom-&gt;getElementsByTagName('meta');
$body = "";
for ($i = 0; $i &lt; $metas-&gt;length; $i ++) { $meta = $metas-&gt;item($i); if ($meta-&gt;getAttribute('name') == 'description') { $body = $meta-&gt;getAttribute('content'); }
} $image_urls = array();
$images = $dom-&gt;getElementsByTagName('img'); for ($i = 0; $i &lt; $images-&gt;length; $i ++) { $image = $images-&gt;item($i); $src = $image-&gt;getAttribute('src'); if (filter_var($src, FILTER_VALIDATE_URL)) { $image_src[] = $src; }
} $output["success"] = 1;
$output["meta"]["title"] = $title;
$output["meta"]["description"] = $body;
$output["meta"]["image"]["url"] = $image_src[0];
echo json_encode($output);
?&gt;
</code></pre>
<h2>Save Editor content to the database</h2>
<p>On clicking the “Save” button below the web text editor, it gets the editor output data and saves it to the database.</p>
<p>It calls the editor.save() callback to get the WYSIWYG web editor output. An AJAX call sends this data to the PHP to store it in the database.</p>
<pre class="prettyprint"><code class="language-javascript">function save() { editor.save().then((outputData) =&gt; { document.getElementById("loader-icon").style.display = 'inline-block'; var xmlHttpRequest = new XMLHttpRequest(); xmlHttpRequest.onreadystatechange = function() { if (xmlHttpRequest.readyState == XMLHttpRequest.DONE) { document.getElementById("loader-icon").style.display = 'none'; if (xmlHttpRequest.status == 200) { // on success get the response text and // insert it into the ajax-example DIV id. document.getElementById("ajax-example").innerHTML = xmlHttpRequest.responseText; } else if (xmlHttpRequest.status == 400) { // unable to load the document alert('Status 400 error - unable to load the document.'); } else { alert('Unexpected error!'); } } }; xmlHttpRequest.open("POST", "ajax-endpoint/save-editor.php", true); xmlHttpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlHttpRequest.send("btnValue=" + JSON.stringify(outputData)); }).catch((error) =&gt; { console.log('Saving failed: ', error) });
}
</code></pre>
<h3>PHP code to save Editor.js data</h3>
<p>This is the endpoint PHP file to process the editor’s rich text output in the backend. It creates the query to prepare and execute the insert operation to save the rich text content to the database.</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
require_once __DIR__ . '/../dbConfig.php'; $sql = "SELECT * FROM editor";
$stmt = $conn-&gt;prepare($sql);
$stmt-&gt;execute();
$result = $stmt-&gt;get_result();
$row = $result-&gt;fetch_assoc();
if (isset($_POST['btnValue'])) { $editorContent = $_POST['btnValue']; if (empty($row["content"])) { $query = "INSERT INTO editor(content,created)VALUES(?, NOW())"; $statement = $conn-&gt;prepare($query); $statement-&gt;bind_param("s", $editorContent); $statement-&gt;execute(); } else { $query = "UPDATE editor SET content = ? WHERE id = ?"; $statement = $conn-&gt;prepare($query); $statement-&gt;bind_param("si", $editorContent, $row["id"]); $statement-&gt;execute(); }
}
?&gt;
</code></pre>
<p><a class="demo" href="https://phppot.com/demo/create-web-text-editor-javascript/">View Demo</a><a class="download" href="https://phppot.com/downloads/javascript/create-web-text-editor-javascript.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/javascript/create-web-text-editor-javascript/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2022/10/...editor-js/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016