Skip to content

Bright Bright Great introduces monthly design industry dialogue series Triple Scoop.       Bright Bright Great introduces monthly design industry dialogue series Triple Scoop

💾
Technology

How-To: Uncle Goose Create-a-Name

An exciting part of last year’s Uncle Goose redesign was the “Create-a-Name” block generator. This had been the most user-requested feature, so it was important for us to make it happen.

Uncle Goose wanted a simple, intuitive way for customers to order individual blocks from one of three sets, and have each block’s color be customizable.

create-a-name-demo
Uncle Goose

Here’s a look at how we built it.

HTML

First, let’s get our container set up. We need a text input so people can type in the letters they want. We also have an empty div where our letters will be stored. The class set-* will dictate which set style the letters have. The data-set attribute will store the set information for use in the shopping cart.

<div class="container letters-container"> <input type="text" class="create-a-name-text" maxlength="26" id="create-a-name-text" placeholder="Enter text" autofocus /> <div class="letters set-abc clear" data-set="set-abc"></div><!-- /.letters --> </div><!-- /.container.letters-container -->

We also need a way for the customer to select which set they want:

<div class="set-selector"> <label>Set:</label> <select id="set-filter"> <option selected value="set-abc">Classic ABC</option> <option value="set-upperlower">Upper Lower</option> <option value="set-lower">Lowercase</option> </select> </div><!-- /.set-selector -->

We also need to store all the info about which blocks and options the customer has selected. We’re going to use a link with all the data stored in data-* attributes that can be parsed by the cart on submission.

Our cart needs a product ID, which is just the WordPress post ID, a block quantity to calculate the price, and all the letter, set, and color details are stored in a product note.

<a href="#" class="add-to-cart btn green icon-cart" data-id="<?=get_the_ID()?>" data-qty="0" data-note="">Add To Cart</a>

Let’s get a template going for our letters. The template letter will be hidden but will be used by our javascript to create new letters on the fly. This is neater and simpler than writing out all this HTML in the javascript.

We’re also going to store the color and set information in data attributes so they’re easy to use in our javascript later on. We’re using PHP to import the SVGs we need for two of the sets. The third set has a solid background color so we can use CSS alone to style it.

<!-- This block serves as a template for any blocks we dynamically create. --> <div class="letter-wrapper letter-template" data-color="" data-letter="" style="display: none"> <div class="letter-inner"> <?php @include(dirname(__FILE__) . '/img/filigree-abc.svg'); ?> <?php @include(dirname(__FILE__) . '/img/filigree-lower.svg'); ?> <span class="letter"></span> </div><!-- /.letter-inner --> <div class="color-select"> <div class="color-option blue" data-color="blue">Blue</div> <div class="color-option green" data-color="green">Green</div> <div class="color-option orange" data-color="orange">Orange</div> <div class="color-option yellow" data-color="yellow">Yellow</div> </div><!-- /.color-select --> </div><!-- /.letter-wrapper -->

CSS

Now that we have a letter going, we can start styling it. We’re going to use ems for all our size values since eventually the font size of the blocks will change dynamically, and we want the blocks to be sized accordingly.

We need a letter wrapper with a width of 2ems, and a :before with top padding of 100% to both preserve our aspect ratio, and to position the color selection element more easily. The letter wrapper also has an active state for when the color selection tool is active.

Let’s set backface-visibility: hidden to avoid repainting issues, and set some basic transition properties. For browsers that support it, we can also warn them that this element is going to have some transforms applied to it.

.letter-wrapper { position: relative; display: inline-block; width: 2em; margin: 0 0 0.5em; z-index: 1; cursor: pointer; transition: all 0.3s; backface-visibility: hidden; will-change: transform; &:before { display: block; padding-top: 100%; content: ''; } &.is-active { z-index: 2; transform: translateY(-0.75em); transition: all 0.3s; } }

.letter-inner is going to be our block-looking element. We’re going to position it absolutely in the wrapper, give it a base background color, a box shadow, and a border radius.

All styles for elements inside .letter-wrapper are nested inside .letter-wrapper in our Sass file, so we can sanely group together modifications based on the set chosen or any state changes.

.letter-inner { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: #feedda; box-shadow: 0 -0.1em #feedda; border-radius: 0.075em; } &.bounce .letter-inner { animation: bounce 0.5s; }

This part of the block also gets a bounce animation during certain interactions. Let’s write that up now.

@keyframes bounce { 0% { transform: translateY(0); } 33% { transform: translateY(-0.25em); } 66% { transform: translateY(0.06em); } 100% { transform: translateY(0); } }

For the blocks’ filigree, we have two SVGs that we’ll be toggling depending on which set is chosen. In an ideal world, we could use an SVG sprite and change viewBox with CSS, but at this time we can only do that with javascript.

We already have a ton going on in javascript so let’s avoid adding more complexity to that file. Since we need to be able to dynamically change the SVG’s fill color, we can’t use one SVG as regular background image sprite either. So two files it is.

svg { position: absolute; top: 0; left: 0; display: none; width: 100%; height: 100%; border-radius: 0.075em; transition: all 0.3s; }

Let’s place the actual letter in the middle of our block. We’ll be making some adjustments to individual letters based on the set/x-height later to make sure all letters are always centered, but for now let’s get the basics down.

.letter { position: absolute; top: 50%; left: 50%; text-transform: uppercase; color: #fff; transform: translate(-50%,-50%); transition: color 0.3s; }

Now that we have the basics of a block down, we can style the different block colors and different sets. Let’s leverage Sass and set up some color variables so we can easily loop through each one.

 // block colors $blockColors: ( 'blue': #3b83db, 'green' : #81c81b, 'orange': #ff900c, 'yellow': #f5c008 ); @each $name, $color in $blockColors { &.#{$name} { svg { fill: $color; } .letter { color: $color; } .set-upperlower & .letter-inner { background: $color; } } } .set-abc & { .filigree-abc { display: block; } .letter { top: 49%; left: 51%; font-family: "Century Schoolbook", sans-serif; } } .set-upperlower & { .letter { top: 48%; margin-top: -1px; font-family: "Century Gothic", sans-serif; color: #feedda; font-size: 1.75em; } } .set-lower & { .filigree-lower { display: block; } .letter { margin-top: -0.125em; font-family: "Century Gothic", sans-serif; text-transform: lowercase; } &.letter-high .letter { margin-top: -0.02em; } &.letter-low .letter { margin-top: -0.175em; } &.letter-mid .letter { margin-top: -0.1em; } &.letter-a .letter { margin-top: -0.12em; } }

You may have noticed some letter-based modifications on the lowercase set. Once the letters are all lowercase, while their baselines may line up, they don’t look centered in the block’s face. In our javascript, we will assign classes to the block based on the letter typed and adjust its positioning accordingly.

The last thing we need to style is the color selection tool. It’s a basic menu, with a triangle pointing toward its block and some color indicators.

.color-select { position: absolute; display: none; padding: 5px 0; margin-top: 0.4em; left: 50%; z-index: 1; background: $black; text-align: left; transform: translateX(-50%); backface-visibility: hidden; // triangle &:before { position: absolute; top: -19px; left: 50%; margin-left: -10px; border: 10px solid transparent; border-bottom-color: $black; content: ''; } .color-option { padding: 5px 15px; white-space: nowrap; @include font-size(18); // font-size mixin which spits out both px and rem transition: background 0.3s; // color bullet &:before { display: inline-block; width: 8px; height: 8px; margin: -5px 10px 0 0; border-radius: 50%; content: ''; vertical-align: middle; } @each $name, $color in $blockColors { &.#{$name}:before { background: $color; } } &:hover, &.is-active { background: $grey-darkest; } } }

Javascript

Now let’s switch over to javascript. First off, we know a lot is going to happen in this generator, so let’s set up a basic structure to our file. We can fill in the functions later. We’ll need two lock variables for controlling when events can happen, one for resize, and one for the various functions that can happen to a block.

We also need functions for interactive, resize, add/edit blocks, opening/closing the color selection UI, color selecting, changing the set, and updating the cart information.

(function($){ var createAName = { //------------------------------------------------------------------------ // Variables //------------------------------------------------------------------------ resizeLock: null, blockLock: true, //------------------------------------------------------------------------ // Functions //------------------------------------------------------------------------ interactive: function() { }, resizeEvents: function() { }, addEditBlock: function(){ }, popColorSelection: function() { }, colorSelection: function() { }, changeSet: function() { }, updateCreateAName: function() { } }; $(document).ready(function(){ // bind interactive events createAName.interactive(); // resize events $(window).resize(function(){ createAName.resizeEvents(); }).resize(); }); })(jQuery);

First off, let’s make some blocks. Inside our interactive function, let’s watch for typing on the input we created earlier, and trigger the addEditBlock function when someone types.

$('#create-a-name-text').keyup(function(){ createAName.addEditBlock(); });

Before we can create the blocks, we need to strip out any non-alphabet letters, trim the length of the text if it’s beyond the max length, correct the letter case to match the set, check whether the letters typed have actually changed since the last input, and if there are any valid characters at all.

addEditBlock: function() { var name = $(this).val().replace(/[^a-zA-Z]/g, ''), //create a nice version of letters to play with block_prototype = $('.letter-template'), //html template for a letter block_wrapper = $('.letters'), //the letters wrapper block_set = block_wrapper.attr('data-set'), //the set we're using block_colors = ['blue','green','orange','yellow'], //colors // group letters based on required position modification block_letters_high = ['b', 'd', 'f', 'h', 'i', 'k', 'l', 't', 'B', 'D', 'F', 'H', 'I', 'K', 'L', 'T'], block_letters_low = ['g', 'p', 'q', 'y', 'G', 'P', 'Q', 'Y']; block_letters_mid = ['u', 'v', 'w', 'x', 'U', 'V', 'W', 'X']; //keep name short... 26 is plenty if(name.length > 26) { name = name.substr(0, 26); } //correct the case if(block_set === 'set-lower'){ name = name.toLowerCase(); } //upercase else { name = name.toUpperCase(); } //exit if nothing has changed if(name === block_wrapper.attr('data-name')) { return true; } //if nothing has been typed, this is easy if(!name.length) { block_wrapper.html(''); }

Now for the meat of this function, actually making our blocks. When blocks are initially created, colors are assigned by looping through the color array. But customers can edit their inputted text, so if they’ve already made a color selection for a letter, edit the text, and that letter is still in their edited text, we want to preserve the color selection.

And though we haven’t written these functions yet, we know we want to update the cart information, and trigger the resize functions to make sure the blocks are being sized properly.

 //if there are letters, let's figure out how to draw them else { //some more variables var letters = name.split(''), //each letter block_new = null, //new block color_index = -1, //color blocks_old = [], //all existing blocks blocks_new = []; //all new blocks //store the old blocks in an array. if($('.letter-wrapper', block_wrapper).length) { $('.letter-wrapper', block_wrapper).each(function(){ blocks_old.push($(this)); }); } //cycle through each letter $.each(letters, function(k,v){ color_index++; //if there is an existing letter matching this one, //preferentially use it (this preserves color selections) if(blocks_old.length > k && blocks_old[k] !== undefined && blocks_old[k].attr('data-letter') === v){ blocks_new.push(blocks_old[k].clone()); } //otherwise let's make a new block else { //start with the prototype block_new = block_prototype.clone(); block_new.removeClass('letter-template'); block_new.removeAttr('style'); var xHeight = 'letter-middle'; //check what x-height based class we should assign to it if($.inArray(v, block_letters_high) > -1){ xHeight = 'letter-high'; } if($.inArray(v, block_letters_low) > -1){ xHeight = 'letter-low'; } if($.inArray(v, block_letters_mid) > -1){ xHeight = 'letter-mid'; } //customize it $('.letter', block_new).text(v); $('.color-option.' + block_colors[color_index], block_new).addClass('is-active'); block_new.attr({'data-letter': v, 'data-color': block_colors[color_index]}); block_new.addClass(block_colors[color_index]); block_new.addClass(xHeight); block_new.addClass('letter-' + v.toLowerCase()); //and add to our list blocks_new.push(block_new); } //and start over with the colors if(color_index + 1 === block_colors.length){ color_index = -1; } }); //now add each block to our set! block_wrapper.html(''); $.each(blocks_new, function(k,v){ block_wrapper.append(v); //if this is not the last item, add a space if(k + 1 < blocks_new.length){ block_wrapper.append(' '); } }); }//letters //save the name so we can skip all this work for non-changey-keys block_wrapper.attr('data-name', name); //and update the cart data createAName.updateCreateAName(); //one last thing, trigger resize events so the blocks get scaled correctly if(createAName.resizeLock) { clearTimeout(createAName.resizeLock); } createAName.resizeLock = setTimeout(function(){ createAName.resizeEvents(); }, 100); }, // end addEditBlock

Let’s tackle the resizing. We want to fit as many blocks on one line as possible while maintaining legibility. We also want to make the blocks as big as possible up to a certain point. So we need a min and a max font size, and figure out what size in that range our blocks should be given the container size and the amount of blocks.

Let’s also include a little wiggle room so the blocks aren’t flush up against the container, and we need to account for the fact that the blocks are 2ems wide, so our final font size will actually be half the number we come up with.

resizeEvents: function() { var containerWidth = $('.letters').width(), // container width letterAmount = $('.letters').find('.letter-wrapper').size(), // how many letters do we have baseSize = containerWidth / letterAmount, // how wide can the blocks be to still fit in the container wiggleSize = (baseSize - (baseSize * 0.15), // wiggle room fontSize = wiggleSize / 2, // blocks are 2ems wide, so font size is half size of block maxSize = 96, // max font size minSize = 38; // min font size if(fontSize > maxSize) { fontSize = maxSize; } if(fontSize < minSize) { fontSize = minSize; } fontSize = Math.floor(fontSize); $('.letters').css('font-size', fontSize + 'px'); }; // end resizeEvents and end 

Now that we’ve got the basics of block making and resizing down, we can work on the options. First up, let’s add a triggering mechanism to our interactive function for changing the block set.

$('#set-filter').on('change', function(){ var oldSet = $('.letters').attr('data-set'), newSet = $(this).val(); createAName.changeSet(oldSet, newSet); });

And let’s fill out our changeSet function. We want to remove the old set’s class and add the new one to all the letters, as well as update the case if necessary, and update the cart information.

changeSet: function(oldSet, newSet){ $('.letters').removeClass(oldSet).addClass(newSet).attr('data-set', newSet); //update data so we're using the right case var block_wrapper = $('.letters'); //lowercase if(newSet === 'set-lower'){ block_wrapper.attr('data-name', block_wrapper.attr('data-name').toLowerCase()); } //uppercase else { block_wrapper.attr('data-name', block_wrapper.attr('data-name').toUpperCase()); } $('.letter-wrapper', block_wrapper).each(function(){ //lowercase if(newSet === 'set-lower'){ $('.letter', $(this)).text($('.letter', $(this)).text().toLowerCase()); $(this).attr('data-letter', $(this).attr('data-letter').toLowerCase()); } //upercase else { $('.letter', $(this)).text($('.letter', $(this)).text().toUpperCase()); $(this).attr('data-letter', $(this).attr('data-letter').toUpperCase()); } }); //and update the cart data createAName.updateCreateAName(); }, // end changeSet

Moving on to color selection. The first step is to actually show the color selection menu when someone clicks on a block. We also want to close it when they click on the same block again, or on a different block. On top of that, we want to close open blocks when they click on anything that isn’t a block.

To accomplish this, we’re using jQuery Outside Events to check whether a user has clicked outside an open block. This is also where our blockLock variable comes in. We just want to make sure we’re not triggering any outside events when there isn’t a block open, so we’re going to set blockLock to true initially, and set it to false when a block is open.

Let’s set up a block click event, and monitor outside events in our interactive function. As a note, anytime we’re binding an event to a block, we have to use .on() on the parent element rather than something like .click() on the element itself, since the blocks are dynamically created and .click() only binds to elements that are present when the event is first bound.

$('.letters').on('click', '.letter-inner', function(e){ e.preventDefault(); createAName.popColorSelection($(this)); }); // close block when you click outside of it $('.letters').bind( 'clickoutside', function(){ if(createAName.blockLock === false){ $('.letter-wrapper.is-active .letter-inner').click(); } }); 

And now for our popColorSelection function.

popColorSelection: function(block){ var parent = block.parents('.letter-wrapper'); // if there is an active block but it is NOT the block we clicked on, close that block if($('.letter-wrapper.is-active') && !parent.hasClass('is-active')){ $('.color-select', $('.letter-wrapper.is-active')).fadeOut(); $('.letter-wrapper.is-active').removeClass('is-active'); } // toggle active class, fade toggle the menu parent.toggleClass('is-active'); $('.color-select', parent).fadeToggle(); // set our blockLock appropriately if(createAName.blockLock === true){ createAName.blockLock = false; } else { createAName.blockLock = true; } }, //end popColorSelection

Awesome. Now we can start doing all the things that need doing when someone changes the color. First up, let’s toss an event trigger in our interactive function and pass the block and menu item info to the colorSelection function.

$('.letters').on('click', '.color-option', function(e){ var block = $(this).parents('.letter-wrapper'); createAName.colorSelection(block, $(this)); });

When someone selects a new color, we need to capture the old color, remove its class, add the new color class, update data-color attribute, and update the cart information. We also need to update the color menu to reflect the active color. The block also gets a little bounce animation when a new color is selected.

colorSelection: function(block, menuItem) { var currColor = block.attr('data-color'); var color = menuItem.attr('data-color'); e.preventDefault(); block.removeClass(currColor).addClass(color).attr('data-color', color); block.addClass('bounce'); // add a bounce animation setTimeout(function(){ block.removeClass('bounce'); }, 500); // length of our bounce animation $('.color-option.is-active', block).removeClass('is-active'); menuItem.addClass('is-active'); //and update the cart data createAName.updateCreateAName(); }, //end colorSelection

The last thing we need to do is build out our function that updates the cart information. It’s pretty simple. We just run through all the blocks and gather all the info we need, and pop it back in the cart button element.

updateCreateAName: function(){ //build the add-to-cart data var block_wrapper = $('.letters'), block_set = block_wrapper.attr('data-set'), blocks = $('.letter-wrapper', block_wrapper), qty = blocks.length, notes = [], button = $('.add-to-cart'); //no quantity, we're done! if(!qty) { button.attr({'data-qty': 0, 'data-note': ''}); } //yes quantity else { notes.push($('#set-filter option[value="' + block_set + '"]').text()); blocks.each(function(){ notes.push('[' + $(this).attr('data-letter') + '] ' + $(this).attr('data-color')); }); button.attr({'data-qty': qty, 'data-note': notes.join(';')}); } }, // end updateCreateAName

That’s it. Be sure to check out the Create-a-Name generator on the Uncle Goose website, along with all their other awesome block sets!

Tiffany Stoik, Front-End Developer