CMS Instant Edit (1 of 3)

Let’s get into some real in depth work today. What better way to demonstrate a little of every language one might use to create internet applications than with the simple instant edit. Instant edit is more times than not is used in content management systems (CMS) to give quick edits to a site owner without having to play with code what so ever. The instant edit might seem simple at first but is a delicate build of DOM JavaScript, Ajax, PHP and MySQL. What better way to break down this topic but into these four languages.

Here is what we are going to build today.

Double click any of the following paragraphs to edit them.

Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Let’s start things off with DOM JavaScript.

Ultimately we the developers have to think about the criteria’s our instant edit is going to have to meet our simple requirements are as follows.

  • Trigger even to start text edit.
  • Trigger event to end text edit.
  • Saves to database without page refreshing.

DOM is here to help us take care of these first two requirements. DOM is a client side language that give the flexibility to edit, add, delete, and manipulate document elements. So with DOM we will create both our trigger events to start and edit our instant text edit.

In of these first two requirements we face even more requirements and they are as follows:

  • Trigger start event must take place when double clicking a specifically specified pages element.
  • Trigger end event must take place when double clicking another none specified pages element.
  • If an edit is still in progress when double clicking another specifically specified pages element we clean up our first edit and begin another.

Ok so we have a crude outline of our most basic requirement for our instant edit so now let’s think about how we are going to meet these requirements. Our trigger events would be the most logical place to start so let’s dig in.

Our first trigger event is going to take place when a user double clicks on a specified pages element. So we need to pick what element is going to be our pivoting point from no instant edit to instant edit and back again. As a web developer we have many page elements that encompass content on sites however the most common element that surrounds text would be the paragraph tags (

). So for our instant edit we will be basing our trigger events off the paragraph tags so when our user double clicks a paragraph tag our instant edit will begin or end.

Let start code!!

Start off with our blank document.





Untitled Document


%MINIFYHTML99874c664789fa6c23182a26d788f7185%%MINIFYHTML99874c664789fa6c23182a26d788f7186%%MINIFYHTML99874c664789fa6c23182a26d788f7187%

In our header add the following script tags.



Untitled Document
    %MINIFYHTML99874c664789fa6c23182a26d788f7188%

Also in your header add the following CSS.

%MINIFYHTML99874c664789fa6c23182a26d788f71818%

Now in our body add the following.

Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ok now back in your script tags lets create our first function. This function will be called the setParagrahEvent() and is our event to turn on our instant edit when double clicking a paragraph tag.

Add the following to our script tags:

function setParagrahEvent()
{
 var ps = document.getElementById('pallet').getElementsByTagName('p');
 for(var i=0;i

Ok so lets break down this function.

In our first line of this function we set a variable called “ps” that is reference or pointing rout to where our script should be looking to locate all the paragraph tags one is going to allow to be edited. Here we point the variable “ps” to first our document, then use the getElementById to traverse to our documents div container of choice and with the getElementsByTagName we point to all paragraph elements.

Our next line of code is what’s called a “for loop” and it sets a numerical variable called “i” and runs through a loop over our “ps” variable to locate all paragraph tags in our div container “pallet”.

Next line works with our “for loop” to add an ondblclick function to each found paragraph in our div container “pallet”. The function we add to each found paragraph tag is called Limit(this); and we set it to each paragraph tag to allow our script to not only find all our paragraph elements but bubble up our specifically double clicked paragraph to the top and edit only it, not the rest.

Well now that we have a function called Limit(this); floating around our paragraph tags we must write the function its self.

Add the following to our script.

function Limit(obj){
 var zxce=window.event||arguments.callee.caller.arguments[0];
 if (!zxce) var zxce=window.event;
 zxce.cancelBubble=true;
 if (zxce.stopPropagation) zxce.stopPropagation();
}

Ok this is a our limit function that receives our found paragraph tags and limits the returned or bubbled up paragraph tag we have double clicked to edit. Once our limit function has found our paragraph tag to edit we can begin to start manipulating our found paragraph tag to edit its contents.

Most likely the text our instant edit will be editing is a long line of text so its wise to use a textarea tag to be our editor for our text. Our textarea should also be unique to the whole document meaning that only one text area with a unique id should exist on the page at any time. So what we want to do is setup a condition that says if any textarea with this unique id is found do this if its not found then do other.

Here is our condition code so add it to our limit function:

var textarea = document.getElementById('currentEdit');
	 if(textarea == null)
	 {  

	 }

	 else
	 {

	 }

Here we set a new variable call textarea and its pointing to any element in our document that has an id of “currentEdit”.
Next we have an if and else conditional statement that’s set to read as, “if textarea is not found then do this, else do that“. What goes in between the else curly brackets represents if a textarea that has an id of “currentEdit” is indeed found. Everything in the if curly brackets is for if a textarea that has an id of “currentEdit” is not found.

Great lets move onto what will be our conditions for both our if and else conditional statement.

So think about this, if no textarea is found we of course want to add one, but what about our else statement? If there is a textarea found we want to remove it right, but what about if a user is trying to double click onto a second edit to end the first edit. To do such a thing we have to be prepared to add a new textarea in both our if and else statements but only in our else do we remove a old textarea before adding a new one.

Make your if and else conditions look like the following:

	 if(textarea == null)
	 {  

		 //INSERT TEXTAREA
		 var makeTextarea = document.createElement('textarea');
		 makeTextarea.setAttribute('id','currentEdit');
		 makeTextarea.style.width="100%";
		 makeTextarea.style.minWidth="100%";
		 var parentElement = obj.parentNode;
		 var nextElement = obj.nextSibling;
		 var elementsInners = obj.innerHTML;
		 makeTextarea.value = elementsInners;
		 parentElement.insertBefore(makeTextarea,nextElement);

		 //REMOVE PARAGRAPH ELEMENT
		 parentElement.removeChild(obj);
		 setParagrahEvent();
	 }

	 else
	 {

		 removeTextarea();

		 //INSERT TEXTAREA
		 var makeTextarea = document.createElement('textarea');
		 makeTextarea.setAttribute('id','currentEdit');
		 makeTextarea.style.width="100%";
		 makeTextarea.style.minWidth="100%";
		 var parentElement = obj.parentNode;
		 var nextElement = obj.nextSibling;
		 var elementsInners = obj.innerHTML;
		 makeTextarea.value = elementsInners;
		 parentElement.insertBefore(makeTextarea,nextElement);

		 //REMOVE PARAGRAPH ELEMENT
		 parentElement.removeChild(obj);
		 setParagrahEvent();
	 }

Ok calm down and we will go over each part to clear up any confusion to what we are look at here. In both our if and else statements we now have a section call “INSERT TEXTAREA” however in the else statement we have an additional “removeTextarea();” function. This removeTextarea function will be covered in a bit but its important to see this slight difference between the if and else.

Our “INSERT TEXTAREA” works like this.

  • var makeTextarea = document.createElement(‘textarea’) (New variable that creates a textarea)
  • makeTextarea.setAttribute(‘id’,’currentEdit’) (Sets this new textareas id to “currentEdit”)
  • makeTextarea.style.width=”100%”; (Sets our textarea width to be 100%)
  • makeTextarea.style.minWidth=”100%”; (Sets our textarea min-width to be 100%)
  • var parentElement = obj.parentNode; (Obj is our paragraph tag and with parentNode we travers to its parent node)
  • var nextElement = obj.nextSibling; (Sets up another varible that points to our obj paragraph tags next sibling)
  • var elementsInners = obj.innerHTML; (Here we capture our paragraphs innerHTML or text we want to edit)
  • makeTextarea.value = elementsInners; (This grabs our captured innerHTML or text and sets it into our new textarea)
  • parentElement.insertBefore(makeTextarea,nextElement); (This points to obj’s parent and inserts the textarea after our nextElement)

Ok so in a nut shell we have made a new textarea and set its id to be unique and a few styles. We then set up three new variables call parentElement nextElement and elementsInners to point to our paragraphs tags parent, next sibling and inner text. Next we use the above variables to copy our paragraphs tags inner text into our new textarea and append our new textarea to our document and after our paragraph tags.

Great but we also must remove our paragraph tags from our document so we don’t end up with our original paragraph tags and also a textarea both containing the text we would like to edit on the same page. To remove our paragraph tags we simple take a look at the other section that both our if and else statement have called “//REMOVE PARAGRAPH ELEMENT”.

//REMOVE PARAGRAPH ELEMENT
parentElement.removeChild(obj);
setParagrahEvent();

All we are doing here is again using our variable called parentElement and removing our obj variable and we also call to our setParagrahEvent(); to reinstall our double click even for find out selected paragraphs.

So our script should look like this now.

function setParagrahEvent(){
 var ps=document.getElementById('pallet').getElementsByTagName('p');
 for(var i=0;i

Ok lets move onto our removeTextarea function.

Add the following to our script:

function removeTextarea()
{
	 var textarea = document.getElementById('currentEdit');
	 var textareaInners = textarea.value; 

	 var innersLength = document.getElementById('currentEdit').value;
	 var innersLength = innersLength.replace(/ /g,"");
  var innersLength = innersLength.replace(/\n/g,""); 

	 if(innersLength.length == 0)
	 {
	 }
	 else
	 {
	 }
}

Ok our removeTextarea function first sets up two variables called textarea that points to our textarea with its unique id “currentEdit” and then our second variable called textareaInners points to our textarea’s value or rather text that may or may not be edited.

We then setup three more variables named “innerLength”. The first “innerLength” variable points to and grabs our “currentEdit’s” elements value or text. Then we setup another variable of the same name and equal it to our first variable and run a JavaScript replace function to remove all spaces. Our third and last variable is also named “innersLength and is equal to our second “innersLenght” and is also using a “replace” function to remove all carriage returns.

We then have a conditional statement that states if “innersLength.lenght” is equal to none or “0” we do this and if “innersLenght” equals any number other than 0 do that.

Its time to think about some things again. if indeed there is no text in our textarea we want to make be sure to replace that nothing with something, other wise we leave an empty paragraph tag. Add the following in the if curly brackets.

alert('Sorry but you must not remove all text!');
var makeNewP = document.createElement('p');
var getParent = textarea.parentNode;
var sibling = textarea.nextSibling;

var textareaInners = "[EMPTY]";

getParent.insertBefore(makeNewP,sibling);
makeNewP.innerHTML = textareaInners;

getParent.removeChild(textarea);
setParagrahEvent();

We first call for an alert to notify the user that they have just tried to same an empty textarea and its not allowed. Then we create four variables called makeNewP, getParent, sibling and textareaInners. Our makeNewP creates a new paragraph tag to replace our textarea while our getParent points to our textareas parent node. The sibling variable points to our textarea’s sibling and our textareaInners gets set to “[EMPTY]” to replace our nothing with something.

Ok next we use our getParent variable to inert our new paragraph element before our textarea’s sibling. We also insert the captured inner text from our textarea back into our new paragraph tag and finally remove our textarea from our document. Again we re-install our setParagrahEvent() to set us up for our next paragraph select.

Lets move onto what goes in between our else curly brackets. Add the following to your else statement.

var makeNewP = document.createElement('p');
var getParent = textarea.parentNode;
var sibling = textarea.nextSibling;

getParent.insertBefore(makeNewP,sibling);
makeNewP.innerHTML = textareaInners;

getParent.removeChild(textarea);
setParagrahEvent();

Ok this is exactly the same as our if statement but its not alerting our user about and empty textarea and instead of filling our newly created paragraph tag with “[EMPTY]” we fill it with our edited text.

Here is our compleated script

function setParagrahEvent(){
 var ps=document.getElementById('pallet').getElementsByTagName('p');
 for(var i=0;i

Ok a few things to talk about before we move on. In the above demo you can disable all occurrences of a textarea with our unique id by double clicking our body tag and we do this by adding the following to our body tag.

Last we must install our setParagraphEvent() by again adding this to our body tag.

CMS Instant Edit Part 2.

Devin R. Olsen

Located in Portland Oregon. I like to teach, share and dabble deep into the digital dark arts of web and game development.

More Posts

Follow Me:
TwitterFacebookGoogle Plus

20 Responses to “CMS Instant Edit (1 of 3)”

  1. Page Birkenhagen says:

    Awesome post. I need to start working out more.

  2. Jerrold Stsauveur says:

    thats just great

  3. Joyjit says:

    It’s truly effective

  4. Attillnot says:

    I found this site using [url=http://google.com]google.com[/url] And i want to thank you for your work. You have done really very good site. Great work, great site! Thank you!

    Sorry for offtopic

  5. Hi People
    How are you doing?

  6. Please see part 3 to this tutorial to download a completed version of the Instant Edit.

  7. manzabud says:

    can you send me this in a zip file, please?

  8. Edwin onyuro says:

    The script was very helpful thanks, i am currently developing a cms for a client to manage their website and was wondering if their are similar scripts for hyperlink management.

  9. Edwin Onyuro says:

    A life saving script thanks alot..

  10. Devin R. Olsen says:

    Giorgos – Greece, thanks for the heads up! The issue has been resolved and information here has been updated.

  11. Giorgos - Greece says:

    Thank you so much for this!

    There is a small mistake on your script:
    do…ent.getElementById(\”dataContent\”).innerHTML = myajax.responseText;

    It is \”Pallet\” no \”dataContent\”. So:
    do…ent.getElementById(\”Pallet\”).innerHTML = myajax.responseText;

  12. Leshan says:

    Amazing. Great stuff

  13. EllisGL says:

    The only thing I would like to see is some tool bar action.

  14. Devin R. Olsen says:

    Lee, sure thing and you can download the full copy here. Please be aware that you must configure the db_cnt.php file to match your local or hosted web server. Also note that I have provided a text file called SQL_TABLE_BUILD and contains a SQL statement for MySQL to build the correct table structure specific to this tutorial. Enjoy!

  15. Devin R. Olsen says:

    Hi Nadia, to edit a specific database rows with the instant edit, you must first be able to identify what row you would like to edit before hand. How this is done, is up to you. Once the row id has been identified we can pass it onto our openFromDatabase.php and use it with our saveToDatabase.php functions. First add this to your \”openDoc()\” function.

    ajaxpack.getAjaxRequest(\”openFromDatabase.php\”, \”rowId=\”+ rowId, processOpenFile, \”html\”);

    That assumes that once you have identified your desired row number to edit, and set its id number to a variable called \”rowId\”.

    Next to add the following to your saveDoc() function.

    var poststr = \”currentEdit=\” + encodeURI(currentEdit) + \”rowId=\”+ encodeURI(rowId);

    In both your saveToDatabase.php and openFromDatabase.php you set the passed varible and update the querys to only select or update our desired rows id.

    If you think it would be beneficial to write up an extension on how to preform this approach please let me know and I will certainly write up a far more detailed tutorial for the rest of my readers.

  16. Nadia says:

    Hi, I have difficulty passing the id of the record i wanna edit. where will i put this on the js so that i can pass it to the post url? Thanks, this is really nice.

  17. Lee says:

    Hey Devin, This looks great, I was wondering though if the code was vailable as a zip to follow along with rather than C

  18. milton says:

    simply amazing!

  19. Janet says:

    Thank you so much for this tutorial! I have been trying to accomplish something like this for quite some time and had no place to start.

  20. Devin R. Olsen says:

    I always enjoy feedback from my readers!

Leave a Reply