Facebook-Style Inline Profile Edit Fields with Ajax
This page may contain links from our sponsors. Here’s how we make money.
The standard Facebook layout is well known amongst fans of social media. Many of the dynamic form fields on the website started a huge trend of Ajax-powered backend scripts. Now we can see open source PHP developers offering examples of their code for dozens of platforms such as WordPress, Drupal, or Joomla!
In this tutorial I’d like to focus on building a simple jQuery inline edit field. We won’t store any data locally, but instead we can update the HTML data directly on the page after each edit. It’s possible to then tie into a MySQL database and store all these values as default. But for now let’s code the mere frontend functionality.
Building the Document
To first start out let me explain the document structure I’m using. I’ve got 3 separate files named index.html, style.css, and profile.js. Within the head area I’m also including an external reference to the latest jQuery 1.7.2 library.
<!doctype html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>FB-Style Inline Edit Fields</title> <meta name="author" content="Jake Rocheleau"> <link rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="profile.js"></script> </head>
Since we’re using the HTML5 doctype I try and take advantage of these additional elements. The open source html5shiv script is also an option if you’re looking to support older legacy browsers. Most of the Internet Explorer releases previous to IE9 will not support all the newer HTML5 elements. You can simply copy over the following code below your document header:
<!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]-->
Form Input Blocks
Much of the core body content is broken up into these elements. Header, footer, sections, and text blocks make up the majority of our demo layout. But more specifically we should take a quick peek at how I’m building the input areas.
I’ve got a set of div elements marked with the class “gear”. This includes some default values when you first load the page, and every time you refresh these defaults are set back again.
<div class="gear"> <label>Full Name:</label> <span id="fullname" class="datainfo">Johnny Appleseed</span> <a href="#" class="editlink">Edit Info</a> <a class="savebtn">Save</a> </div>
I’m using some other internal classes which we can target later using jQuery. Most notably the .datainfo class is applied to each span element containing the user values. Each span also has a unique ID so we can reference the correct name/value pairs.
Coding Display Styles
We should take a quick peek at some important elements inside our simple CSS stylesheet. Most of the interesting properties are set up on the edit/save buttons. For example, we need to initially hide the save buttons until a user clicks the related “edit” link.
/** @group buttons **/ .savebtn { position: absolute; right: 0; top: 13px; padding: 4px 9px; background: #5972a8; font-size: 1.2em; cursor: pointer; border: 1px solid #1a356e; color: #fff; -webkit-box-shadow: inset 0 1px 0 #8a9cc2; -moz-box-shadow: inset 0 1px 0 #8a9cc2; box-shadow: inset 0 1px 0 #8a9cc2; margin-bottom: 5px; margin-top: -5px; display: none; } .savebtn:hover { color: #fff; background: #607db7; text-decoration: none; } .savebtn:active { background: #556790; }
Many of these CSS styles are created to mimic the old Facebook buttons. The edit link is a slightly different story, but we can update those CSS properties using jQuery.
.profileinfo { background: #f2f2f2; width: 100%; padding: 4px 10px; border-left: 1px solid #b3b3b3; border-right: 1px solid #b3b3b3; border-bottom: 1px solid #b3b3b3; } .profileinfo h2 { position: relative; left: -250px; } .gear { position: relative; display: block; margin-bottom: 25px; padding-bottom: 15px; border-bottom: 1px solid #d9d9d9; } .gear a.editlink { position: absolute; right: 0; top: 13px; } .datainfo { margin-left: 10px; font-size: 11px; color: #333; } label { display: inline-block; font-weight: bold; color: #696969; font-size: 12px; width: 100px; } .hlite { background: #e2e8f6; border: 1px solid #bdc7d8; width: 250px; margin-left: -7px; padding: 4px 7px; color: #565656; font-size: 12px; }
This last bit of code takes a look at a few internal CSS classes. The .gear and label elements have special properties for displaying these input forms. I’ve set everything to display inline on the same block area, then when you hit “edit” the input field is placed right inside the same display.
DOM Script Manipulation
Understanding the basic page structure is crucial for us going into the jQuery code. You’ll want to have a plan in advance so you know how to attack the problem. With this script, I’ll just replace all the internal .datainfo with an input field where the user can edit and save changes.
$(document).ready(function(){ $(".editlink").on("click", function(e){ e.preventDefault(); var dataset = $(this).prev(".datainfo"); var savebtn = $(this).next(".savebtn"); var theid = dataset.attr("id"); var newid = theid+"-form"; var currval = dataset.text(); dataset.empty(); $('<input type="text" name="'+newid+'" id="'+newid+'" value="'+currval+'" class="hlite">').appendTo(dataset); $(this).css("display", "none"); savebtn.css("display", "block"); });
This whole function block contains the code we run every time a user clicks any of the edit links. First, we prevent the URL from loading any value in the HREF attribute. Then I’ve set up a bunch of local variables which access the .datainfo and .savebtn all inside the same gear input.
After pulling the current text value we totally erase the internal HTML using .empty(). Then I’ve constructed a basic input field with the same value as displayed inside the data info. By attaching .appendTo() onto this element I can choose any DOM container which will now store this new input field. Then obviously the last step is to hide the edit link and show the save button.
You can see this is all fairly straightforward except for one outlier. I’m not using any traditional form element or submit input button, mostly because we have no backend tied into the script. But even if we were saving to a database I’d still only use the input field, because we don’t need a full-fledged form to submit any of this data. The only reason I could see is for supporting older legacy browsers with JavaScript disabled.
Saving the User Changes
This final piece to the profile.js script contains all the code we run whenever the user hits the save button. I’ve done the same event.preventDefault() so no href value is loaded by the browser.
Some of the variables require awkward workarounds to pull the current input field value. But we store this before wiping out the input element, then add back the value as plain text. All of these commands are done inside the local .datainfo container.
$(".savebtn").on("click", function(e){ e.preventDefault(); var elink = $(this).prev(".editlink"); var dataset = elink.prev(".datainfo"); var newid = dataset.attr("id"); var cinput = "#"+newid+"-form"; var einput = $(cinput); var newval = einput.attr("value"); $(this).css("display", "none"); einput.remove(); dataset.html(newval); elink.css("display", "block"); }); });
When referencing $(this) we are now referring to the save button. So the last few lines are hiding the save button and completely removing the input field. Then we replace the input with whatever value was stored at the moment before clicking save. And lastly, we want to re-display the edit link so users can go back and make further edits if needed!
It’s all a very simple procedure once you understand the plan and how you’re tackling the whole script. It would certainly be just as easy to edit the save function with an internal .ajax() call. Then in some other PHP backend file, you can handle all the database queries without even touching any other part of the script.
Closing Thoughts
I hope this tutorial into jQuery page edits can help you understand more about DOM manipulation. You can do pretty much anything if you have enough time for coding a proper solution. And with more open-source libraries it’s easier than ever to scale functionality.
If you haven’t already seen the live demo you should try checking out the link above or download a copy of my source code. It’s very easy to go through and make custom changes on your own. Then you can implement a similar method on your website or even in future web projects. If you have any further comments or ideas feel free to share in the post discussion area below.
For more coding tutorials, please see: