Simple web Online Editor Based on Contentditable Attribute

There are two ways to implement web online editor: one is based on iframe, the other is based on contenteditable.

Setting the contenteditable attribute for the element allows editability within the element's area.

<div class="textareaByDiv" contenteditable></div>

Set the css property of the editable area, which is written in less:

				.textareaByDiv{
					width: 1000px;
					height: 600px;
					border: 1px solid #bbb;
					padding: 10px;
					img{
						max-width: 300px;
					}
				}

Set the maximum size of img to avoid too large a picture when inserting a preview of the picture.

Next for the HTML code of the button, I used bootstrap originally, but it seems too messy to write all of them here. The style part refers to the bootstrap document to write. I only write the content related to the text editor here.

<!-- Setting Font Button Group -->
<div class="btnsGroupOfEdit">
	<ul class="dropdown-menu">
		<li><a href="javascript:;" class="editBtn" data-edittype="fontname" data-editvalue="Microsoft YaHei">Microsoft YaHei</a></li>
		<li><a href="javascript:;" class="editBtn" data-edittype="fontname" data-editvalue="KaiTi">Regular script</a></li>
	</ul>
</div>
	<!-- Button groups for setting fonts -->
<div class="btnsGroupOfEdit">
	<ul class="dropdown-menu">
		<li><a href="javascript:;" class="editBtn" data-edittype="fontsize" data-editvalue="7">Number one</a></li>
		<li><a href="javascript:;" class="editBtn" data-edittype="fontsize" data-editvalue="6">Number two</a></li>
		<li><a href="javascript:;" class="editBtn" data-edittype="fontsize" data-editvalue="5">No. three</a></li>
		<li><a href="javascript:;" class="editBtn" data-edittype="fontsize" data-editvalue="4">Number four</a></li>
		<li><a href="javascript:;" class="editBtn" data-edittype="fontsize" data-editvalue="3">Number five</a></li>
		<li><a href="javascript:;" class="editBtn" data-edittype="fontsize" data-editvalue="2">the sixth day of the month</a></li>
		<li><a href="javascript:;" class="editBtn" data-edittype="fontsize" data-editvalue="1">Number seven</a></li>
	</ul>
</div>
	<!-- Setting the color of the button group -->
<div class="btnsGroupOfEdit">
	<ul class="dropdown-menu color-drop-menu">
		<li><a href="javascript:;" class="editBtn" data-edittype="forecolor" data-editvalue="#000 "> Color 1</a></li>
		<li><a href="javascript:;" class="editBtn" data-edittype="forecolor" data-editvalue="#FF0036 "> Color 2</a></li>
		<li><a href="javascript:;" class="editBtn" data-edittype="forecolor" data-editvalue="#B5B527 "> Color 3</a></li>
		<li><a href="javascript:;" class="editBtn" data-edittype="forecolor" data-editvalue="#4F4FD9 "> Color 3</a></li>
		<li><a href="javascript:;" class="editBtn" data-edittype="forecolor" data-editvalue="#1FAF56 "> Color 4</a></li>
	</ul>
</div>

<div class="btnsGroupOfEdit">
	<button type="button" class="editBtn bold " data-edittype="bold">
		bold
	</button>
	<button type="button" class="editBtn italic" data-edittype="italic">
		Italics
	</button>
	<button type="button" class="editBtn underline" data-edittype="underline">
		Underline
	</button>
    <button type="button" class="editBtn removeFormat" data-edittype="removeformat">
      	Clear Format
    </button>
    <button type="button" class="editBtn" data-edittype="justifyleft">
    	Left alignment
	</button>
	<button type="button" class="editBtn" data-edittype="justifycenter">
		Centered
	</button>
</div>


<div class="btnsGroupOfEdit">
	<!-- When pressing the button, pop-up box input url -->
	<button type="button" class="showPopWinOfEdit">
		Insert links
	</button>
	<div class="popWinOfEdit hide">
		<input type="text" class="form-control" id="exampleInputName2" placeholder="input url">
		<button type="button" class="editBtn" data-edittype="createlink">Sure?</button>
	</div>
</div>

<div class="btnsGroupOfEdit">
	<button type="button" class="editBtn" data-edittype="formatblock" data-editvalue="<pre>"></>Insert code</button>
</div>

	<!-- Insert Picture Button -->
<button type="button" class="imgBtn">
  	<span class="glyphicon glyphicon-picture" aria-hidden="true">
  		<input type="file" id="exampleInputName2" placeholder="input url">
  	</span>
</button>

The effect of the button is as follows:

In the HTML source code of the button,

We find the button through BTNs group of Edit and editBtn, determine the operation type through data-edittype, and set the value through data-editvalue if the operation needs to be set.

We use jquery event delegation, the specific code is as follows:

	//Text editing domain
	var btnsGroupOfEdit = $('.btnsGroupOfEdit')
	var editType = null
	var editValue = null
	var editer = null
	var fileInput = btnsGroupOfEdit.find('input[type=file]')

	btnsGroupOfEdit.on('click', '.editBtn', function(event) {
		event.preventDefault();
		/* Act on the event */
		editType = $(event.currentTarget).data('edittype')

		switch(editType){
			case 'forecolor':
			case 'fontname':
			case 'fontsize':
			case 'formatblock':
				editValue = $(event.currentTarget).data('editvalue')
				console.log('emit')
				
				break
			case 'insertimage'://Picture upload is not solved here, but is solved separately in the change listening event of input below.
			case 'createlink':
				var parent = $(event.currentTarget).parents('.popWinOfEdit')
				var inputText = parent.children('input[type=text]')
				editValue = inputText.val()
				//Find the text field and focus
				var contentBox = parent.parents('.contentBox')
				editer = contentBox.find('.textareaByDiv')
				console.log(editer)
				editer.focus();
				checkPopWinOfEdit($(event.currentTarget))
				break
			default:
				editValue = null
		}
		document.execCommand(editType,false,editValue)
	});

One thing to note about jquery event delegation is that event.target is the target you actually click on and event. current target is the target you bind to. Whatever you click on, event.currrentTarget can be triggered by event bubbles, so we use event. current Target here.

Because some rich text operations have value, and some rich text operations have no value, we use swich statement to classify and process.

Because "Setting Links" will pop up a modal box for users to input url, when the modal box press the confirmation button, the modal box will disappear. The checkPopWinOfEdit() function realizes the appearance and disappearance of the modal box. The specific details of the function are as follows:

	function checkPopWinOfEdit(target){
		var parent = target.parents('.btnsGroupOfEdit')
		var popWinOfEdit = parent.children('.popWinOfEdit')
		if (popWinOfEdit.hasClass('hide')) {
			popWinOfEdit.removeClass('hide')
		}else{
			popWinOfEdit.addClass('hide')
		}
	}

In addition, bind events for the activation button of the modal box:

	showPopWinOfEdit.click(function(event) {
		/* Act on the event */
		event.stopPropagation()
		checkPopWinOfEdit($(this))
	});
For the image upload button, we use a < button > to wrap an < input type= "file". We use CSS to make the < button > style override the < input type= "file" style. When you click on it, you actually click on <input type="file". The code of CSS is very simple, so you can adjust it by yourself.~

After the picture is uploaded, the object url method is inserted into the editing field to achieve preview. For details of this section, please refer to another blog post of mine.< Using Object URL to Realize Local Preview Pictures>

The source code of the picture preview is as follows:

	//Upload Picture Preview
	//You also need to upload pictures to the background.
	fileInput.change(function(event) {
		/* Act on the event */
		var files = this.files
		var url = window.URL.createObjectURL(files[0])
		//Focus text box
		var contentBox = $(this).parents('.contentBox')
		editer = contentBox.find('.textareaByDiv')
		editer.focus();
		 if (url) {  
        	if (/image/.test(files[0].type)) {    //If the uploaded file type is image  
            	document.execCommand('insertimage',false,url)
        	}else{  
            	alert('please upload a picture!')  
        	}  
    	}else{  
        	alert('your browser doesnt support obj urls!')
    	}  
	});

Finally, a very rough web text editor is implemented! In addition to image insertion, basically all the other buttons are valid when clicked. Especially the insert code button, if clicked directly, it seems that everything behind the text field is in <pre>. For our insertion code function here, we must paste the code into the text field first, select it and edit it later.

Keywords: Javascript JQuery Attribute less

Added by NYSiRacer on Fri, 21 Jun 2019 05:12:58 +0300