public
Created

designPattern example - factory

  • Download Gist
fiddle.css
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
*{
margin:0;
padding:0;
}
body{
padding:30px;
}
.face{
border:1px solid #000;
position:relative;
float:left;
margin:5px;
padding:.5em .8em;
}
.happy{
background:#fff;
color:#000;
}
.unhappy{
background:#000;
color:#fff;
}
fiddle.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
(function(){
 
/* faces */
var faces_happy = [ '(・∀・)', '∩( ・ω・)∩', '(^o^)' ];
var faces_unhappy = [ '(;´Д`)', '(-_-;)', '(´;ω;`)' ];
 
/* create face element from received info.
This is why I called this "factory" */
window.generateFace = function(msg, isHappy){
var $el = $('<div class="face"></div>');
var nth = randomNum(0,2);
var face = isHappy ? faces_happy[nth] : faces_unhappy[nth];
$el.addClass(isHappy ? 'happy' : 'unhappy');
$el.text(face + ' ' + msg).bind('mouseenter', function(){
$el.shake();
});
return $el;
};
/* just shake it */
$.fn.shake = function(){
return this.each(function(){
$(this).stop()
.animate({ left: "-6px" }, 40).animate({ left: "6px" }, 40)
.animate({ left: "-6px" }, 40).animate({ left: "6px" }, 40)
.animate({ left: "0px" }, 40);
});
};
/* util */
function randomNum(from, to) {
return from + Math.floor( Math.random() * (to - from + 1) );
}
 
})();
 
$(function(){
generateFace('ひゃっほーい', true).appendTo('body');
generateFace('やたー', true).appendTo('body');
generateFace('うれぴー', true).appendTo('body');
generateFace('感激', true).appendTo('body');
generateFace('もうだめ', false).appendTo('body');
generateFace('あばばば', false).appendTo('body');
generateFace('死ぬ', false).appendTo('body');
generateFace('徹夜', false).appendTo('body');
});
fiddle.manifest
1 2 3 4 5
name: designPattern example - factory
description: http://jsfiddle.net/gh/gist/jQuery/1.6.2/1191790/ https://gist.github.com/1191790
authors:
- Takeshi Takatsudo
normalize_css: no

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.