Page 1 of 1

A simple text editor in html, javascript and a tiny bit of css Rate Topic: -----

#1 Tayacan  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 145
  • View blog
  • Posts: 275
  • Joined: 18-January 11

Posted 07 September 2011 - 11:52 AM

*
POPULAR

So, today we're going to create a simple text editor. A few things before we get started:

What should we end up with?
When you're done here, hopefully you'll end up with a simple text editor that accepts three BBCode tags: , and . It will have three buttons which will add these tags to the selected tags, and a button to view the formatted text below. Not very useful alone, but a nice basis for something more complex.

What should you know?
- You should have a good grasp of how html works.
- Knowing what classes and id's are is a good idea.
- Basic css won't hurt, although the css I use here isn't really important.
- I'm not going to explain how variables work - knowing at least the basics of programming in any language should be just fine.

Other stuff:
- I'm using HTML5 for this, but the only HTML5-specific thing here is the meta tag and of course the doctype, so you can use something else.

Let's get started!

The first thing we'll want to do is create our basic html structure:
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Text editor</title>
</head>
<body>
	
	<!-- Buttons -->
	<input type="button" value="B" />
	<input type="button" value="I" />
	<input type="button" value="U" />
	<br />
	
	<!-- Text area -->
	<textarea class="text_edit" id="my_text"></textarea>
	<br />
	
	<!-- Submit button -->
	<input type="button" value="Show text" />
	
	<!-- Empty div to put the text in -->
	<div id="view_text">
	</div>

</body>
</html>



Great! We now have some buttons, a textarea in which the user can enter text, and an empty div in which we'll be putting our text once we're done formatting it. Before we go on to the javascript, let's just make it look slightly nicer with some css:

.text_edit {
	width: 500px;
	height: 300px;
	resize: none;
}

#view_text {
	width: 500px;
}


You can put it in a separate css file or inside a <style></style> tag in your html.

Next up is making the 'Show text' button work. For that we're going to use javascript, but before we get to the actual code, let's think about what we want to do for a moment.

There are two html elements involved in this - the textarea and the empty div where we want to show the text. We've given each of those an id, so we can use the javascript function document.getElementById(id). Then we need to pull the text out of the textarea, and dump it in the empty div. Somewhere in between we'll have to look for BBCode tags in the text and a few other things I'll get to in time. But for now, let's just pop the text directly into our div:

<script type="text/javascript">
	function view_text () {
		// Find html elements.
		var textArea = document.getElementById('my_text');
		var div = document.getElementById('view_text');
			
		// Put the text in a variable so we can manipulate it.
		var text = textArea.value;

		// Print the text in the div made for it.
		div.innerHTML = text;
		}
</script>



You'll want to put this within the head tag. Remember that to get the text from textarea, we have to use the value variable rather than innerHTML.

Alright, let's put this function on the 'Show text' button! Modify it like this:
<input type="button" value="Show text" onclick="view_text()" />

Clicking the button should now cause the text entered in the text area to be displayed below - try it out.

Okay, so that's all very nice, but have you tried entering more than one line? Yeah, I noticed, it doesn't make line breaks. This is because in a textarea, what you see is what you get, so when you see a newline, it's an actual newline - the \n character rather than the <br /> your browser understands. Luckily, it's not that difficult to fix. We simply have to look through our text string, which we've conveniently stored in a variable called 'text', and replace any occurrence of '\n' with '<br />':

text = text.replace(/\n/gi, "<br />");


Looks a bit cryptic? Well, don't worry, it's pretty simple once you get the hang of it.
The first parameter is /\n/gi. You see the \n, which is the character we want to replace? Well, if we remove that, we're left with / /gi. The slashes surrounds the string we're searching for, and 'gi' are some extra options. The g makes it global, so we replace all occurrences, and not just the first. The i makes it not case sensitive - just in case. The other parameter should be pretty self-explanatory.

Put this code in your view_text() function, just after the var "text = textArea.value;" line.

Ok, so now we have a text box, we have newline support - how about we make some of that fancy BBCode work, you might ask. However, before we do that, try one thing for me - put <b> and </b> around some text you enter in the textarea and see waht happens.

Oups, yes. If our user can enter html tags - ANY html tags, with attributes and all - they can pretty much ruin our site. So how about we make sure that no html tags are allowed? The easy way to do that is to simply find all occurences of < and >, like we did with the newlines, and replace them with the html values for the same characters:

// Make sure html and php tags are unusable by disabling < and >.
text = text.replace(/\</gi, "<");
text = text.replace(/\>/gi, ">");



Pop that into your function just before the other replace() - if you place it after, the < and > in <br /> will be escaped as well, and your newlines will no longer work. Also, notice that we escape the < and > with a backslash. Otherwise javascript will see them as 'lesser than' and 'greater than' symbols.

Now, at last, we get to the BBCodes. They're made with replace() as well, with [, ] and / all escaped with backslashes - it looks like this:

// Basic BBCodes.
text = text.replace(/\[b\]/gi, "<b>");
text = text.replace(/\[\/b\]/gi, "</b>");
			
text = text.replace(/\[i\]/gi, "<i>");
text = text.replace(/\[\/i\]/gi, "</i>");
			
text = text.replace(/\[u\]/gi, "<u>");
text = text.replace(/\[\/u\]/gi, "</u>");



Make sure to put it after the < and > replace(), for the same reason as with the newlines.

So, we now have a shiny text editor with some basic BBCode - how about we make those fancy buttons work so we won't have to type our tags every time?

We're going to need a new function, one we can call every time one of the buttons are clicked. This function should take the tags we want to insert as parameters. It should then insert them at the cursor, or if we have selected text, around the selection. So how do we get the selected text?

What we're going to do is we'll split the text in three parts using javascripts substr() function (http://www.w3schools.com/jsref/jsref_substr.asp). This function takes two parameters, a starting point and a length, and operates on a string. We'll split our text into everything that comes before the selection, everything that comes after, and of course the selection itself. For this purpose we'll need to know where the selection starts and ends, and for that we'll use the textArea.selectionstart and textArea.selectionend properties (replace textArea with the name of your textarea). Last of all we'll put the text back together, with the tags in between. It looks like this:

function mod_selection (val1,val2) {
	// Get the text area
	var textArea = document.getElementById('my_text');
			
	// Do we even have a selection?
	if (typeof(textArea.selectionstart) != "undefined") {
		// Split the text in three pieces - the selection, and what comes before and after.
		var begin = textArea.value.substr(0, textArea.selectionstart);
		var selection = textArea.value.substr(textArea.selectionstart, textArea.selectionend - textArea.selectionstart);
		var end = textArea.value.substr(textArea.selectionend);
		
		// Insert the tags between the three pieces of text.
		textArea.value = begin + val1 + selection + val2 + end;
	}
}


Put this function after your view_code() function, and modify the three buttons to call the function with different tags:

<input type="button" value="B" onclick="mod_selection('[b]','[/b]')" />
<input type="button" value="I" onclick="mod_selection('[i]','[/i]')" />
<input type="button" value="U" onclick="mod_selection('[u]','[/u]')" />



Now, if you try this out in Internet Explorer, you'll notice that the buttons aren't working. That's because IE selects text differently from all the other browsers. We'll have to add in some IE-specific code to deal with that:

if( -1 != navigator.userAgent.indexOf ("MSIE") ) { 
				
	var range = document.selection.createRange();
	var stored_range = range.duplicate();
	
	if(stored_range.length > 0) {
		stored_range.moveToElementText(textArea);
		stored_range.setEndPoint('EndToEnd', range);
		textArea.selectionstart = stored_range.text.length - range.text.length;
		textArea.selectionend = textArea.selectionstart + range.text.length;
	}


Put that in the top of your mod_selection() function. What it does is it calculates the start and end points of the selection in a rather cryptic way, then simply sets the two variables, selectionstart and selectionend, so IE can use them as well.

Grats, you now have a working text editor with button and all! From here, you'll have to continue on your own. be creative, and remember: Have fun!

It should look like this:

Attached Image

The final code:

<!DOCTYPE HTML>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Text editor</title>
	<link rel="stylesheet" type="text/css" href="style.css" />
	
	<script type="text/javascript">
		function view_text () {
			// Find html elements.
			var textArea = document.getElementById('my_text');
			var div = document.getElementById('view_text');
			
			// Put the text in a variable so we can manipulate it.
			var text = textArea.value;
			
			// Make sure html and php tags are unusable by disabling < and >.
			text = text.replace(/\</gi, "<");
			text = text.replace(/\>/gi, ">");
			
			// Exchange newlines for <br />
			text = text.replace(/\n/gi, "<br />");
			
			// Basic BBCodes.
			text = text.replace(/\[b\]/gi, "<b>");
			text = text.replace(/\[\/b\]/gi, "</b>");
			
			text = text.replace(/\[i\]/gi, "<i>");
			text = text.replace(/\[\/i\]/gi, "</i>");
			
			text = text.replace(/\[u\]/gi, "<u>");
			text = text.replace(/\[\/u\]/gi, "</u>");
			
			// Print the text in the div made for it.
			div.innerHTML = text;
		}
		
		function mod_selection (val1,val2) {
			// Get the text area
			var textArea = document.getElementById('my_text');
			
			// IE specific code.
			if( -1 != navigator.userAgent.indexOf ("MSIE") ) { 
				
				var range = document.selection.createRange();
				var stored_range = range.duplicate();
				
				if(stored_range.length > 0) {
					stored_range.moveToElementText(textArea);
					stored_range.setEndPoint('EndToEnd', range);
					textArea.selectionstart = stored_range.text.length - range.text.length;
					textArea.selectionend = textArea.selectionstart + range.text.length;
				}
			}
			// Do we even have a selection?
			if (typeof(textArea.selectionstart) != "undefined") {
				// Split the text in three pieces - the selection, and what comes before and after.
				var begin = textArea.value.substr(0, textArea.selectionstart);
				var selection = textArea.value.substr(textArea.selectionstart, textArea.selectionend - textArea.selectionstart);
				var end = textArea.value.substr(textArea.selectionend);
				
				// Insert the tags between the three pieces of text.
				textArea.value = begin + val1 + selection + val2 + end;
			}
		}
	</script>
	
	
</head>
<body>
	
	<!-- Knapper -->
	<input type="button" value="B" onclick="mod_selection('[b]','[/b]')" />
	<input type="button" value="I" onclick="mod_selection('[i]','[/i]')" />
	<input type="button" value="U" onclick="mod_selection('[u]','[/u]')" />
	<br />
	
	<!-- Text area -->
	<textarea class="text_edit" id="my_text"></textarea>
	<br />
	
	<!-- Submit button -->
	<input type="button" value="Show text" onclick="view_text()" />
	
	<!-- Empty div to put the text in -->
	<div id="view_text">
	</div>

</body>
</html>



Stylesheet:

.text_edit {
	width: 500px;
	height: 300px;
	resize: none;
}

#view_text {
	width: 500px;
}


This post has been edited by Tayacan: 14 September 2011 - 09:56 AM


Is This A Good Question/Topic? 7
  • +

Replies To: A simple text editor in html, javascript and a tiny bit of css

#2 Tayacan  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 145
  • View blog
  • Posts: 275
  • Joined: 18-January 11

Posted 14 September 2011 - 09:41 AM

Edit: Added a bug fix for Internet Explorer ;)
Second edit: There were a few words in the html which were in danish - if you see any strange words (or typos or other errors of that kind) let me know and I'll fix it :)

This post has been edited by Tayacan: 14 September 2011 - 09:58 AM

Was This Post Helpful? 0
  • +
  • -

#3 sas1ni69  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 85
  • View blog
  • Posts: 431
  • Joined: 04-December 08

Posted 14 September 2011 - 06:19 PM

Very nice, simple and clear :)
Was This Post Helpful? 0
  • +
  • -

#4 saimanoj  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 14
  • Joined: 19-August 10

Posted 15 September 2011 - 06:52 AM

nice idea and implementation. kudos. :)
Was This Post Helpful? 0
  • +
  • -

#5 Tayacan  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 145
  • View blog
  • Posts: 275
  • Joined: 18-January 11

Posted 15 September 2011 - 07:05 AM

Thanks, both of you :D
Was This Post Helpful? 0
  • +
  • -

#6 Creative Ginger  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 11-July 12

Posted 30 July 2012 - 05:55 AM

Hi thanks for this tutorial your instructions appeared to be really clear, however when I gave this a go and opened it in both chrome and firefox it looked right display wise, but none of the buttons were working, does this sound like a problem with the javascript? because I checked back through 3 times and it looks the same as yours :whatsthat:
Was This Post Helpful? 0
  • +
  • -

#7 mridulpv  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 05-September 10

Posted 08 October 2013 - 01:35 AM

View PostCreative Ginger, on 30 July 2012 - 05:55 AM, said:

Hi thanks for this tutorial your instructions appeared to be really clear, however when I gave this a go and opened it in both chrome and firefox it looked right display wise, but none of the buttons were working, does this sound like a problem with the javascript? because I checked back through 3 times and it looks the same as yours :whatsthat:/>

Replace "textArea.selectionstart" with "textArea.selectionstart" and "textArea.selectionend" with "textArea.selectionend"

View Postmridulpv, on 08 October 2013 - 01:30 AM, said:

View PostCreative Ginger, on 30 July 2012 - 05:55 AM, said:

Hi thanks for this tutorial your instructions appeared to be really clear, however when I gave this a go and opened it in both chrome and firefox it looked right display wise, but none of the buttons were working, does this sound like a problem with the javascript? because I checked back through 3 times and it looks the same as yours :whatsthat:/>/>

Replace "textArea.selectionstart" with "textArea.selectionstart" and "textArea.selectionend" with "textArea.selectionend"

In textArea.selectionstart letter s in start is capital letter S. In textArea.selectionend letter e in start is capital letter E.
Was This Post Helpful? 0
  • +
  • -

#8 anu18  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 09-June 14

Posted 10 June 2014 - 03:01 AM

View Postmridulpv, on 08 October 2013 - 01:35 AM, said:

View PostCreative Ginger, on 30 July 2012 - 05:55 AM, said:

Hi thanks for this tutorial your instructions appeared to be really clear, however when I gave this a go and opened it in both chrome and firefox it looked right display wise, but none of the buttons were working, does this sound like a problem with the javascript? because I checked back through 3 times and it looks the same as yours :whatsthat:/>/>

Replace "textArea.selectionstart" with "textArea.selectionstart" and "textArea.selectionend" with "textArea.selectionend"

View Postmridulpv, on 08 October 2013 - 01:30 AM, said:

View PostCreative Ginger, on 30 July 2012 - 05:55 AM, said:

Hi thanks for this tutorial your instructions appeared to be really clear, however when I gave this a go and opened it in both chrome and firefox it looked right display wise, but none of the buttons were working, does this sound like a problem with the javascript? because I checked back through 3 times and it looks the same as yours :whatsthat:/>/>/>

Replace "textArea.selectionstart" with "textArea.selectionstart" and "textArea.selectionend" with "textArea.selectionend"

In textArea.selectionstart letter s in start is capital letter S. In textArea.selectionend letter e in start is capital letter E.


even after making 's' as 'S' and 'e' as 'E' in textArea.selectionstart and textArea.selectionend respectively, the buttons are not working. please help..
Was This Post Helpful? 0
  • +
  • -

#9 codespook  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 148
  • Joined: 31-October 12

Posted 28 June 2014 - 03:26 AM

I like this too so I can keep it and build on it as I go along. Thanks.
But like the last guy, I can't get the buttons to work:( Everything shows up but when I click the button, nothing shows uop in the div after typing in the text box.

<!doctype html>
<html>
<head>
<title>Notepad</title>
<link rel="stylesheet" href="style.css">

<script type="text/javascript">
function view_text () {
var textArea = document.getElementById('my_text');
var div = document.getElementById('view_text');
var text = textArea.value;
div.innerHTML = text;
</script>


</head>

<body>


<input type="button" value="B" />
<input type="button" value="I" />
<input type="button" value="U" />
<br />
<textarea class="text_edit" id="my_text"></textarea>
<br />
<input type="button" value="Show text" onclick="view_text()" />
<div id="view_text">
</div>


</body>
</html>



Was This Post Helpful? 0
  • +
  • -

#10 andrewsw  Icon User is offline

  • It's just been revoked!
  • member icon

Reputation: 3806
  • View blog
  • Posts: 13,499
  • Joined: 12-December 12

Posted 28 June 2014 - 04:03 AM

You are missing the closing brace } for your function. There will be an error in your browser's console.

It would also be sensible to name the function differently from the div's id.
Was This Post Helpful? 1
  • +
  • -

#11 codespook  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 148
  • Joined: 31-October 12

Posted 29 June 2014 - 01:19 AM

Thakns and the rest of it works too:)
Was This Post Helpful? 0
  • +
  • -

#12 smith1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 11-December 14

Posted 11 December 2014 - 05:35 AM

I want to add list, size and color in the editor can someone help me?
Was This Post Helpful? 0
  • +
  • -

#13 andrewsw  Icon User is offline

  • It's just been revoked!
  • member icon

Reputation: 3806
  • View blog
  • Posts: 13,499
  • Joined: 12-December 12

Posted 11 December 2014 - 05:57 AM

First question: Have you studied, and do you understand, this tutorial?

Are you experienced with Javascript (and HTML/CSS)?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1