Blog

How To Wrap Text Around Custom Shapes Using CSS

Web pages have always been about rectangular content blocks stacked one next to the other.

Web designers are often frustrated when their out-of-the-box creative layouts get slashed by web developers, often citing complexity and cross-browser support.

With the introduction of CSS shapes, things have changed for the better. It has become easier than ever to wrap text around custom shapes like circle, ellipse, polygon.

Web designers can play around with complex shapes in their designs. And web developers don’t have to work extra hard to get them working across browsers. Now that’s a win-win.

Let me show you how I used this approach to code some of my clients otherwise challenging layouts.

About shape-outside property
The ‘shape-outside’ property can be applied to a floated element. It controls how content will wrap around the floated element. You can pass in values to the ‘shape-outside’ property to define the shape you want the text to be reflowed. Typical values can be circle, ellipse or a polygon.

Example 1 | Used Around A Circular Image : The Spanish Art Project

Wrap text around the circular image
Wrap text around the circular image

Here is the HTML/CSS that I used to code this layout.

See the Pen wrap text around circular image by Femy Praseeth (@femkreations) on CodePen.

.element {
   float: left;
   height: 10em;
   width: 15em;
   shape-outside: circle();
}

Example 2 | Used Around An Ellipse : The Espresso Campaign

How to wrap text around custom shapes
Wrapping text around espresso cup in an ellipse shape

Here is the HTML/CSS that I used to code this layout.

See the Pen wrap text around shapes-espresso by Femy Praseeth (@femkreations) on CodePen.

NOTE:
The ellipse is defined as (rx ry at cx cy), where rx and ry are the radii for the ellipse on the X-axis and Y-axis, while cx and cy are the coordinates for the center of the ellipse.

.circle{
  float:left;
  width:225px;
  height:auto;
  margin-right:1em;
  shape-outside: ellipse(150px 150px at 20% 50%); 
}

Example 3 | Used Around A Polygon Shape

How to wrap text around custom shapes
Wrapping text around an image in a polygon shape

Here is the HTML/CSS that I used to code this layout.

See the Pen wrap text around image – polygon shape by Femy Praseeth (@femkreations) on CodePen.

NOTE:

  • The format for a polygon is (x1 y1, x2 y2, …) where you specify pairs of x y coordinates for each point of a polygon.
  • The minimum number of pairs to specify a polygon is three, a triangle.
  • You can set the coordinates of the points defining the shape in length units or percentages.
  • Using percentages keeps the polygon responsive.
.polygon-art{
  float: right;
  height: 100vh;
  width: calc(100vh + 100vh/4);
  shape-outside: polygon(80% 0, 60% 0%, 50% 100%, 5% 60%, 45% 40%);
  
}

Example 4 | Used To Create Pull Quotes

Using css shapes to create pull quote
Using css shapes to create pull quote

Here is the HTML/CSS that I used to code this layout.

See the Pen wrap text-pull quote by Femy Praseeth (@femkreations) on CodePen.

.pull-quote{
  shape-outside: content-box;
  float: left;
  width:350px;
  height:auto;
  font-size:18px;
  font-weight:bold;
  margin:0 1em 1em 0;
}

I hope you found this article interesting. I’d love to hear back from you when you try this out on your next project.

Send me a link where you used this approach to wrap text around a custom shape.

How To Feature Your Recent WordPress Posts On Home Page

With content marketing being all the rage, you are writing blog posts consistently. It’s a great user experience to display your most recent posts, right on the homepage.

Your audience will find your latest posts easily. Your home page will have a refreshed look every time new posts are put out.

Here are two examples of websites that have taken this approach.

how to display recent posts on homepage problogger
Pro blogger website showing the latest blog posts on the home page
how to display recent posts on homepage xosarah
XoSarah’s website showing the latest blog posts on the home page

So by now, you are convinced about this tactic to get your audience to your latest posts. But what if your theme doesn’t support this feature? What if you don’t want to clog your WordPress admin with yet another plugin.

Well, fret no more. I’m going to show you an easy way to get two of the recent blog posts with a featured image, to show up on the home page. With a little bit of code and a cup of hot masala chai, let’s get your latest posts on the home page. No plugins will be harmed:-)

Here is what the end result will look like.

How to feature recent posts on home page
Screenshot of two recent posts on my home page

Steps To Feature Your Recent WordPress Posts On Home Page

  1. Open the front-page.php file from your WordPress theme directory.
  2. Go to the location where you want the recent posts to be displayed in the .php file.
  3. Copy and Paste the code snippet and make the necessary changes to suit your needs and theme structure.
<?php 
/* Code snippet to feature two recent posts on home page */

//2 is the number of posts to display on the home page
$args = array( 'numberposts' => 2 ); 
$lastposts = get_posts( $args );

//change the div class based on your theme structure
echo '<div class="article-container">'; 
foreach($lastposts as $post) : setup_postdata($post); 
echo '<article>';
if (has_post_thumbnail()){ ?>

//getting the featured image of the post
<figure class="featured-image"> 
<a href="<?php echo esc_url(get_permalink());?>" rel="bookmark">
<?php the_post_thumbnail(); ?>
</a>
</figure>
<?php } ?> 

//getting the post title
<h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> 
<?php echo '</article>';
endforeach; 
echo '</div>';?>

That’s it. Your most recent posts with the featured image will be displayed on the home page.

I hope this article helped you to understand how to feature the recent posts on the home page with no plugins. I used this quick and easy method to get my recent posts on my home page and on several client projects.

I’d love to hear back from you when you try this out on your client projects.

TELL ME: What worked and what tweaks did you make to customize it for your theme?

How To Add Drop Caps To Your Website Content

What is drop cap? Have you noticed magazines have the first letter of the paragraph larger than the rest of the text and it usually spans the height of two or more lines of regular text? This first letter is called the Drop Cap.

how to add drop caps Mark Ronson screenshot
A magazine layout using drop cap (The letter C)

Why use drop caps? Drop Caps have been used in print design to mark the beginning of a new section of text. They are a great way to add visual interest to long-form content. They help to accentuate an article and bring the reader’s attention to a particular section or chapter.

You must be wondering how you can use this style in your WordPress website and blog posts. Thanks to the wonders of CSS, I’ll show you three easy ways to add drop caps to your paragraphs. For those who don’t want to mess around with code, I’ll show you a plugin alternative, as well.

Here are a few examples of websites that use drop caps to spark up their website content.

how to add drop caps jessica hische screenshot
Jessica Hische, a lettering artist using drop caps on her website
how to add drop caps nautilus screenshot
Nautilus, a popular science magazine using drop caps on their website

Four ways to add drop caps to your WordPress website

Method 1 | The Code Free Plugin way.

To apply drop caps to every post, all you have to do is go to Plugins – Add new, and search for Simple Drop Cap.

How to add drop caps- Simple Drop Cap Plugin
Simple Drop Cap Plugin

After installed and activated, you can go to Settings » Simple Drop Cap, and you will see Three Modes: Normal Mode, Float Mode, and Custom Mode. You can customize it as needed.

How to add drop caps- Simple Drop Cap Plugin Settings
Simple Drop Cap Plugin Settings

NOTE:

  • Plugins slow down your website. Hence I don’t recommend this approach for styling unless you don’t want to muck with code.

Method 2 | The CSS3 way.
If you want to turn the first letter of the first word of the first paragraph element on every WordPress post into a drop cap.

Open the style.css file and add the following css code

.post p:first-of-type:first-letter {
  font-size: 40px;
  float: left;
  margin:5px;
}

NOTE:

  • This code will work ONLY on WordPress posts where the post content is generated by the WordPress loop which adds a class ‘post’ to the div wrapping the post content.
  • This code will work even when the post has a featured image inside the post content before the first paragraph element.
  • This code will style ALL the blog post’s first paragraph elements first letter with no extra markup.
  • The drop cap text cannot be selected.

Method 3 | Manually adding a drop cap to select paragraph elements on a page.

Open the style.css file and add the following css code

p.drop:first-letter {
  font-size: 40px;
  float: left;
  margin:5px;
}

Add a class named “drop” to the paragraph element where you’d like to have the drop cap.

  <p class="drop">This paragraph will start with a drop cap.</p>

NOTE:

  • This requires a bit of extra effort to manually add the class ‘drop’ to the paragraph element to get the drop cap.
  • Gives you complete control of where in the post or page, the drop caps will appear.
  • Old blog posts and page content will need to be tweaked to show the drop caps.
  • The drop cap text cannot be selected.
  • Not supported in older browsers.

Method 4 | The cross-browser way.

Open the style.css file and add the following css code

.dropcap {
  color: #903;
  float: left;
  font-size: 75px;
  line-height: 60px;
  padding: 4px 8px 0 3px;
}

In the HTML editor, wrap the first character of the paragraph element in a span with a class dropcap.

  <p><span class="dropcap">T</span>his paragraph will start with a drop cap.<p>

NOTE:

  • This requires extra effort to manually add the span tag with the class ‘dropcap’ to the paragraph element.
  • Old blog posts will not show the drop cal unless the content is tweaked.
  • The drop cap text can be selected.
  • Works across all browsers.

Once you have the drop cap working, you can style it any which way you want. You can change the font, the drop cap color, add a background color, set a background image, change the font weight etc. For inspiration on how you can style your drop caps, check out Daily Drop Cap.

I hope this article was helpful. I’d love to hear back from you.

TELL ME: Which method did you use to style your website content for drop caps?

How To Add A Signature To All WordPress Posts

Having a custom signature at the end of your blog post adds a personal touch to your content. It’s also a great way to tie in the human element to your branding.

What can you add in your signature?

Your blog signature can be a scanned image of your actual signature. Or it can be your first name in a fancy script font. You can use a program like PicMonkey, Canva or Photoshop to save the image as a PNG or an SVG.

Eg: Fancy script font signature in Marie Forleo’s posts

How to add signature to wordpress posts- marie screenshot
Fancy script font signature in Marie Forleo’s posts

It can be your nickname in the same font as the rest of your website content.

Eg: Rebecca Tracey of Uncaged life signs of her blog posts as becca

How to add signature to wordpress posts- Uncaged screensho
Rebecca Tracey of Uncaged life signs of her blog posts as becca

You can sign off your blog posts using your branding keywords such as “Xo, Love, Warm regards’.

Eg: Jen Carrington signs off her emails and blog posts with “As always, I’m rooting for you”.

How to add signature to wordpress posts- Jen screensho
Jen Carrington signs off her emails and blog posts with “As always, I’m rooting for you”.

You can use a combination of the above to personalize your blog post.

Eg: I sign off my blog posts with “Lets geek out together” and an image of my first name.

How to add signature to wordpress posts- femKreations screensho
femKreations uses a combination of “Lets Geek out together” and her first name in fancy script font

Now that we know what to add to the signature, let’s look at how we make this happen.

By default, WordPress doesn’t have an easy way to display a signature after your blog post. I’ll show you two easy ways you can do this in WordPress.

NOTE:
This tutorial will add a signature to ALL your posts, old and new. If you have already typed in a signature in your existing posts, your posts will show two signatures. The only workaround for this is to go back to your old posts and remove all the old signatures.

I think it’s worth the effort because going forward you’re going to have a shiny signature at the end of all your posts – new and old.

Two ways to add a signature to all your WordPress posts

Method 1 | Adding a WordPress signature using a plugin.
The easy way to add a signature to all your WordPress posts without tweaking code is to use a plugin. Go to Plugins – Add new, and search for Simple Drop Cap.

To apply drop caps to every post, all you have to do is go to Plugins – Add new, and search for WP Post Signature.

How to add signature to wordpress posts- WP Post Plugin
WP Post Signature Plugin

After activating the plugin, go to Settings – WP Post Signature. You can customize the User Settings to work with your design. You can customize which posts, pages or catgories you want the signature displayed.

To add a custom image, you can add the following HTML in the first text area under User Settings.

// Replace src attribute with your website and image url details 
<img src="http:/yoursite.com/wp-content/themes/yourtheme/images/signature.png" alt="signature" />

NOTE:

  • Plugins slow down your website. Hence I don’t recommend this approach for styling unless you don’t want to muck with code.

Method 2 | Adding a WordPress signature by editing the functions.php file.

  1. Open the functions.php file from your WordPress theme directory, in your text editor.
  2. Copy and Paste the code snippet below
  3. Replace the image location with the correct URL for where you signature image is located
  4. Make any other the necessary tweaks to suit your needs and theme structure.
  5. Save and upload the functions.php to your theme directory.
/**
 * Adding signature to the blog posts.
 */
function add_signature($text) {
  global $post;
  if($post->post_type == 'post') $text .= '<p><em>Lets geek out together,</em></p>
    <p class="signature"><img src="/wp-content/themes/femscores/images/signature-femy.svg"></p>';
	return $text;
}

add_filter('the_content','add_signature');

To add a text only signature, use the following code snippet.

function add_signature($text) {
  global $post;
  if($post->post_type == 'post') $text .= '<p class="signature">As always, I am rooting for you,<br>Jen</p>';
	return $text;
}

add_filter('the_content','add_signature');

If you want to also add the signature at the end of pages and posts, you’ll add a condition to the IF statement. Replace the

if(($post->post_type == 'post'))

with

if(($post->post_type == 'post') || ($post->post_type == 'page'))

I’m signing off for now. I hope this article inspires you to create a custom signature to spruce up your posts.

TELL ME: Which method did you use to add a signature to your posts? Did you run into any issues?

How to create column layouts using css

As the monitor sizes increase, it’s not practical to have one big chunk of text on your web page that takes up the width of the screen. Users often have trouble reading long lines of text. To keep your readers interested in your content, having column layouts is a great idea.

The traditional approach to breaking the content into columns is to use floats. With the advent of responsive development, this method has become code-intensive. The new CSS3 spec has come up with an easy alternative.

Here are two websites that use the column layout to break content.

How to create column layout using css
New York Magazine using the column layout

How to create column layout using css
Time Magazine using the column layout
The CSS Properties to create the column layouts
  • column-count: The number of columns you want to apply to the element.
  • column-width: The width of a single column.
  • column-gap: The width of the gap between the columns.
  • column-rule: The shorthand for column-rule-width, column-rule-style, column-rule-color. It is similar to the border shorthand. Its specifies the border of your column.
  • column-rule-width: The width of the border of your column (similar to the one for border).
  • column-rule-style: The style of the border of your column (similar to the one for border).
  • column-rule-color: The color of the border of your column (similar to the one for border).
  • column-span: Specify a value that tells the browser how many columns you want an element to span. This is good for headings and works like colspan and rowspan in tables.

Here is a simple layout using three basic column layout CSS properties: column-count, column-width, and column-gap.

See the Pen column layout simple by Femy Praseeth (@femkreations) on CodePen.

A sampling of the code

.columns{
  column-count:3;
  column-width:25%;
  column-gap: 10%;
}

Here is a layout where the columns are styled similar to border rule. The rule column-span is applied to the child element (h1) to break the column layout for that element.

See the Pen column layout with borders and colspan by Femy Praseeth (@femkreations) on CodePen.

A sampling of the code

.column-borders{
  column-width:50%;
  column-count:2;
  column-gap:100px;
  column-rule: 1px dotted #dcdcdc;
}
.column-borders h1{
  column-span:all;
  
}

This approach is a lot simpler than using floats and doing a ton of math to make sure the layouts don’t break on various screen sizes. To verify the browser support, check out Can I Use.

I hope this article will inspire you to handle column layouts in a simpler fashion.

TELL ME: Have you used columns in your layout? Did you stick with floats or did you try the CSS3 approach?

A touch-friendly and responsive navigation menu

The startup client I was working for-Upgrademe, was launching a new web app for their educational online resource. I was specifically working on the front-end development of the web app.

Setting up the secondary navigation menu for the web app posed some challenges for the development team. Since the majority of their audience was school/college kids, it was vital to have the navigation touch-friendly, so that it functions well on tablets, ipads and other touch sensitive devices.

The key considerations when developing a touch-friendly and responsive navigation menu were:

  • Get the navigation menu to respond to tapping versus hovering.
  • Make the navigation usable on small screen space.
Screenshot of the touch-friendly responsive navigation menu

Notes:

  • Using jQuery and CSS, I build an open/close navigation menu.
  • Using media queries the navigation was made responsive.
  • Instead of using the hover on-off states to display the open/close navigation, using the jQuery events – mousedown and touchstart, to open and close the drop down menu.

The jQuery code snippet

 
$(".facetParent &gt; a").on("mousedown touchstart", function(e){
        if(!$(this).hasClass("active")) {
        	// hide any open menus and remove all other classes
        	e.preventDefault();
            $(".facetParent div").slideUp(300);
            $(".facetParent a").removeClass("active");

            // open our new menu and add the open class
            $(this).next("div").slideDown(300);
            $(this).addClass("active");
        }
        else if($(this).hasClass("active")) {
            $(this).removeClass("active");
            $(this).next("div").slideUp(300);     
        }
    });  

How to create a shadow box effect using css

By using negative z-index, pseudo elements and borders of very similar shades of a color, here is a simple and easy way to add a shadow box effect to your web page, with no images.

See the Pen shadow box effect by Femy Praseeth (@femkreations) on CodePen.

Here is the HTML/ CSS Code snippet

.box{
	position:relative;
	z-index:1;
	background:rgb(48,43,42);
}
.box:after{
	content:"";
	position:absolute;
	top:20px;
	right:20px;
	bottom:20px;
	left:20px;
	z-index: -1;
	background:rgb(39,34,34);
	border-top:1px solid rgb(32,27,27);
	border-left:1px solid rgb(32,27,27);
	border-bottom:1px solid rgb(82,71,81);
	border-right:1px solid rgb(82,71,81);
}

Did you find this trick interesting? Would you like to learn more tricks like this using CSS?
Please let me know.

A learning lifecycle map for Cisco

While working on a Cisco internal website, I got a request to create a Sales Enablement Learning Lifecycle Map – an online resource created by Cisco to assist their clients with becoming more productive, knowledgeable and competent in selling Cisco solutions. The image map has five colored 3D shapes representing the five stages of the learning lifecycle. The idea was to have a hover state when the user moves the mouse over each stage in the lifecycle map. Clicking on each of the images will take you to a page with the related stage’s details.

Learning Lifecycle Map for Cisco
Screenshot of the learning lifecycle map

Using separate images for the on-off states, playing with the opacity of the images, quite a bit of absolute positioning of the images and a dash of jQuery, I created the learning lifecycle map. The client was happy with the outcome and the learning lifecycle map was displayed on Cisco’s business page.

Steps to create a learning lifecycle map.
  • Create five separate png images for the five colored 3d shapes.
  • Create a div with five anchor tags for the five colored shapes + one for the center with the title text for the image map.
  • Use css to position the five colored shapes inside the div.
  • Use css hover states to change the opacity of the colored shapes.
  • Use jquery animate to change the position of the colored shapes and the opacity.

The html used to setup the donut.

<div id="graphic">
          <p class="image"><a class="img1 off" href="http://cisco.cvent.com/events/the-sell/custom-20-95a683ee1c5b4f86aff4929040e12de0.aspx" style="opacity: 1; top: 0px;"><span></span></a></p>
          <p class="image"><a class="img2 off" href="http://cisco.cvent.com/events/the-sell/custom-19-95a683ee1c5b4f86aff4929040e12de0.aspx" style="opacity: 1;"><span></span></a></p>
          <p class="image"><a class="img3 off" href="http://cisco.cvent.com/events/the-sell/custom-18-95a683ee1c5b4f86aff4929040e12de0.aspx" style="opacity: 1;"><span></span></a></p>
          <p class="image"><a class="img4 off" href="http://cisco.cvent.com/events/the-sell/custom-17-95a683ee1c5b4f86aff4929040e12de0.aspx" style="opacity: 1;"><span></span></a></p>
          <p class="image"><a class="img5 off" href="http://cisco.cvent.com/events/the-sell/custom-21-95a683ee1c5b4f86aff4929040e12de0.aspx" style="opacity: 1; top: 0px;"><span></span></a></p>
          <p class="text">Sales Enablement <br>Learning Lifecycle</p>
        </div>

The css snippet that creates the donut

#graphic {
	width:432px;
	height:275px;
	position:relative;
	margin:20px 0;
}
p.text {
	color:#1b4374;
	position:absolute;
	font: 20.16px Arial, Verdana, sans-serif;
	top:139px;
	left:141px;
	margin:0;
}
p a {
	position:absolute;
	background-repeat:no-repeat;
	text-indent:-999999px;
	outline:none;
	cursor:pointer;
}
p a span{
	display:block;
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)"; /* IE8 */   
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF);   /* IE6 & 7 */      
    zoom: 1;
}
p a.img1{
	top:0;
	left:0;
	width:186px;
	height:160px;
}
p a.img1 span{
	background-image:url('images/intermediate.png');
	width:186px;
	height:160px;
}
p a.img2{
	top:85px;
	left:0;
	width:124px;
	height:175px;
}
p a.img2 span{
	background-image:url('images/foundational.png');
	width:124px;
	height:175px;
}
p a.img3{
	left:115px;
	top:194px;
	width:225px;
	height:81px;
	z-index:11;
}
p a.img3 span{
	background-image:url('images/on-boarding.png');
	width:225px;
	height:81px;
}
p a.img4{
	top:81px;
	right:5px;
	width:106px;
	height:169px;
	z-index:10;
}
p a.img4 span{
	background-image:url('images/talent.png');
	width:106px;
	height:169px;
}
p a.img5{
	top:0;
	left:209px;
	width:193px;
	height:152px;
}
p a.img5 span{
	background-image:url('images/advanced.png');
	width:193px;
	height:152px;
}

p a.off{
	opacity:1;
}
p a.on{
	opacity:0.5;
}

jQuery code snippet

$(document).ready(function() {
	$("p.image a").addClass("off");					   
	
	$("p.image a").hover(
		function(){
			$("p.image a").not(this).animate({
				opacity:0.5	
			},200, 'linear');
			$(this).animate({
				opacity:1,
				"top": "+=2px",
				easing: "easein"
			},300, 'linear', "slow");
			
		},
		function(){
			$("p.image a").animate({
				opacity:1	
			},0);
			$(this).animate({
				"top": "-=2px"
			},300, 'linear', "slow");

		}
	); 
	
});

I hope you liked my approach to creating a learning lifecycle map. I would like to know your thoughts and any suggestions on how we can improve this learning lifecycle map. Thanks for reading.

A simple price calculator using javascript

My client who is an active lifestyle coach wanted a price calculator on her webpage. She planned on selling multiple products with different product pricing. Her clients could add the desired quantity they wanted to purchase. Based on the Shipping method and the State where the products were to be delivered, the estimator had to calculate the total price.

Below is a price estimator I created as a prototype. The estimator was later tweaked and used on my client’s business page.

Snapshot of the simple price calculator
Snapshot of the simple price calculator

Notes

  • Create text fields for the user to input the quantity for each Item.
  • Make sure each text field has a unique ID.
  • Create separate javascript variables to represent each of the products.
  • Set the tax based on the location where the products need to be shipped.
  • Set the shipping and handling fee based on the method selected by the user.
  • On form submit event, calculate the total using a lot of math.
  • To make sure the calculations are rounded off to two decimal places, I used the javascript methods toFixed.
  • Display the final results as the value in the Text Field created for this purpose.

Sample html code to setup the input fields.

<div class="order">
   <label for="bb_sneakers">Quantity Desired: </label>
   <input type="number" name="bb_sneakers" id="bb_sneakers" min="0" placeholder="0" size="3">
</div>

Here is the javascript used for the calculation.

 
// JavaScript Document

(function() {
"use strict";
var state = document.getElementById("id_state");
document.addEventListener('DOMContentLoaded', function(){
	document.getElementById('cart_custom').addEventListener('submit', estimateTotal);
	var v_btn_estimate = document.getElementById('btn_estimate');
	v_btn_estimate.disabled = true;
	state.addEventListener('change', function(){
		if(state.value === ''){
			v_btn_estimate.disabled = true;
			console.log("True");
		}
		else{
			v_btn_estimate.disabled = false;
			console.log("False");
		}
	});
});
function estimateTotal(event) {
	event.preventDefault();
	if( state.value === ''){
		alert('Please select the state you want to send your shipment');
		state.focus();
	}
	var sneakers = parseInt(document.getElementById("bb_sneakers").value, 10 )|| 0;
	var jersey = parseInt(document.getElementById("a_jersey").value, 10 )|| 0;
	var supple = parseInt(document.getElementById("p_supple").value, 10 )|| 0;
	var water = parseInt(document.getElementById("m_water").value, 10 )|| 0;
	console.log(water);
	var state_index = state.value;
	var shipping = document.querySelector('input[name=ship]:checked').value || '';
	var special_gift = document.getElementById("gift").checked;
	var special_mailing = document.getElementById("mailing").checked;
	var special_recipes = document.getElementById("recipes").checked;
	var t_message = document.getElementById("message").value;
	var shippingCostPer,
		totalShippingCost, 
		taxFactor = 1,
		totalItemPrice, 
		estimate;
	var t_quantity = sneakers + jersey + supple + water;
	totalItemPrice = (sneakers * 90 ) + (jersey * 25) + (supple * 30) + (water * 4);
	if (state.value === 'CA'){
		taxFactor = 1.075;
	}
	else if(state.value ==='WA'){
		taxFactor = 1.065;	
	}
	switch(shipping){
		case 'us':
			shippingCostPer = 2;
			break;
		case 'ups':
			shippingCostPer = 3;	
			break;
		default :
			shippingCostPer = 0;
			break;
	}
	totalShippingCost = shippingCostPer * t_quantity;
	estimate = '$' +((totalItemPrice * taxFactor ) + totalShippingCost).toFixed(2);
	document.getElementById('total_estimate').value=estimate;
	var result_html = document.getElementById('results');
	result_html.innerHTML = 'Total Item: ' + t_quantity + '<br>';
	result_html.innerHTML +='Total Shipping: $' + totalShippingCost.toFixed(2) + '<br>';
	result_html.innerHTML +='Tax:' + (( taxFactor - 1 )*100).toFixed(2) + '%';
	result_html.innerHTML +='(State:'  + state_index + ')';
}
})();

Are you looking at building a price estimator on your web page? Let me know if you have any questions.

An animated product description donut using jQuery

When I was working for a Marketing agency, our client – Cognitas requested us to build an animated donut to represent the four pillars of their product description model. The idea was to have a hover state when the user moves the mouse over each section of the donut. Clicking on each section will take you to a page with the related product description.

Animated Product description donut using jQuery
Screenshot of the product description donut

Using separate images for the on-off states of the donut, quite a bit of absolute positioning of the images and a dash of jQuery, I created the animated product description donut. The client was happy with the outcome and the donut was displayed on the client’s home page and products page.

Steps to create the animated product description donut.
  • Create three separate images to represent the three hover states of the donut.
  • Create one image to represent the whole donut (with no hover).
  • Create a div with five separate anchor tags to repesent the 5 colored areas on the donut including the center.
  • Use separate css classes to set the different images as background image for the donut.
  • On hover state for each anchor tag, use jquery to add/remove the css class.

The html used to setup the donut.


<div class="box_image_map">
   <a class="top" href="http://www.cognitas.com:80/cognitas/products/mobile_device_security_management"></a>
   <a class="left" href="http://www.cognitas.com:80/cognitas/products/crosslink"></a>
   <a class="right" href="http://www.cognitas.com:80/cognitas/products/pockettoken"></a>
   <a class="bottom" href="http://www.cognitas.com:80/cognitas/products/crosslink"></a>
   <a class="middle" href="http://www.cognitas.com:80/cognitas/products"></a>
</div>

The css snippet that creates the donut

.box_image {
	padding:10px; width:206px;
}
.box_image_map {
	padding:10px; width:206px; height:195px;
	background-image:url(images/rightcol_products.jpg);
	background-repeat:no-repeat;
	background-position:0 0;
	background-color:transparent;
	position:relative;
	-webkit-transition: background 0.5s linear;
	-moz-transition: background 0.5s linear;
	-o-transition: background 0.5s linear;
	transition: background 0.5s linear;
}
.box_image_map_crosslink {
	padding:10px; width:206px; height:195px;
	background-image:url(images/rightcol_crosslink.jpg);
	background-repeat:no-repeat;
	background-position:0 0;
	background-color:transparent;
	position:relative;
	-webkit-transition: background 0.5s linear;
	-moz-transition: background 0.5s linear;
	-o-transition: background 0.5s linear;
	transition: background 0.5s linear;
}
.box_image_map_mdsm {
	padding:10px; width:206px; height:195px;
	background-image:url(images/rightcol_msdm.jpg);
	background-repeat:no-repeat;
	background-position:0 0;
	background-color:transparent;
	position:relative;
	-webkit-transition: background 0.5s linear;
	-moz-transition: background 0.5s linear;
	-o-transition: background 0.5s linear;
	transition: background 0.5s linear;
}
.box_image_map_pockettoken {
	padding:10px; width:206px; height:195px;
	background-image:url(images/rightcol_pockettoken.jpg);
	background-repeat:no-repeat;
	background-position:0 0;
	background-color:transparent;
	position:relative;
	-webkit-transition: background 0.5s linear;
	-moz-transition: background 0.5s linear;
	-o-transition: background 0.5s linear;
	transition: background 0.5s linear;
}

.box_image_map .top, 
.box_image_map_pockettoken .top, 
.box_image_map_crosslink .top, 
.box_image_map_mdsm .top   	
	{position:absolute; top:20px; 	right:70px; 	background:transparent; 	width:100px; 	height:30px;}
.box_image_map .bottom, 
.box_image_map_pockettoken .bottom, 
.box_image_map_crosslink .bottom, 
.box_image_map_mdsm .bottom  	
{position:absolute; top:145px; 	right:70px; 	background:transparent; 	width:100px; 	height:30px;}

.box_image_map .right, 
.box_image_map_pockettoken .right, 
.box_image_map_crosslink .right, 
.box_image_map_mdsm .right 	
	{position:absolute; top:50px; 	right:40px;		background:transparent; 	width:30px; 	height:100px; }
.box_image_map .left, 
.box_image_map_pockettoken .left, 
.box_image_map_crosslink .left, 
.box_image_map_mdsm .left
	{position:absolute; top:50px; 	right:170px;	background:transparent; 	width:30px; 	height:100px; }
.box_image_map .middle, 
.box_image_map_pockettoken .middle, 
.box_image_map_crosslink .middle, 
.box_image_map_mdsm .middle
	{position:absolute; top:68px; 	right:93px; 	background:transparent; 	width:55px; 	height:55px;}

jQuery code snippet

$(document).ready(function(){
  	$('a.top').hover(function(){
				//Hover on code
				var classNameFull = $(this).parent().attr('class');
				$(this).parent().data('className', classNameFull)
					.removeClass().addClass('box_image_map_mdsm');
			},
			function(){
				//Hover off code	
				$(this).parent().removeClass("box_image_map_mdsm").attr('class',$(this).parent().data('className'));
	});
	
	
	$('a.left').hover(function(){
				//Hover on code
				var classNameFull = $(this).parent().attr('class');
				$(this).parent().data('className', classNameFull)
					.removeClass().addClass('box_image_map_crosslink');
			},
			function(){
				//Hover off code	
				$(this).parent().removeClass("box_image_map_crosslink").attr('class',$(this).parent().data('className'));
	});
	
	$('a.bottom').hover(function(){
				//Hover on code
				var classNameFull = $(this).parent().attr('class');
				$(this).parent().data('className', classNameFull)
					.removeClass().addClass('box_image_map_crosslink');
			},
			function(){
				//Hover off code	
				$(this).parent().removeClass("box_image_map_crosslink").attr('class',$(this).parent().data('className'));
	});
	
	$('a.right').hover(function(){
				//Hover on code
				var classNameFull = $(this).parent().attr('class');
				$(this).parent().data('className', classNameFull)
					.removeClass().addClass('box_image_map_pockettoken');
			},
			function(){
				//Hover off code	
				$(this).parent().removeClass("box_image_map_pockettoken").attr('class',$(this).parent().data('className'));
	});
	
	$('a.middle').hover(function(){
				//Hover on code
				var classNameFull = $(this).parent().attr('class');
				$(this).parent().data('className', classNameFull)
					.removeClass().addClass('box_image_map');
			},
			function(){
				//Hover off code	
				$(this).parent().removeClass("box_image_map").attr('class',$(this).parent().data('className'));
	});
							  
});


I hope you liked my approach to creating a donut. I would like to know your thoughts and any suggestions on how we can improve this donut. Thanks for reading.

How to load JSON on button click

This is a prototype of a project done on a client website.

For a client’s About page, my designer wanted to have an uncluttered look when the page loads. The page was designed to have details about the company, mission, board member profiles and some other interesting facts.

She designed the page to have the team member’s info hidden as the page loads initially, with a big fancy button promoting the user to click in order to find out about the team member’s details.

To keep the team member’s bio and other information easy for the client to update, we decided to build out a JSON file with the speaker name and a short bio. The information was stored as javascript objects.

In order to prevent, the page from reloading when the user clicks on the button, I decided to use AJAX. Using Ajax, I parsed the JSON and loaded the output into a JSON object. I then created an unordered list of the bios and displayed on the page. The button onclick event triggered the process.

How to load JSON file on button click
Screenshot of the team bio loaded on button click

What is a JSON file?
JSON stands for Javascript Object Notation. It is a text file used to exchange data between browser and server. The data is stored as javascript objects.

Example of a JSON file

[
    {
        "name":"Barot Bellingham",
        "shortname":"Barot_Bellingham",
        "reknown":"Royal Academy of Painting and Sculpture",
        "bio":"Barot has just finished his final year at The Royal Academy of Painting and Sculpture, where he excelled in glass etching paintings and portraiture. Hailed as one of the most diverse artists of his generation, Barot is equally as skilled with watercolors as he is with oils, and is just as well-balanced in different subject areas. Barot's collection entitled \"The Un-Collection\" will adorn the walls of Gilbert Hall, depicting his range of skills and sensibilities - all of them, uniquely Barot, yet undeniably different"
    }
}

About AJAX

  • AJAX stands for Asynchronous Javascript and XML.
  • This means the client can request new pieces of information from the server any time without loading the entire page. The new request can be triggered by an event on the browser such as clicking on a button, hovering on an image etc.
  • Javascript handles the events, creating new requests etc. and also takes care of updating the part of the document that needs to be changed.
  • Javascript talks to the server using APIs called XHR-XML HTTP Request.
  • Data transferred from the server to the client using XHR can be text file, html file or JSON object.

The html code on the page for the carousel

 <p>Click the button below, to load the speaker bio details</p>
  <button id="loadMore">Load Speaker Bios </button>
  <div id="update"></div>

Javascript code to create an AJAX request and load the JSON with the bio details

  document.getElementById("loadMore").onclick = function(){
    /* Supporting Older IE Browsers */
    var request;
    if(window.XMLHttpRequest){
	request = new XMLHttpRequest();
    }
    else {
	request = new  ActiveXObject("Microsoft.XMLHTTP");
    }
    request.open('GET', 'data.json');
    request.onreadystatechange = function(){
      if((request.readyState === 4) && (request.status === 200)){
	 var items = JSON.parse(request.responseText);
	 console.log(items);
	 var output = "<ul>";
	 for(var key in items){
		 output += "<li>" + items[key].bio + "</li>";
	 }	
	 output += "</ul>";			
	 document.getElementById("update").innerHTML = output;
      }		
    };		request.send();
  }

I hope you found this article useful and interesting.

Have you used AJAX on your website project? Do you have any thoughts on how to improve the process?

How to build a carousel using JSON and template engine

This is a prototype of a project done on a client website. For their home page, the client wanted to have a events panel with a carousel of all the speakers at their upcoming event. The carousel was to include the speaker name, avatar and a short bio.

To keep the speaker information easy for the client to update, we decided to build out a JSON file with the speaker name, shortname to find the avatar image and a short bio. This time we decided to template the JSON file using mustache.js.

Using JSON and mustache templating engine, we build out the carousel.
Screenshot of the carousel build with json and mustache templating engine

What is a JSON file?
JSON stands for Javascript Object Notation. It is a text file used to exchange data between browser and server. The data is stored as javascript objects.

Example of a JSON file

{ "speakers" : [
    {
        "name":"Barot Bellingham",
        "shortname":"Barot_Bellingham",
        "reknown":"Royal Academy of Painting and Sculpture",
        "bio":"Barot has just finished his final year at The Royal Academy of Painting and Sculpture, where he excelled in glass etching paintings and portraiture. Hailed as one of the most diverse artists of his generation, Barot is equally as skilled with watercolors as he is with oils, and is just as well-balanced in different subject areas. Barot's collection entitled \"The Un-Collection\" will adorn the walls of Gilbert Hall, depicting his range of skills and sensibilities - all of them, uniquely Barot, yet undeniably different"
    }
}

Why Use Templating?

  • Templating makes working with data a breeze. It is essentially a combination of data and layout.
  • The advantage of using templating is to keep the data and how that data is presented, separate from each other.
  • It is usually used for repeating data records which are then merged with one layout and presented to the user.
  • The data is in the JSON file and the layout is specified in the template script embedded in the html.
  • Placeholders are placed in the layout to specify which parts of the data records are going to be used.
  • Both the data and the layout are fed to the templating engine to create the finished HTML layout.
  • One application that uses repeating data records and presents it using one layout is Twitter.
Using JSON and mustache templating engine, we build out the carousel.
Screenshot of how templating engine works: From Lynda.com

About Mustache Templating
Mustache is an open-source template system developed for languages like Javascript and PHP. We are using Mustache as the templating system for this project. Mustache Templates have tags as indicators for the placeholders where data will be added in the final layout.

Mustache Templating snippet

<script id="speakerstpl" type="text/template">
    {{#speakers}}
        <div class="speaker">
            <img src="images/{{shortname}}_tn.jpg" alt="Photo of {{name}}" />
            <h3>{{name}}</h3>
            <h4>{{reknown}}</h4>
            <p>{{bio}}</p>
        </div>
    {{/speakers}}
</script>

The html code on the page for the carousel

 <div id="speakerbox">
    <a href="#" id="prev_btn">&laquo;</a>
    <a href="#" id="next_btn">&raquo;</a>
    <div id="carousel"></div>
</div>

jQuery code snippet

$(function() {
    $.getJSON('data.json', function(data) {
        var template = $('#speakerstpl').html();
        var html = Mustache.to_html(template, data);
        $('#carousel').html(html);
        $('#carousel').cycle({
            fx: 'fade',
            pause: 1,
            next: '#next_btn',
            prev: '#prev_btn',
            speed: 500,
            timeout: 10000
        });
    }); 
}); 

I hope you found this article useful and interesting.

Have you used JSON or Mustache templating in your project? Do you have any thoughts on how to improve the process?

Extreme attention to detail

Femy worked with us on a very demanding project with multiple moving parts that required extreme attention to detail and extending beyond a normal workday. Femy provided wonderful assistance to our team with her valued expertise and professionalism. We were very fortunate to have her during that stretch and are so pleased she’s back with us again.

Jennifer McClenon Marketing and Advertising Professional, 3Marketeers