Posts Tagged ‘span class

Anyone that has spent time trying to improve their click through rates (
CTR ) from search engine results pages (
SERP s) will tell you that Google algorithmically picks the snippet displayed for a given page; it’s not something you can always control. Unfortunately, Google doesn’t always display the snippet that will give you the best conversion rate.

However, the use of microformats, a set of agreed upon
HTML conventions used to describe content, can give you more control of the snippets displayed in Google
SERP s. Once your site is properly using rich snippets, you will see them also appear in your Google custom search and Google site search results, so this technique is definitely worth exploring if you use those tools as well.

The changes are easy to implement for WordPress, Magento and other software, let’s take a look at some use cases based on hReview, hCard, hProduct and XFN:

Businesses & Organizations:

Property Description
name (fn/org) The name of the business. If you use microformats, you should use both fn and org, and ensure that these have the same value.
url Link to a web page on the business’s site.
address (adr) The location of the business. Can contain the sub properties street address, locality, region, postal-code, and country-name.
tel The telephone number of the business or organization.
geo Specifies the geographical coordinates of the location. Includes two elements: latitude and longitude. Optional.

Could be marked up as follows:

<div class="vcard"> <span class="fn org">L'Amourita Pizza</span> Located at <div class="adr"> <span class="street-address">123 Main St</span>, <span class="locality">Albuquerque</span>, <span class="region">NM</span>. </div> <span class="geo"> <span class="latitude"> <span class="value-title" title="37.774929" /> </span> <span class="longitude"> <span class="value-title" title="-122.419416" /> </span> </span> Phone: <span class="tel">206-555-1234</span> <a href="http://pizza.example.com/" class="url">http://pizza.example.com</a> </div>

Learn more about the business and organization markup at webmaster central.

Products:

Property Description
brand The brand of the product for example, ACME.
category The product category for example, “Books—Fiction”, “Heavy Objects”, or “Cars”.
description Product description
name (fn) Product name
price Floating point number. Can use currency format.
photo URL of product photo
url URL of product page

Could be marked up as follows:

<div class="hproduct"> Brand: <span class="brand">ACME</span> <span class="category">Heavy objects</span> <h1 class="fn">Large all-purpose anvil</h1> On sale for <span class="price">$99.95</span>. <span class="description">If you need an object to drop from a height, the classic A23859 anvil from ACME is the way to go.</span> <a href="http://anvil.example.com" class="url">Anvil details page</a>
</div>

Becomes:

Individual Product

Learn more about the product markup at webmaster central.

People:

Property Description
name (fn) Name
nickname Nickname
photo An image link
title The person’s title (for example, Financial Manager)
role The person’s role (for example, Accountant)
url Link to a web page, such as the person’s home page
affiliation (org) The name of an organization with which the person is associated (for example, an employer). If fn and org have the exact same value, Google will interpret the information as referring to a business or organization, not a person.
friend Identifies a social relationship between the person described and another person.
contact Identifies a social relationship between the person described and another person.
acquaintance Identifies a social relationship between the person described and another person.
address (adr) The location of the person. Can have the sub properties street address, city, region, postal-code, and country-name.

Could be marked up as:

<div class="vcard"> My name is <span class="fn">Bob Smith</span>, but people call me <span class="nickname">Smithy</span>. Here is my home page: <a href="http://www.example.com" class="url">www.example.com</a>. I live in <span class="adr"> <span class="locality">Albuquerque</span>, <span class="region">NM</span> </span> and work as an <span class="title">engineer</span> at <span class="org">ACME Corp</span>. My friends: <a href="http://darryl-blog.example.com" rel="friend">Darryl</a>, <a href="http://edna-blog.example.com" rel="friend">Edna</a>
</div>

Becomes:

People

Learn more about markup for people at webmaster central.

Reviews:

Property Description
itemreviewed (item) The item being reviewed. In microformats, can contain the element name (fn).
rating A numerical quality rating for the item (for example, 4). You can indicate a rating scale by specifying best (default: 5) and worst (default: 1). More information about review ratings.
reviewer The author of the review.
dtreviewed The date that the item was reviewed in ISO date format.
description The body of the review.
summary A short summary of the review.

Could be marked up as:

<div class="hreview"> <span class="item"> <span class="fn">L’Amourita Pizza</span> </span> Reviewed by <span class="reviewer">Ulysses Grant</span> on <span class="dtreviewed"> Jan 6<span class="value-title" title="2009-01-06" /> </span>. <span class="summary">Delicious, tasty pizza on Eastlake!</span> <span class="description">L'Amourita serves up traditional wood-fired Neapolitan-style pizza, brought to your table promptly and without fuss. An ideal neighborhood pizza joint.</span> Rating: <span class="rating">4.5</span>
</div>

Learn more about markup for reviews at webmaster central.

Interested in getting started? Well there’s no reason not to start using microformats as much as possible already; semantic markup is always good for search engine optimization:

  1. Update your markup (make sure it’s valid) and use the Quix bookmarklet to check your page, by entering ’snippet’ to submit the current page to Google Rich Snippets test tool.
  2. Getting the “Insufficient data to generate the preview” error? Then make sure that there are no errors in the markup (go back to step one) or check that you are using enough data to generate the snippet preview, so check the microformat syntax again.
  3. Finally, let Google know that you’re an early adopter.

So who’s using microformats in this and other ways? Brands like Mashable, Yahoo!, Yelp, Technorati, SearchMonkey, LinkedIn, Urbanspoon and many more. If you’re interested in digging deeper into the future of microformats as they relate to web analytics as well, Dennis Mortensen from Yahoo! has a great post on what the future may hold.

Google & Microformats: Drive More Traffic is a post from Joost de Valk’s Yoast – Tweaking Websites.A good WordPress blog needs good hosting, you don’t want your blog to be slow, or, even worse, down, do you? Check out my thoughts on WordPress hosting!


Go to Source

Organizing the content of a page in a both intuitive and eye-catching manner, is a must in modern web design. One principle that has been around for some time is dividing text into tabs. This allows you to squeeze much more content in a seemingly limited space and provide a structured way of accessing it.

Today we are making an AJAX-powered tab page with CSS3 and the newly released version 1.4 of jQuery, so be sure to download the zip archive from the button above and continue with step one.

Step 1 – XHTML

As usual, we start off with the XHTML markup.

demo.html

<ul class="tabContainer">
	<!-- The jQuery generated tabs go here -->
</ul>

<div class="clear"></div>

<div id="tabContent">
	<div id="contentHolder">
		<!-- The AJAX fetched content goes here -->
	</div>
</div>

If you think the markup looks too simple to be true, you are right. As you can see, we are missing the code for the tabs, because it is inserted dynamically by jQuery on page load. This makes it extremely easy to add new tabs as you only need to add them on the JavaScript side (more on that in a moment).

demo.html

<li>
	<a href="#" class="tab green">Tab two
		<span class="left"></span>
		<span class="right"></span>
	</a>
</li>

This is the markup that is inserted by jQuery for each tab. It consists of a LI element positioned inside of the .tabContainer unordered list above, and contains a hyperlink with two spans. Those show the left and the right part of the background image and thus enable the tabs to stretch and give room for the text label inside.

Also notice the green class of the link – it determines the background, text color and hover state of the tab, as you will see in the next step of this tutorial.

Sweet AJAX-ed Tabs With jQuery 1.4 & CSS3

Sweet AJAX-ed Tabs With jQuery 1.4 & CSS3

Step 2 – CSS

With the markup in place, we can take a more detailed look at the styling of the tab page.

styles.css – Part 1

.tabContainer{
	/* The UL */
	float:right;
	padding-right:13px;
}

#contentHolder{
	background-color:#EEEEEE;
	border:2px solid #FFFFFF;
	height:300px;
	margin:20px;

	color:#444444;
	padding:15px;
}

#tabContent{
	background-color:#333;
	border:1px solid #444;
	margin-top:-15px;
	width:100%;
}

#tabContent, .tabContainer li a,#contentHolder{
	-webkit-box-shadow:0 0 2px black;
	-moz-box-shadow:0 0 2px black;
	box-shadow:0 0 2px black;
}

.tabContainer li{
	/* This will arrange the LI-s next to each other */
	display:inline;
}

.tabContainer li a,.tabContainer li a:visited{
	/* Styling the hyperlinks of the tabs as colorful buttons */

	float:left;
	font-size:18px;

	/* display:block allows for additinal CSS rules to take effect, such as paddings: */
	display:block;

	padding:7px 16px 1px;
	margin:4px 5px;
	height:29px;

	/* Giving positioning */
	position:relative;

	/* CSS3 text-shadow */
	text-shadow:1px 1px 1px #CCCCCC;
}

Here we use a number of CSS3 rules that add up to the overall feel of the page. First is the box-shadow property, which adds a shadow below the tabs, the #tabContent div and the #contentHolder.

After this we have the text-shadow property, which adds a light-colored shadow (more of a outer glow in this case), which adds an inset feel to the text of the tabs.

styles.css – Part 2

#overLine{
	/* The line above the active button. */
	position:absolute;

	height:1px;
	background-color:white;
	width:90px;

	float:left;
	left:1px;
	top:-5px;
	overflow:hidden;
}

#main{
	margin:0 auto;
	position:relative;
	width:700px;
}

ul .left{
	/* The left span in the hyperlink */

	height:37px;
	left:0;
	position:absolute;
	top:0;
	width:10px;
}

ul .right{
	/* The right span in the hyperlink */

	height:37px;
	right:0;
	position:absolute;
	top:0;
	width:10px;
}

/* Styling the colors individually: */

ul a.green{	background:url(img/green_mid.png) repeat-x top center;	color:#24570f;}
ul a.green span.left{ background:url(img/green_left.png) no-repeat left top;}
ul a.green span.right{ background:url(img/green_right.png) no-repeat right top;}

/* .. Analogical styles for the red, blue and orange color .. */

/* The hover states: */
ul a:hover{	background-position:bottom center; text-decoration:none;}
ul a:hover span.left{ background-position:left bottom;}
ul a:hover span.right{ background-position:right bottom;}

.preloader{
	display:block;
	margin:120px auto;
}

In the second part of the code, you can see that we define different backgrounds for the hyperlink and the left and right spans, depending on the color class that is assigned. This way we can successfully change a number of CSS styles and as a result have a completely different design of the tab, by just setting a different class name for the hyperlink.

The Tabs

The Tabs

Step 3 – jQuery

This is where the magic happens. First we need to include the jQuery library in the page:

demo.html

<link rel="stylesheet" type="text/css" href="styles.css" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>

We include the latest version of jQuery from Google’s CDN and immediately after it, we add our own script.js file, which contains all of our scripts.

Here is a detailed explanation of what exactly jQuery does:

  • The page is opened in a visitor’s browser and the jQuery library is downloaded from Google’s Content Depository Network;
  • $(document).ready() is queued for execution and the function that is provided as a parameter is run when the DOM has finished loading;
  • The Tabs object is looped with the $.each() method and individual <LI> elements are created and appended to the .tabContainer <UL> (covered in step one);
  • Event listeners for the click event on the tabs are set up.

You can view the code below:

script.js – Part 1

$(document).ready(function(){
	/* This code is executed after the DOM has been completely loaded */

	/* Defining an array with the tab text and AJAX pages: */

	var Tabs = {
		'Tab one'	: 'pages/page1.html',
		'Tab two'	: 'pages/page2.html',
		'Tab three'	: 'pages/page3.html',
		'Tab four'	: 'pages/page4.html'
	}

	/* The available colors for the tabs: */
	var colors = ['blue','green','red','orange'];

 	/* The colors of the line above the tab when it is active: */
	var topLineColor = {
		blue:'lightblue',
		green:'lightgreen',
		red:'red',
		orange:'orange'
	}

	/* Looping through the Tabs object: */
	var z=0;
	$.each(Tabs,function(i,j){
		/* Sequentially creating the tabs and assigning a color from the array: */

		var tmp = $('<li><a href="#" class="tab '+colors[(z++%4)]+'">'+i+' <span class="left" /><span class="right" /></a></li>');

		/* Setting the page data for each hyperlink: */

		tmp.find('a').data('page',j);

		/* Adding the tab to the UL container: */
		$('ul.tabContainer').append(tmp);
	})

The source above is the first part of script.js, which you can find in the download archive. You can add your own tabs on the page by inserting a new property to the Tabs object. The left part holds the name of the tab in single quotes, and the right part (after the semicolon) contains the AJAX URL which is going to be fetched and displayed in the #contentHolder div.

In the following second part of the script, you’ll see jQuery 1.4 in action, as we create a new div element (that acts as the line above the active tab) and pass an object with the ID and CSS properties instead of setting them separately with the .attr() and .css() methods.

script.js – Part 2

	/* Caching the tabs into a variable for better performance: */
	var the_tabs = $('.tab');

	the_tabs.click(function(e){

		/* "this" points to the clicked tab hyperlink: */
		var element = $(this);

 		/* If it is currently active, return false and exit: */
		if(element.find('#overLine').length) return false;

 		/* Detecting the color of the tab (it was added to the class attribute in the loop above): */

		var bg = element.attr('class').replace('tab ','');

 		/* Removing the line: */
		$('#overLine').remove();

 		/* Creating a new div element with jQuery 1.4 by passing an additional object parameter: */

		$('<div>',{
			id:'overLine',
			css:{
				display:'none',
				width:element.outerWidth()-2,
				background:topLineColor[bg] || 'white'
			}}).appendTo(element).fadeIn('slow');

 		/* Checking whether the AJAX fetched page has been cached: */

		if(!element.data('cache'))
		{
			/* If no cache is present, show the gif preloader and run an AJAX request: */
			$('#contentHolder').html('<img src="img/ajax_preloader.gif" width="64" height="64" class="preloader" />');

 			$.get(element.data('page'),function(msg){
				$('#contentHolder').html(msg);

 				/* After page was received, add it to the cache for the current hyperlink: */
				element.data('cache',msg);
			});
		}
		else $('#contentHolder').html(element.data('cache'));

 		e.preventDefault();
	})

	/* Emulating a click on the first tab, so that the content area is not empty: */
	the_tabs.eq(0).click();

});

Notice the use of the jQuery data() method throughout the code. It assigns arbitrary data to an element by calling the method with two parameters $(‘#selector’).data(‘label’,”String Data”). This assigns the string “String Data” to the element and we can later access it (or check if it has been set) by calling the data method without the second parameter.

This way we set up a simple caching system for the AJAX requests. The first time an AJAX call is made, the text of the response (held in the msg variable) is stored at data(‘cache’). On consecutive calls we check for this cache variable and return it instead of firing a new request. This way we remove unnecessary server load and improve the responsiveness of the tabs.

Active Tab

Active Tab

With this our sweet AJAX-ed tabs are complete!

Conclusion

Today we created AJAX – enabled colorful tabs with jQuery 1.4 and CSS3. We also implemented a simple caching mechanism using the data() method. The source code is easily modifiable and adding new tabs is as easy as adding new properties to the Tabs object.

If you liked this tutorial, be sure to follow us on twitter for early previews and interesting links from the world of web development.

What do you think? How would you improve this example?

Go to Source

Today we are making an AJAX-enabled Sticky Note management system. It will give visitors the ability to create notes with a live preview, and move them around on the screen. Every movement is going to be sent to the back-end via AJAX and saved in the database.

We are using version 1.4 of jQuery and the fancybox plugin (you can also check our CSS3 Lightbox Gallery Tutorial, where we also used fancybox).

You can download the example files and keep the demo site open in a tab so that it is easier to follow the steps of the tutorial.

Step 1 – XHTML

The first step is to create the necessary XHTML structure. The markup in the main demonstration file – demo.php is pretty straightforward, as you can see for yourself from the code below.

demo.php

<div id="main">
<a id="addButton" class="green-button" href="add_note.html">Add a note</a>

<?php echo $notes?>

</div>

It contains the main div, which holds all the notes and limits their movement during the dragging process. The rest is generated dynamically by PHP after running a SELECT query against the database, and after storing the result in the $notes variable as you will see in the next step.

If you click the “Add a note” button on the demonstration site, you will see that a form with a live preview pops up. This functionality is provided by the fancybox, which fetches add_note.html (which contains the form) and shows it within a pop-up.

add_note.html

<h3 class="popupTitle">Add a new note</h3>

<!-- The preview: -->
<div id="previewNote" class="note yellow" style="left:0;top:65px;z-index:1">
<div class="body"></div>
<div class="author"></div>
<span class="data"></span>
</div>

<div id="noteData"> <!-- Holds the form -->
<form action="" method="post" class="note-form">

<label for="note-body">Text of the note</label>
<textarea name="note-body" id="note-body" class="pr-body" cols="30" rows="6"></textarea>

<label for="note-name">Your name</label>
<input type="text" name="note-name" id="note-name" class="pr-author" value="" />

<label>Color</label> <!-- Clicking one of the divs changes the color of the preview -->
<div class="color yellow"></div>
<div class="color blue"></div>
<div class="color green"></div>

<!-- The green submit button: -->
<a id="note-submit" href="" class="green-button">Submit</a>

</form>
</div>

In the form you can fill in the text of the note, your name and choose a color. Providing a way for users to see how their note will appear in the page in real time is a useful addition which serves another practical purpose – when clicking the submit button and the lightbox window closes, the preview note is copied to the main div, which saves us from writing additional code.

Note Creation Form With Live Preview

Note Creation Form With Live Preview

Step 2 – PHP

As mentioned earlier, PHP fills the $notes variable by running a query againts the database and outputs it on the page. Lets see how this works.

demo.php

$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");

$notes = '';
$left='';
$top='';
$zindex='';
while($row=mysql_fetch_assoc($query))
{
	// The xyz column holds the position and z-index in the form 200x100x10:
	list($left,$top,$zindex) = explode('x',$row['xyz']);
	$notes.= '
		<div class="note '.$row['color'].'" style="left:'.$left.'px;top:'.$top.'px;	z-index:'.$zindex.'">
		'.htmlspecialchars($row['text']).'
		<div class="author">'.htmlspecialchars($row['name']).'</div>
		<span class="data">'.$row['id'].'</span>
	</div>';
}

The notes table not only stores the text and the author of the note, but it also has a dedicated column for the x and y coordinates, as well for the z-index (or stacking order). Those are stored in the xyz field of the table, which is updated by AJAX.

After the visitor clicks on the “Add a note” button, fancybox grabs add_note.html (which was covered in step one) and displays the live preview form. When it is submitted, the data is sent via AJAX to post.php, given below.

post.php

// Escaping the input data:
$author = mysql_real_escape_string(strip_tags($_POST['author']));
$body = mysql_real_escape_string(strip_tags($_POST['body']));
$color = mysql_real_escape_string($_POST['color']);
$zindex = (int)$_POST['zindex'];

/* Inserting a new record in the notes DB: */
mysql_query('	INSERT INTO notes (text,name,color,xyz)
VALUES ("'.$body.'","'.$author.'","'.$color.'","0x0x'.$zindex.'")');

if(mysql_affected_rows($link)==1)
{
	// Return the id of the inserted row:
	echo mysql_insert_id($link);
}
else echo '0';

After escaping all the input data and inserting it in the table, the script checks whether there were any rows affected after the insert query. If mysql_affected_rows returns 1, this would mean that the insert was successful and the automatically assigned auto_increment ID is outputted.

AJAX is also used to save the positions of the individual notes after the end of each movement. The JavaScript code that actually requests these AJAX calls is presented in step 4 of this tutorial. The PHP code is included below:

update_position.php

// Validating the input data:
if(!is_numeric($_GET['id']) || !is_numeric($_GET['x']) || !is_numeric($_GET['y']) || !is_numeric($_GET['z']))
die("0");

// Escaping:
$id = (int)$_GET['id'];
$x = (int)$_GET['x'];
$y = (int)$_GET['y'];
$z = (int)$_GET['z'];

// Saving the position and z-index of the note:
mysql_query("UPDATE notes SET xyz='".$x."x".$y."x".$z."' WHERE id=".$id);

echo "1";

After making sure that the input data is valid, the script updates the xyz field of the row for the note in question and prints 1 on success.

Lets continue with step three.

Step 3 – CSS

All the markup is in place, so it is time to throw in some fancy styling. The styles are defined in styles.css. I divided the file in three parts.

styles.css – Part 1

.note{
	height:150px;
	padding:10px;
	width:150px;
	position:absolute;
	overflow:hidden;
	cursor:move;

	font-family:Trebuchet MS,Tahoma,Myriad Pro,Arial,Verdana,sans-serif;
	font-size:22px;

	/* Adding a CSS3 shadow below the note, in the browsers which support it: */
	-moz-box-shadow:2px 2px 0 #DDDDDD;
	-webkit-box-shadow:2px 2px 0 #DDDDDD;
	box-shadow:2px 2px 0 #DDDDDD;
}

#fancy_ajax .note{ cursor:default; }

/* Three styles for the notes: */

.yellow{
	background-color:#FDFB8C;
	border:1px solid #DEDC65;
}

.blue{
	background-color:#A6E3FC;
	border:1px solid #75C5E7;
}

.green{
	background-color:#A5F88B;
	border:1px solid #98E775;
}

/* Each note has a data span, which holds its ID */
span.data{ display:none; }

/* The "Add a note" button: */
#addButton{
	position:absolute;
	top:-70px;
	left:0;
}

In the first part we define the appearance of the notes and provide three color schemes – yellow, blue and green. Those color classes are also used in the live preview form when creating a note.

Every note has special span element with a class name of data, which holds the internal ID it is assigned in the database. This ID is used by jQuery and returned with the AJAX calls back to the server in order to update the note’s position and z-index.  We are hiding this span from view with display:none.

Three Styles Of Notes

Three Styles Of Notes

styles.css – Part 2

/* Green button class: */
a.green-button,a.green-button:visited{
	color:black;
	display:block;
	font-size:10px;
	font-weight:bold;
	height:15px;
	padding:6px 5px 4px;
	text-align:center;
	width:60px;

	text-shadow:1px 1px 1px #DDDDDD;
	background:url(img/button_green.png) no-repeat left top;
}

a.green-button:hover{
	text-decoration:none;
	background-position:left bottom;
}

.author{
	/* The author name on the note: */
	bottom:10px;
	color:#666666;
	font-family:Arial,Verdana,sans-serif;
	font-size:12px;
	position:absolute;
	right:10px;
}

#main{
	/* Contains all the notes and limits their movement: */
	margin:0 auto;
	position:relative;
	width:980px;
	height:500px;
	z-index:10;
	background:url(img/add_a_note_help.gif) no-repeat left top;
}

The second part of the file defines the green button class, complete with a hover state and a CSS3 text-shadow. These are a few tiny details that may not look like much, but leave a good overall impression to the user.

styles.css – Part 3

h3.popupTitle{
	border-bottom:1px solid #DDDDDD;
	color:#666666;
	font-size:24px;
	font-weight:normal;
	padding:0 0 5px;
}

#noteData{
	/* The input form in the pop-up: */
	height:200px;
	margin:30px 0 0 200px;
	width:350px;
}

.note-form label{
	display:block;
	font-size:10px;
	font-weight:bold;
	letter-spacing:1px;
	text-transform:uppercase;
	padding-bottom:3px;
}

.note-form textarea, .note-form input[type=text]{
	background-color:#FCFCFC;
	border:1px solid #AAAAAA;
	font-family:Arial,Verdana,sans-serif;
	font-size:16px;
	height:60px;
	padding:5px;
	width:300px;
	margin-bottom:10px;
}

.note-form input[type=text]{	height:auto; }

.color{
	/* The color swatches in the form: */
	cursor:pointer;
	float:left;
	height:10px;
	margin:0 5px 0 0;
	width:10px;
}

#note-submit{	margin:20px auto; }

In the last part of styles.css, we add CSS rules for the live preview form, staring from the H3 heading and finishing with the color swatches on the bottom.

Step 4 – jQuery

jQuery manages the front-end and all of the AJAX requests. In order to be able to use the library, we first need to include a few lines to the head section of demo.php:

demo.php

<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="fancybox/jquery.fancybox-1.2.6.css" media="screen" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="fancybox/jquery.fancybox-1.2.6.pack.js"></script>

<script type="text/javascript" src="script.js"></script>

We include jQuery and jQuery UI from Google’s content repository network, as well as the rest of the css and js files needed for this tutorial. Now lets dig a bit deeper into our jQuery script.

script.js – Part 1

$(document).ready(function(){
	/* This code is executed after the DOM has been completely loaded */

	var tmp;

	$('.note').each(function(){
		/* Finding the biggest z-index value of the notes */

		tmp = $(this).css('z-index');
		if(tmp>zIndex) zIndex = tmp;
	})

	/* A helper function for converting a set of elements to draggables: */
	make_draggable($('.note'));

	/* Configuring the fancybox plugin for the "Add a note" button: */
	$("#addButton").fancybox({
		'zoomSpeedIn'		: 600,
		'zoomSpeedOut'		: 500,
		'easingIn'			: 'easeOutBack',
		'easingOut'			: 'easeInBack',
		'hideOnContentClick': false,
		'padding'			: 15
	});

	/* Listening for keyup events on fields of the "Add a note" form: */
	$('.pr-body,.pr-author').live('keyup',function(e){

		if(!this.preview)
			this.preview=$('#previewNote');

		/* Setting the text of the preview to the contents of the input field, and stripping all the HTML tags: */
		this.preview.find($(this).attr('class').replace('pr-','.')).html($(this).val().replace(/<[^>]+>/ig,''));
	});

	/* Changing the color of the preview note: */
	$('.color').live('click',function(){

		$('#previewNote').removeClass('yellow green blue').addClass($(this).attr('class').replace('color',''));
	});

First the script finds the maximum z-index value, so that it can cache it into the zIndex variable and increment it before assigning it to the notes in the beginning of every drag movement. This way, when you start dragging a note, it is moved to the top of the stack.

Another interesting moment is that we use the jQuery live() method to listen for events, instead of the regular bind(). This is so, because the page elements we are listening for events on, are created only when the form is shown and, once defined, live() event listeners are active on all elements yet to be created.

script.js – Part 2

	/* The submit button: */
	$('#note-submit').live('click',function(e){

		if($('.pr-body').val().length<4)
		{
			alert("The note text is too short!")
			return false;
		}

		if($('.pr-author').val().length<1)
		{
			alert("You haven't entered your name!")
			return false;
		}

		$(this).replaceWith('<img src="img/ajax_load.gif" style="margin:30px auto;display:block" />');

		var data = {
			'zindex'	: ++zIndex,
			'body'		: $('.pr-body').val(),
			'author'		: $('.pr-author').val(),
			'color'		: $.trim($('#previewNote').attr('class').replace('note',''))
		};

		/* Sending an AJAX POST request: */
		$.post('ajax/post.php',data,function(msg){

			if(parseInt(msg))
			{
				/* msg contains the ID of the note, assigned by MySQL's auto increment: */
				var tmp = $('#previewNote').clone();

				tmp.find('span.data').text(msg).end().css({'z-index':zIndex,top:0,left:0});
				tmp.appendTo($('#main'));

				make_draggable(tmp)
			}

			$("#addButton").fancybox.close();
		});

		e.preventDefault();
	})
});

Here we are listening for the click event on the form submit link. Once clicked, the data is validated and sent with the $.post method. If the insert was successful, the lightbox is hidden and the newly created note is added to the page. Notice that we are using the make_draggable function, which is included below.

The Note Position And Stacking Are Saved With AJAX

The Note Position And Stacking Are Saved With AJAX

script.js – Part 3

var zIndex = 0;

function make_draggable(elements)
{
	/* Elements is a jquery object: */
	elements.draggable({
		containment:'parent',
		start:function(e,ui){ ui.helper.css('z-index',++zIndex); },
		stop:function(e,ui){

			/* Sending the z-index and positon of the note to update_position.php via AJAX GET: */
			$.get('ajax/update_position.php',{
				x		: ui.position.left,
				y		: ui.position.top,
				z		: zIndex,
				id	: parseInt(ui.helper.find('span.data').html())
			});
		}
	});
}

In the last part of script.js, we have the make_draggable function. It turns a set of jQuery elements passed as a parameter into draggable objects. I’ve moved this functionality into a separate function because we need to create draggables in twice – once on initial page load, and once when we add a new note to the page.

Step 5 – MySQL

If you plan on running and building upon this demo, you’ll need to set up a working version on your server. You’ll need to execute the code from table.sql of the download archive in phpMyAdmin and fill in your database credentials in connect.php.

With this our AJAX-ed Sticky Note system is complete!

Conclusion

Today we created an Ajax Enabled Sticky Note Management System and demonstrated how we could use one of the readily available plug-ins for the jQuery library to build a dynamic interface, complete with a live preview.

What do you think? How would you improve this code?

Go to Source


About this blog

This blog delivers stylish and dynamic news for designers and web-developers on all subjects of design, ranging from: CSS, Ajax, Javascript, web design, graphics, typography, advertising & much more. Our goal is to help you communicate effectively on the web with an engaging website or functional interface.

  • Daisycakes: I dont sympathise with drug smugglers.He broke the law, besides, having bipolar wouldnt affect his v [...]
  • hdsok: This would vary by locale. The rates you mentioned would be way to high in some areas, except for v [...]
  • Yash B: The price of 8GB unlocked iPhone inPhilippines is nearly $550 - 600. The original iPhone is much dur [...]
  • AMANDA B: Being a former Progressive adjuster I can tell you that the check will be made out to the body shop [...]
  • U V: For the 2 sources, besides having similar wavelength of light, they must be COHERENT.. [...]
Web Analytics