1stwebdesigner

Posted by | Posted on 17:11

1stwebdesigner


How to Create a Flash-like Color and Pattern Morphing effect with jQuery

Posted: 23 Mar 2010 01:50 PM PDT

How to Create a Flash-like Color and Pattern Morphing effect with jQueryToday you will learn, how you can create a Flash-like effect with only using a few lines of jQuery and a transparent PNG as mask.

Not only will you be able to dynamically change the color of the logo, but also add patterns as you wish and even animate them later with a few lines of code. With this technique you will also be able to add transition effects and control any single part of the colors, patterns and animations.

Introduction and Demonstration

You can take a look to the finished Demonstration by clicking here. As you see, you will be able to adjust every single bit of the color, transparency, pattern and even the animation itself.

If you want to follow along, you can download the finished project files here (zip archive).

This technique generally does not require any jQuery at all – but we are using it, to make nice transitions and to be able to adjust the color, pattern and animation by a few sliders.

Step 1: Preparing the Mask and Pattern Images

The Key-PNG for this Effect:

First you have to create a PNG-24 (24bit, so the alpha-channel gets saved too) similar to this one:

Masked-Logo

As you see, the transparency is not the outside of the logo. It is inside of it, where you want to change the color, apply the gradients, add patterns and animate them. The background should be exactly the same as in the container, in which the logo is going to be. You can either use a single color or whatever else you want to. Just take care if your background has a pattern so the transition is seamless to your main background-pattern.

The Pattern-PNG for the Animation Effect:

The next image we will need is the one with the gradient and/or pattern. The one I will use looks like this:

Pattern-howto

The dimensions of my pattern are 450 x 3000 pixel. The width should be exactly the same as the PNG-mask. The height does not matter. The higher, the better. Also make sure to remember the size. We will need it later in our script to adjust the animation.

Step 2: Arranging the Folders and the XHTML Structure

Before we start creating our needed files, we first create our folder structure again. It should look something like this again:

Folder-Structure

Our index.html, which will be created at the root of this structure will need following wrappers around the PNG-mask:

 <div id="wrapper">    <div id="color"></div>    <div id="pattern"></div>    <div id="logobox"></div> </div> 

As you see here, we have 3 different wrappers for each element. The first one will contain only the color. The second one only the pattern. And the last one will only contain the PNG-mask, which also will be the topmost element.

Why three wrappers???

Maybe you ask yourself now, why we need 3 separate wrappers for each element, if we can do the same with only one. This is why: With 3 separate wrappers, we will be able to adjust different transparencies for every used element, without worrying about loosing opacity on the pattern or the logo itself.

For the sliders we will use the latest jQuery UI again – so you don't have to worry too much about the structure there. Just make sure they have all the same class and different ID's.

My Slider structure looks like this:

 <!-- color sliders --> <div id="red" class="slider"></div> <div id="green" class="slider"></div> <div id="blue" class="slider"></div> <div id="alpha1" class="slider"></div>  <!-- pattern sliders --> <div id="alpha2" class="slider"></div> <div id="speed" class="slider"></div> 

For the buttons I'm using ordinary a-tags – Just give them all the same class and different ID's again, so you can style them and bind different functions to them. We will later escape the default link-behavior by returning "false" in the script.

Scripts and styles in the header:

 <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/black-tie/jquery-ui.css" type="text/css" media="all" />  <link rel="stylesheet" href="css/style.css" type="text/css" media="all" />  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>  <script type="text/javascript" src="js/jquery-ui-1.8rc3.custom.min.js"></script>  <script type="text/javascript" src="js/script.js"></script> 

For saving bandwidth, we will link to the Google files again. Unfortunately the latest jQuery UI (version 1.8, release candidate 3) is not hosted there yet, so you have to host in on your own server. You can customize the download yourself here. You will only need the UI Core and the Slider Widget.

I cannot use the latest stable release (version 1.7.2) because there is a small "bug", regarding the animation of the sliders, when changing the values programmatically. You can take a look at the bug-tracker ticket here. However, it is resolved in the latest release candidate, so I will not go further into the changes now.

Of course you can use the jQuery UI ThemeRoller to create your own slider-styles.

This time I will skip the CSS part completely because there is nothing special to take care of. The only thing you maybe want to add is classes for pattern-only settings and animation-only settings, so we can hide them later in our script by only using the class names as selector.

Step 3: Writing Some JavaScript Functions

The first thing we have to do is to create document.ready function, so the scripts start, as soon as the DOM is loaded and before the page contents are loaded.

 $(function(){    // put all your jQuery goodness in here. }); 

Now we will setup a few variables at first:

 // color container var color = $("#color");  // pattern  container var pattern = $("#pattern");  //  animation start/stop button var startstop = $("#startstop");  // show/hide button var showhide = $("#showhide");  // random-color button var randomcolors = $("#randomcolors");  // default animation speed (5ms to 100ms) var speed = 50;  // starting position of  the pattern var  curPos = 0;  //  reset-position var resetPos = -(3000-117); 

The last variable defines when our pattern hits the end, so we can start from the beginning again – it will be for the animation later. 3000 is the height of our pattern image and 117 is the height of our logo.

Don't forget to put a minus in front of this value. The pattern will move up in its container with the CSS background-position animated.

Converting the slider-div's to the jQuery UI sliders:

 // setting up the jQuery UI sliders  $("#red, #green, #blue").slider({ animate:true, range:"min", max:255, slide:colorChanger, change:colorChanger });  $("#red").slider("value", 52); $("#green").slider("value", 174); $("#blue").slider("value", 203);  $("#alpha1").slider({ animate:true,  range:"min", max:100, value:100, slide:alphaChanger1, change:alphaChanger1 });  $("#alpha2").slider({ animate:true, range:"min", max:100, value:100, slide:alphaChanger2, change:alphaChanger2 });  $("#speed").slider({ animate:true, range:"min", min:5, max:100, value:50, slide:speedChange, change:speedChange }); 

This is everything you need, to "install" the sliders and setup the starting-values and behaviors.

I will go true all options, so you know what you are doing here:

  • animate:true: Smoothly scroll the handle of the sliders to the position where the user clicked or to the value of our random function. You can also also use one three predefined strings ("slow", "normal", "fast") or the number of milliseconds to run the animation (e.g. 500).
  • range:"min": This is optional – I'm using this, so I can fill up the slider with a color or a pattern. With "min" the color/pattern will go all the way from left to the position of the handle.
  • min:5: The minimum value of the slider (used only on the animation-speed slider).
  • max:255: The maximum value of the slider.
  • value:50: Setting the starting-value of the slider
  • slide/change: Those two are events of the slider. They are triggered when the user slides or changes the values. We are calling our functions there which will be created in the next step.

If you need more information about the options and events we are using, you can take a look at the documentation here.

Now everything is ready to create our main functions.

Converting RGB to HEX

 // RGB to HEX converter (with 3 arguments) function rgbToHex(r,g,b){     var hex = [       // converting strings to hex (16)       r.toString(16),       g.toString(16),       b.toString(16)    ];     // get all 3 values of the array    $.each(hex, function(nr, val){        // make sure they are not empty       if (val.length == 1){           // add leading zero          hex[nr] = "0" + val;       }    });     // returns a valid hexadecimal  number    return hex.join("").toUpperCase(); } 

With this function, we will convert the values of the red, green and blue sliders to a valid hexadecimal for using it in CSS.

For making this work, we need to pass 3 variables to the function (r,g,b) and convert those strings to hex-code. We do so by using .toString(16).

We also wrapped them into an array, so we can go through them now by jQuery's each() loop, passing the index of the array (nr) and the value (val) to the loop.

Last thing we need to to is to join those 3 values and converting them to uppercase.

Background-color Changer:

 // changing the colors function colorChanger(){     // value of the "red"-slider    var red = $("#red").slider("value");     // value of the  "green"-slider    var green = $("#green").slider("value");     // value of the "blue"-slider    var blue = $("#blue").slider("value");     // converting values to hex    var hex = rgbToHex(red,green,blue);     // changing the background-color of  the wrapper    color.css("background-color", "#" + hex);  } 

This function will get all 3 values of our red-, green- and blue-sliders, convert the values to a valid hex-code using the previous function and change the css of our color-container.

That's all! You should now be able to change the color of your logo. (You have to comment out the alpha and the speed sliders, or you will get a JavaScript error.)

Opacity Changer:

 // change the opacity of the color-wrapper function alphaChanger1(){     var opacity = $("#alpha1").slider("value") / 100;    color.css("opacity", opacity ); }  // change the opacity of the pattern-wrapper function alphaChanger2(){    var opacity = $("#alpha2").slider("value") / 100;    pattern.css("opacity", opacity ); } 

Those two functions will handle the opacity of the color-wrapper and the pattern-wrapper. Nothing special there. Just make sure to divide your value by 100, so you get a value between 0.00 and 1.00. This step is important because the opacity attribute does not accept 3 digits as value. So a 50% opacity will be 0.50.

You can also combine those two functions by passing the correct container returning the right value. I skipped this step. It's quick and dirty – but it works! :)

Function for the Animation:

 // pattern animation function patternScroller(){     // substracting 1 with  every call    curPos--;     // if it hits  our reset-position, back to 0    if (curPos == resetPos){ curPos = 0; }    pattern.css("background-position", "0 " + curPos + "px"); } 

Every time this function gets called, we will subtract 1 from our current position variable (curPos). If it hits the value of our reset position (resetPos), we will set it back to 0. The last step there is to change the vertical position of the background from our pattern-container.

Speed Changer:

 // animation speed changer function speedChange(){     // get the current value of the  speed-slider    speed = $("#speed").slider("value");     // clear interval,  if there is any    clearInterval(initScroll);     // set a new interval with the current speed    initScroll = setInterval(patternScroller, speed); } 

This function will change the speed of our animation. First we need to get the current value of our speed-slider. After this we have to clear any previous interval (if there is any). Last but not least we are creating a new interval. This will call our previous function (patternScroller) every x milliseconds. The x stands for the value of our speed slider.

Random Color and Alpha function:

 // random color function function randomColors(){    $("#red").slider("value", Math.floor(Math.random()*256), true);    $("#green").slider("value", Math.floor(Math.random()*256), true);    $("#blue").slider("value", Math.floor(Math.random()*256), true);    $("#alpha1").slider("value", Math.floor(Math.random()*101), true); } 

This function will change the values of the red, green, blue and alpha1 sliders randomly when called. It does so by using JavaScripts Math.random() function. To make sure the returned value is not 0, just add 1 to the maximum value. To make it a Integer we wrapped returned value into Math.floor(), so it gets rounded downwards to the nearest integer.

This function is now ready to be bound to button:

 // random colors button randomcolors.click(function(){     // if button has  no "random" class    if (!$(this).hasClass("random")){        // add it       $(this).addClass("random");        // change the button text       $(this).text("random-colors & alpha: ON");        // call the  random function once       randomColors();        // set a intervall with the random function       randomizer = setInterval(randomColors, 2000);     } else {        // remove the class       $(this).removeClass("random");        // change the button text       $(this).text("random-colors & alpha: OFF");        // clear the  interval       clearInterval(randomizer);    }     // change the  default link-behavior    return false; }); 

We will check if the random-function is already running by adding and removing a class ("random") to the button.

The important parts of this whole function is setting/clearing the interval. The interval will get called every 2 seconds (2000 milliseconds) and the first call is after 2 seconds, so we are manually calling it the first time. By returning false, we make sure the override the default behavior of a link.

Show and Hide the Pattern container:

 // show and hide the pattern showhide.click(function(){     // if button has no "visible"  class    if (!pattern.hasClass("visible")){        // add it       pattern.addClass("visible");        // change the text       $(this).text("hide pattern");        // fade in the pattern-container       pattern.stop().fadeTo(1000, 1);        // fade in all elements with the class "forpattern"       $(".forpattern").stop().fadeTo(800,  1);     } else {        // remove the  class       pattern.removeClass("visible");        // change the button text       $(this).text("show pattern");        // fade out the pattern-container       pattern.stop().fadeTo(800,  0);        // fade out all elements with  the class "forpattern"       $(".forpattern").stop().fadeTo(800, 0);    }     // change the default link-behavior    return false; }); 

Again we are checking if the pattern is hidden or not by adding and removing a class to the button ("visible"). Nothing complicated in here – by now, everything should be clear. Just to make sure: The second fade-effect is used to show/hide all elements which have the class "forpattern".

Start and Stop the Animation:

 // start and stop the animation startstop.click(function(){     // if button has no  "scrolling" class    if (!pattern.hasClass("scrolling")){        // add it       pattern.addClass("scrolling");        // change the text       $(this).text("stop animation");        // start a new intervall with current speed-slider value       initScroll = setInterval(patternScroller,  speed);        // fade in  all elements with the "foranimation" class       $(".foranimation").stop().fadeTo(800, 1);     } else {        // remove the class       pattern.removeClass("scrolling");        // change the button text       $(this).text("start  animation");        // clear the interval again       clearInterval(initScroll);        // fade out all elements with the "foranimation" class       $(".foranimation").stop().fadeTo(800,  0);    }     // change the  default link-behavior    return false; }); 

This is the last button-function we need for this project.

It will start and stop the animation of our pattern. To distinguish if the animation is already started or not, we are again adding and removing a class ("scrolling"). If the button does not have this class yet we are adding it, initiate an interval with the current value of our "speed" variable. If it has this class, we remove it and clear this interval again. For a little bit eye candy we are again fading all elements with the class "foranimation" in and out.

That's All Folks!

You should now have a Flash-like color and pattern morphing logo, using only a transparent PNG as mask and a few jQuery functions. You can take a look at the demo by clicking here or download all files by clicking here.

If you have any questions or need help with any of the steps, feel free to ask them in the comments!

Happy coding!

A Crash Course in Creating E-Commerce Websites with WordPress

Posted: 23 Mar 2010 03:00 AM PDT

WordPress is an awesome publishing platform which is utilized everywhere these days. You will find WordPress development from Harvard Gazette to Andy Roddick's official website. In this 1st article of 1st E-Commerce week, we will learn how to create a website which has online store's functionalities in it. In simple words we will create a fully functional electronic store. We will also talk about building e-commerce themes from a developer's point of view.

Cheap SSL CertificatesE-commerce week is sponsored by SSLmatic which sells SSL certificates for much cheaper prices (RapidSSL, Geotrust, Verisign) and offers great support. Check their site to get the cheap SSL certificates.

Who should read this tutorial?

If you have not ever created an e-commerce website before, then this crash course is best-suited for you. I am considering that you are totally an idiot when it comes to e-commerce websites. At the end we will also talk about how a developer can integrate e-commerce features in his WordPress theme. So I will say this tutorial will take you from beginner level and at the end you can continue with creating e-commerce websites with WordPress as a developer.

What we will learn in this tutorial?

We will create a demo store using WP e-Commerce and WordPress. At the end there will be a discussion about how to develop e-commerce ready WordPress themes.

Our Main tool:  WP e-Commerce?

There are a lot of free and premium e-commerce plugins available to enhance WordPress for e-commerce functionality but we are going to use WP e-Commerce. The reasons why we have picked it out are pretty simple.

Why Use WP e-Commerce?

  • Free and open source (You are free to modify its code and to share it with others).
  • The Oldest one: Yes, WP e-Commerce is the first ever plugin created to deal with e-commerce in WordPress. So it has a lot of nice features which shows its maturity like many shipping solutions and so on.
  • Free support forums and most importantly a very friendly support team.
  • It offers template tags to integrate it in your WordPress theme and hence easy to design themes which have e-commerce functionalities in them.
  • Premium Modules: If you don't know how to code or have less time for finalizing a client project, you can always buy some premium modules of WP e-Commerce from their store to extend and enhance some features of your e-store.

Pro Tip: Setting up the development environment

It is always the best practice to set up WordPress on localhost as it fastens the process of development. After setting it up, you have no need to use any ftp program to upload files to servers. In short, hassle free development and it increases  productivity a lot. So this is highly recommended for you. If you are on windows or Linux you can use xampp. For mac lovers, I will suggest to use mamp. Follow these short and easy tutorials on how to setup local host on your own computer.

Resources:

  1. Setting Up WordPress On Your PC/Linux Using XAMPP
  2. Installing WordPress Locally on Your Mac With MAMP

Moreover I am using jQ, an awesome free theme for WordPress. How ever this tutorial should work fine with all bugs free themes.

Let's do some real action. Fasten your seat belts as we are ready to start our development.

Installing the plugin

You can install WP e-Commerce from official plugins repository or from its official website. After activation, you will find a tab named Products below the comments tab. We will start from settings and then we will create some products to finally set up our demo store.

Settings WP e-Commerce>General

The first sub-tab under the settings tab is of general options. You can set your location, target markets and currency in which you will sell products. You can also set additional tax which will be applied on the top of your product price. For example in Pakistan, each business has to pay 15% of the total sales as general sales tax.

Settings WP e-Commerce>Presentation

The presentation tab is all about how you want to show your store. Instinct, the company behind WP e-Commerce also offers a gold cart with more options. You can say that it's a premium version with more features so if you see some options disabled in settings, don't worry. There is nothing wrong with your server permissions or installation method. You can only enable them after buying Gold Cart.

Most of the options in this tab are pretty self explanatory.  You can choose button types and choosing whether to show breadcrumbs, product ratings or not. Show Postage and Packaging means that you want to show the shipping charges on your product pages or not.

Product page settings allow you to customize the layout of product pages. You can select different layouts (only for gold cart) and different themes to show products. WP e-Commerce comes with three built-in themes. 3rd option is what group of products you want to show on product pages. The concept of product groups is a bit complex and we will take a look on it later. For now, just take them as categories which help you in categorizing products in different ways as well as helping your customers in finding products easily and quickly.

Shopping cart settings allows you to choose where you want to show cart. You can select different options ranging from widgets to manual insertion of template tag. Sliding cart enables your customers to maximize and minimize the shopping cart using +/- buttons and the last option has been explained already.

Before going to next section of settings, it will be good if you learn what product groups are.

What are product groups?

You can take them as categories and tags built in with WordPress. Actually WP e-Commerce uses pages for all its needs and WordPress don't allow you to categorize pages. That's why the plugin comes with product groups. For example if you are creating a theme store (download goodies shop) you can make product groups of WordPress, tumblr, Drupal and Joomla while you can also categorize all the themes with respect of colors or some specific features. Hopefully you got the point. Just think that you can group product of same features with help of these product groups. I will try to make this concept clearer when we will create our product groups.

Let's get back to Settings of our E-Store

While creating a product group you can give description and thumbnail of that group. In Product Group settings you can choose which parameters to show on product pages.

Thumbnails are pretty self explanatory. You can also choose pagination. If enabled, it will divide your products into different pages just like WordPress pagination. You can also choose whether to use IntenseDebate or not.

Settings WP e-Commerce>Admin

Here you can setup your digital goodies store. You can set how much time a user can download a specific file. You can also lock downloads to that specific ip from which orders has been placed. You can also set default email addresses for sending different notifications to customer and for your own record.

You can also write custom messages here which will be sent out to your customers on different events and also to the admin of e-store. At the end of this setting page you can give link to different pages. You will have to set page links after changing permalink structure.

Settings WP e-Commerce>Shipping

You can setup all the shipping options here. You can choose different shipping schemes like flat rate and weight rate. The plugin will automatically calculate the shipping charges and will add these charges on top of your product price. WP e-Commerce has built in support for ShipWire which is an order fulfillment company for online vendors. You can create some kind of conditions/layers. For example you can set rate if product's weight is greater than 4 pounds. Remember you don't need these options if you are going to set up a digital products store.

Settings WP e-Commerce>Payments Options

The most important part of an e-commerce store is payment gateways. WP e-commerce comes bundled with 2 Payment Gateways, paypal and google checkout. You can also select Manual Payment/Test Gateway if you want to receive payments using money orders or online transactions to your bank account.

Using import tab you can import data of your previously made products from a csv file.

Settings WP e-Commerce>Checkout

This is last step in setting up WP e-Commerce is setting up the checkout form. You can implement the restriction of registration before checking out. Remember that it will only work if you will check "Any one can register" box in WordPress general website settings.

So we are done with our settings. Let's create some product groups and products so that we can have a functional e-store.

Creating Product Groups and Categories

We are going to create a t-shirt store from where people can buy t-shirts. So we are getting into t-shirt business.:) Just think how you can group t-shirts? You can group them by size, by brand, by color and also by sex. Then we can have sub groups under these parameters to organize things more professionally. I have come up with following groups to set up demo store.

T-Shirts

  • Color
    • Black
    • Blue
  • Brand
    • Nike
    • Adidas

Let's start adding them. Go to Products>Categories. First of all add a new group there and after that you can create categories in it. This is as simple as creating categories for WordPress. Take products as categories and "categories" as sub-categories.

After this step you will be able to select t-shirts from drop down menu. Select then edit it and add sub-categories to it.

The concept of adding categories can confuse you a bit. Best way to understand it to play with it as long as you become a master. Don't forget to delete two dummy categories "brands" and "categories". This is what I have after adding all the categories.

So we are done with categories. Let's move towards products.

Creating your first Product with WordPress and WP e-Commerce

Go to Products>Products. You can add new products here. You will see a WYSIWYG editor just like WordPress post editor where you can fill all the details. Some things which are important to define are given below

SKU: is abbreviation of Stock Keeping Unit. It's a general term used in our everyday life. In store it is an identifier of specific product just like each post in WordPress has unique id. I am showing you process of adding one t-shirt. You can add others products with some method.

You can also choose inventory to keep track of your store. Moreover you will have to upload product image here. After adding two products, this is how my product dashboard looks like.

After finalizing products, its time to add widgets to your WordPress theme. Go to Appearance> Widgets. Add shopping cart widget and product groups widget to sidebar. It will give an awesome look to your e-store.

You can now see how our store looks like.

Single Product Page

You can also use products page as home page by going to WordPress reading settings if you don't want a blog at all. Another tip is to utilize wp-hide-post for hiding some pages so that no one can access shopping cart page and order pages directly.

Short Codes:

You can use short codes for showing specific products and product groups inside posts and pages. You can get a short code by editing the category. Just see the following screenshot for better understanding.  Same is the case for products.

Integrating WP e-Commerce in your WordPress theme

Another great feature of WP e-Commerce is its template tags which make the job of integrating e-Commerce functionalities in a WordPress theme very easier.

You can use following template tags to include different functionalities in your WordPress theme.

 <?php echo nzshpcrt_shopping_basket(); ?>// Show Shopping Carts <?php nzshpcrt_latest_product(); ?>// Show Display Latest Products <?php show_cats_brands(); ?>// Show all Categories <?php echo wpsc_buy_now_button(1); ?>//Show Buy Now Button <?php echo wpsc_add_to_cart_button(1); ?>// Display Add to Cart Button 

Extending WP e-Commerce

Because of its reputation, there are lots of premium and community plugins available to extend the functionality of WordPress. You can take a look on this page for the plugins and themes available to extend WP e-Commerce.

I am sure that you enjoyed this crash course in building e-commerce websites with WordPress. Feel free to leave your questions and thoughts about the article.

Cheap SSL CertificatesE-commerce week is sponsored by SSLmatic which sells SSL certificates for much cheaper prices (RapidSSL, Geotrust, Verisign) and offers great support. Besides standard SSL certificates, wildcard and EV certificates are offered with discounts too. Check their site to get the cheap SSL certificates.

Comments (0)

Post a Comment