Tuesday, July 31, 2012

Some Powerful Object Oriented Javacript

So here is some code I wrote to 'make' javascript classes a little bit easier. In essence what the code below does is, you create an object like so:

var aPerson = myObjWrap("Name, Age, Gender");

from there, my code creates the 'aPerson' object so you can perform functions on it like so:

aPerson.setName("Brendon");
aPerson.setAge("24");
aPerson.setGender("Male");

And then if you want to see what the object contains you can do something like this:

console.log("Name: " + aPerson.getName() + " Age:" + aPerson.getAge() + " Gender: " + aPerson.getGender() );

 Which would spit out:  Name: Brendon Age:24 Gender: Male

So here's the code
//code for trim
if (!String.prototype.trim) {
    String.prototype.trim = function () {  
        return this.replace(/^\s+|\s+$/g,'');  
    };  
}

$(document).ready(function() {
    function AddGettersAndSetters(object) {
        for (var field in object) {
            if (typeof(object[field]) != 'function') {
                if (typeof(object[field]) == 'object') {
                    for (var f = 0; f < object[field][0].length; f++) {
                        AssignFunctions(object, object[field][0][f].trim() );
                    }
                } else {
                    AssignFunctions(object, field);
                }
            }
        }

        function AssignFunctions(object, field) {
            object['get' + field] = function() {
                return this[field];
            };

            object['set' + field] = function(value) {
                this[field] = value;
            };
        }
    }

    var myObjWrap = function(fields) {
        var functions = new Array(fields.split(","));
        var theObj = {
            fields: functions
        };
        var gs = new AddGettersAndSetters(theObj);
        return theObj;       
    }

    var aPerson = myObjWrap("Name, Age, Gender");

    console.log( aPerson );
    
    aPerson.setName("Brendon");
    aPerson.setAge("24");
    aPerson.setGender("Male");

    console.log( aPerson );

    
    console.log("Name: " + aPerson.getName() + " Age:" + aPerson.getAge()
 + " Gender: " + aPerson.getGender() );
   
});

Thursday, May 17, 2012

Getting started with creating Mobile App like websites, quickly and Easily

So, I am assuming if you have come across this posting, you're looking to create a mobile friendly website of your current website or from scratch. Well, you've come to the right place. I am going to assume you have at least some familiarity with things like CSS, HTML, jQuery & Javascript, and we'll go from there.

So how do we begin? Step one. Have a design, well at-least in mind. To create something mobile friendly, your content is going to have to be presented in a mobile friendly fashion. In alot of cases, these changes can be made very easily and I'll outline a few examples. So without further ado, Lets start.

Step 1.

Start with the correct html structure and  doctype.

In this case, there are two doctypes you should look into using, the mobile doctype like so:

<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN"
"http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">

or the standard HTML5 doctype like so:


<!DOCTYPE html>


Using one of theses doctypes will help your application render better in Mobile devices.

Step 2.

Add in the appropriate "meta tags"

<meta name="HandheldFriendly" content="true" /> <meta name="viewport" content="user-scalable=no" /> <meta name="viewport" content="width=480" /> 

The meta tags above are going to give you much better cross device look and consistency. As you can see, in my example, I am assuming the viewport should be 480px wide (I have found this yields nice results on most devices).

Add in the optional "Meta tags"

<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
These are i-Device specific meta tags (see apple documenation

And lastly, add some polish (note file paths will be unique and you'll have to change).

<link rel="shortcut icon" href="/GetSiteFile/favicon.ico" />

These are all Apple specific items

<link rel="apple-touch-icon" href="/GetSiteFile/touch-icon-iphone.png" />
<link rel="apple-touch-icon" sizes="72x72" href="/GetSiteFile/touch-icon-ipad.png" />
<link rel="apple-touch-icon" sizes="114x114" href="/GetSiteFile/touch-icon-iphone4.png" />
<link rel="apple-touch-startup-image" href="/GetSiteFile/startup.png">
Step 3.

We have our doctype, we have our meta tags and other tid bits setup, now how about actually displaying content. This goes back to having a design in mind, and designing in mind for mobile.

Mobile Layouts have to be tuned to work with less real-estate, which means, cut the crap, and only show what is relevant. This can be a bit challenging when scaling from a Desktop website to a Mobile site, but its not impossible.

A typical Menu on a website may look something like this:

[Option 1][Option2][Option3][Option4][Option5]

but in a mobile site, that should be re-structured to something like this:

[Option 1]
[Option 2]
[Option 3]
[Option 4]
etc...

Step 4.

Consider implementing touch gestures (where applicable). Not everything, or everyone will require swipe gestures for items, but in some instances it makes sense to include it. To keep this posting short, I'll leave you with a nice little jQuery plugin which I have found most useful and easy to use.

http://www.netcu.de/jquery-touchwipe-iphone-ipad-library



Step 5.

The rest is for you, this is very quick list of things to create a mobile website quickly.

Other things to investigate if you haven't
-Using a mobile framework like Sencha Touch
-Using a framework like Less.js to make styling changes easier

I will post more relevant items when I think of them.



View this: http://bren1818.blogspot.ca/2012/09/simple-web-app-for-android-and-ios.html (A newer post)

















Wednesday, June 8, 2011

Magento

If any of you work on E-stores, you probably have come across, or developed a store using Magento. Magento is a powerful php e-store, which is flexible, configurable, fairly easy to style and nice to work with. The other thing I really like about Magento is the community. It is rare that you run into an issue in Magento which you can't fix with a quick Google. There are plenty of forums and websites devoted to Magento help. Seeing as how I have now developed a few Magento sites, this time around  decided to document the problems one will typically run into. I have layed some of this out, and with luck, it will help someone out.

Remove Components (hide em)
System > Cofiguration > Advanced and disable ex:  Mage_Newsletter


Change Layout
Open the \app\design\frontend\nameofProj\default\layout\catalog.xml
find:

<block type="page/html" name="root" output="toHtml" template="current Template">
to
<block type="page/html" name="root" output="toHtml" template="page/2columns-right.phtml">
eg: one-column.phtml


File Locations



Product View Template
\app\design\frontend\YourPath\default\template\catalog\product\view.phtml


Image Maginifcation for product
\app\design\frontend\YourPath\default\template\catalog\product\view\media.phtml



Varients Code Location
\app\design\frontend\YourPath\default\template\catalog\product\view\options\wrapper.phtml


Bottom of product Code Location
\app\design\frontend\YourPath\default\template\catalog\product\view\options\bottom.phtml 



Menu for Categories
\app\design\frontend\YourPath\default\template\catalog\navigation\top.phtml


-simply add list items here with custom links which may not be in the categories by default
<?php echo $_menu ?>
<li id="storeHome" class="level0 nave-1 level-top first parent">
        <a class="level-top" href="/index.php">
                <span>HOME</span>
        </a>
</li>


Header of Site
\app\design\frontend\YourPath\default\template\page\html\header.phtml
/*This is where you can change the logo, modify the top links etc*/


Footer of Site
\app\design\frontend\YourPath\default\template\page\html\footer.phtml
-comment out <?php echo $this->getCopyright() ?> replace with your own code etc


Grid/List view Code
\app\design\frontend\YourPath\default\template\catalog\product\list.phtml
-This is where you can chane image sizes and which details are shown on the home page




toolbar for pages
\app\design\frontend\YourPath\default\template\catalog\product\list\toolbar.phtml


page numbers in pagination  - you can change your divider ~line 94
\app\design\frontend\YourPath\default\template\page\html\pager.phtml


breadcrumbs 
\app\design\frontend\YourPath\default\template\page\html\breadcrumbs.phtml
/*change formatting of breadcrumbs*/


Login Page

\app\design\frontend\YourPath\default\template\customer\form\login.phtml

Register
\app\design\frontend\YourPath\default\template\customer\form\register.phtml

Shopping Cart
\app\design\frontend\YourPath\default\template\checkout\cart.phtml

Dashboard
\app\design\frontend\YourPath\default\template\customer\account\dashboard.phtml

Sub Categories Page
\app\design\frontend\YourPath\default\template\catalog\category\view.phtml

Tricks
Use JQuery on pages:

<script type="text/javascript" src="/pathTo/jquery.min.js"></script>
<script type="text/javascript">
   //<![CDATA[
jQuery.noConflict();
var $j = jQuery.noConflict(); //alias jquery with j$
$j(function(){
$j('button.button span span').html(""); /*can be used to hide span text and fix some bugs if using images*/
});
//]]>
   </script>

Links to Sitemap
/catalog/seo_sitemap/product/ -product sitemap
/catalog/seo_sitemap/category/ -category sitemap

Hide index.php in the store view:
In admin, System>Configuration>Web Tab. Under Search Engine Optimization, change User Webserver rewrites to Yes.

Check if a user is logged in:
$this->helper('customer')->isLoggedIn()

<?php
if( $this->helper('customer')->isLoggedIn() ){
?>
<li class="level0 nav-cat1"><a href="/customer/account/login/"><span>logout</span></a></li>
<?php
}else{
?>
<li class="level0 nav-cat1"><a href="/customer/account/login/"><span>login</span></a></li>
<?php } ?>


Display Product Skus: (for product page)
<p class="itemSku">Item #<?php echo $this->htmlEscape($_product->getSku()) ?></p>

Change the number of displayed products in list/grid view:

Admin -> System > Catalog > frontend
and: app/design/frontend/default/default/layout/catalog.xml


Embed Contact form in CMS page:


<!-- CONTACT FORM -->
{{block type="core/template" name="contactForm" form_action="/contacts/index/post" template="contacts/form.phtml"}}
<!-- END OF CONTACT FORM -->


Get the Sub-Category Page to display Images: (replace your

\app\design\frontend\YourPath\default\template\catalog\category\view.phtml with below code)

<?php
$_category = $this->getCurrentCategory();
$collection = Mage::getModel('catalog/category')->getCategories($_category->entity_id);

$rootcat = $_category->entity_id;
$cat = Mage::getModel('catalog/category')->load($rootcat);
$child = $cat->getChildren();
//echo $child;

if($child)
{
$helper = Mage::helper('catalog/category');
$_helper = $this->helper('catalog/output');
?>
<div class="category-custom-products">
<table>
<tr>
<td valign="top" width="405">
<h1 class="page-title"><?php echo $_helper->categoryAttribute($_category, $_category->getName(), 'name') ?></h1>
<?php
$_imgUrl = $_category->getImageUrl();
echo '<img id="ProductCategoryImage" src="'.$_imgUrl.'"/>';
?>

</td>
<td width="40">

</td>
<td valign="top">
<div class="products-grid categories-grid">

<?foreach ($collection as $cat):?>
<?php if($_category->getIsActive()):?>
<?php
$cur_category = Mage::getModel('catalog/category')->load($cat->getId());
$_imgUrl = $cur_category->getImageUrl();
?>
<div class="categoryItem">
<a class="categoryImageLink" href="<?php echo $helper->getCategoryUrl($cat);?>"><?php echo '<img class="categoryImg" width="216" height="180" id="ProductCategoryImage" src="'.$_imgUrl.'"/>'; ?></a>
<a class="categoryProductLink" href="<?php echo $helper->getCategoryUrl($cat);?>"><?php echo $cat->getName();?></a>
<a class="viewDetailsLink" href="<?php echo $helper->getCategoryUrl($cat);?>">view details</a>
</div>

<?php endif?>
<?php endforeach;?>
</div>
</td>
</tr>
</table>
</div>
<?php
}
else
{
?>
<?php echo $this->getProductListHtml() ?>
<?php
}
?>


Hope this helps someone out. I'll try to add to it if I learn something interesting.

Saturday, May 28, 2011

Advanced Image Scaling & Preloading - Jquery

Hi All, this is my second jQuery plugin I have written, and again want to contribute to the world. Feel free to use in any fashion you like, but please leave my name, link to blog, and email in the source code.

This plugin is called "imgResizer" and it is for pre-loading and scaling images.

You can configure it with the following options:
height : integer               (defaults to 300)
width  : integer              (defaults to 300)

loadingImage : string     (defaults to "images/loading.gif")
failImage: string             (defaults to "images/fail.png")
autoCenterImage: string (defaults to "true")

**note the autoCenterImage uses relative & absolute position. If it is set to true, the image will always sit within a box with the height and width as specified. If it is set to false, the image will just be scaled to the dimensions and pre-loaded.

***you will need to create or find a loading image and fail image, and place them in your images folder.


(function($){
$.fn.imgResize = function(options) 
{
//function by Brendon Irwin | 2011 | http://bren1818.blogspot.com/ | bren1818@gmail.com
//Last update: May 24th 2011

//set defaults
var defaults = {
  height: "300",
  width: "300",
  loadingImage: "images/loading.gif",
  failImage: "images/fail.png",
  autoCenterImage: "true"
};
 
var options = $.extend(defaults, options);
//If there are one or more elements, return them  
return this.each(function() {
$(this).wrap('<div class="loader" style="height: ' + options.height + '; width: ' + options.width +'; overflow: hidden; position: relative; background-image: url(' + options.loadingImage + '); background-position: center; background-repeat: no-repeat; "/>');
$(this).css({'display':'none'});
//load the image
$(this).load(function(){
$(this).css({'display':'none'});
$(this).css({'background-image' : 'url(' + options.loadingImage + ')', 'background-position' : 'center', 'background-repeat' : 'no-repeat'});
},function(){
//load complete, begin scaling
var maxWidth = options.width; // Max width for the image 
var maxHeight = options.height;     // Max height for the image
var ratio = 0;   // Used for aspect ratio
var width = $(this).width();     // Current image width
var height = $(this).height();   // Current image height

// Check if the current width is larger than the max
if(width > maxWidth){
ratio = maxWidth / width;   // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio);   // Scale height based on ratio
height = height * ratio;     // Reset height to match scaled image
width = width * ratio;     // Reset width to match scaled image
}

// Check if current height is larger than max
if(height > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight);   // Set new height
$(this).css("width", width * ratio);     // Scale width based on ratio
width = width * ratio;     // Reset width to match scaled image
}

if(height == maxHeight)
{
$(this).css("top", "0px");
}

if(options.autoCenterImage == "true")
{
$(this).css('position', 'absolute');
//center left
if( width  <= options.width){
var lef= ( (options.width- parseInt(width) ) / 2 ) + 'px'; 
$(this).css('left', lef);
}else{
$(this).css('left', '0px');
}

//center top
if( height < options.height) {
var top = ( (options.height - parseInt(height) ) / 2 ) + 'px';  
$(this).css('top', top );
}

if(height == options.height){
$(this).css('top', '0px' );
}
}else{ //No Auto-Centering
var w, h;
h = $(this).height() + 'px';
w = $(this).width() + 'px';
$(this).parent().css('height' , h );//, $(this).width() + 'px' });
$(this).parent().css('width' , w );
}

//Fade image in
$(this).fadeIn(5000, function() { 
$(this).css({'display':'block'});
$(this).parent().css({'background-image' : 'url(none)'});
});//end fadeIn function

});// end load function


$(this).error(function() {
$(this).attr('src' , options.failImage);
$(this).load(function(){ $(this).css({'display':'none'}); },function(){
//fade image in
$(this).fadeIn(5000, function() {
$(this).css({'display':'block'});
$(this).css({'background-image' : 'url(none)'});
});//end fadeIn
});//end load
});//end error


});// endeach function
 
};//end function resize
})(jQuery);//end function deceleration