My studying notebook

Showing posts with label Javscript. Show all posts
Showing posts with label Javscript. Show all posts

2010/07/02

Convert rgb color to hex color

7/02/2010 11:00:00 AM Posted by Unknown , , , 2 comments
If you have written HTML file, you must know that how to assign color to DOM element. You just need to assign CSS style to
DOM element like

<span style="color:#ff0000">This is text</span>
It is very simple. But, we may want to change the color
by Javascript like color picker. What's the problem? You may get the "rgb(255, 0, 0)" color value by Javascript.
Then, you have to convert rgb to hex color or convert hex to rgb color. The following is simple code.

rgb to hex


function rgb2hex(rgb){
var hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
var hex = function(x){
return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
};
var tmp = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
var color = hex(tmp[1]) + hex(tmp[2]) + hex(tmp[3]);
return color;
}

hex to rgb

function hex2rgb(v){
if (/^[0-9A-F]{3}$|^[0-9A-F]{6}$/.test(v.toUpperCase())) {
if (v.length == 3) {
v = v.match(/[0-9A-F]/g);
v = v[0] + v[0] + v[1] + v[1] + v[2] + v[2];
this.value = v;
}

var r = parseInt(v.substr(0, 2), 16);
var g = parseInt(v.substr(2, 2), 16);
var b = parseInt(v.substr(4, 2), 16);
return [r, g, b].join(',');
}
return v;
}

Result

var input = $(this).css('color'); // rgb(255,0,0)

var hex = rgb2hex(input); //ff0000
var rgb = hex2rgb(hex); //255,0,0

2009/11/02

JSONC Of Picasa Web Ablum

11/02/2009 11:14:00 PM Posted by Unknown , , , 2 comments
What is JSON and JSONC?

JSON, short for JavaScript Object Notation, is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects). - wiki

JSONC: Clean, Compact, and Customizable. Minimize the number of JavaScript objects

You guys might have used a lot of JSON data in your web page, web application etc. If you are familiar with Blogger template, you might ever received your Picasa web album JSON format data by calling Javascript function in your blogger by using this URL
http://picasaweb.google.com/data/feed/api/user/userID?alt=json&callback=?

Whatever you receive JSON data by Javascript callback function or jQuery Ajax callback funtion. You need to parse callback json data and get the data what you need. There are too many objects in that data. It's a little complicate to get current fields you need.

Google Data Protocol support JSONC data format return in Google Web Album. That let you guys can receive data from Google Web Album more easy than before. What do we receive the JSONC format data. Changing feed URL to
http://picasaweb.google.com/data/feed/api/user/userID?v=2&alt=jsonc&callback=?

Conclusion

It's a easy way to receive your Google Web Album data by modify feed URL arguments. The simple object data means you can decrease callback response time and increase the web page performance. If you are interested in performance articles, you should read following link

Reference

2009/01/08

Audio Player Wordpress Plugin Wizard

1/08/2009 10:57:00 PM Posted by Unknown , , , 1 comment
Google like Audio Player WordPress Plugin Wizard

Background:

In my another blog www.cage1016.blogspot.com. I wrote a post about a mobile answer tone 別別掛. The point is i found many audio(mp3) players that i can embed mp3 in my blog easily. Final, i found a post Inline Mp3 Player(WordPress version) and talk about a simple inline audio player. It's Audio Player Wordpress plugin. The audio player support you can setting simple options to change the look of palyer. for example: background color, Text color, enable auotplay and enable loop play.


<object id="audioplayer1" height="24" width="290" data="http://cage.chung.googlepages.com/player.swf" type="application/x-shockwave-flash">
<param value="http://cage.chung.googlepages.com/player.swf" name="movie"/>
<param value="playerID=2&bg=0xCDDFF3&leftbg=0x357DCE&lefticon=0xF2F2F2&rightbg=0xF06A51&rightbghover=0xAF2910&righticon=0xF2F2F2&righticonhover=0xFFFFFF&text=0x357DCE&slider=0x357DCE&track=0xFFFFFF&border=0xFFFFFF&loader=0xAF2910&soundFile=xxxx" name="FlashVars"/>
<param value="high" name="quality"/>
<param value="false" name="menu"/>
<param value="#FFFFFF" name="bgcolor"/>
</object>


Above code is the audio player plugin syntax. we can see that there are few options are relative to Color bg, leftbg etc. It's a little difficult to setting these color to product a beautiful look. Or if you don't real understand the html color hex code. I think that the best way is you can change the option color directly. And few ago, when i studied Google Static Map API. In button of Static Maps API Developer's Guide has a firendly wizard(Goolge Static Map Wizard) support a simple UI-dirven way to generate static maps via a simple UI interface.

So, i wirte some javascript to support a similar simple UI-dirven way to generate Audio Player Wordpress Plugin. Just 3 steps and few settings. You can get the beautiful audio player.

Explain:

The Audio Player WordPress Plugin Wizard is Google style like. Build All by whole javascript and use excellent sliders are courtesy of Erik Arvidsson over at WebFX. The simple UI-dirven way let you can build your player look easily and only 3 steps.

Audio Player Color Schema:

As you can see. There are 9 color you can change.

Step1: Customize your audio player setting


First, you have 3 things to do. Choose the Audio Player Plugin play.swf url and choose the auido file url you want to embed in your blog (This 2 items have default, if you want test first and don't mind it). Then, there are 3 color schema patten. Choose one and you will see the colors bind to table of step2.

Step2: Customize audio player options of colors, autoplay and loop



After the color schema binded. I set autoplay and loop field are ture. If the player url and audio file url are current. Now you will listen to the music. In this step, you can change the color of palyer you want. Click the ratio button of option column. The color picker will be setting to equal the option color you click. You can change the color by darp the red, green and blue or type the html color hex code directly. The player will update if you any change the color, autoplay, loop setting and.

step3:Generate audio player embed code



Now, you can copy this code to embed in you blog.

enjoying~~~


2008/06/23

[Javascript & Css] CountDown

6/23/2008 09:30:00 PM Posted by Unknown , , 2 comments

google code jam 2008的首頁中,有一個斗大的CountDown,正在一秒一秒的倒數著報名截止的時間(07/16/2008 23:00:00 UTC)。看到這一個Counter就想起讀研究所的時候,幫老師帶大學部的助教,在作業上傳的頁面也作了一個CountDown,倒數著學生上傳最後的期限(每一次Reload時間才會改變),不過看起來的品質就沒有這一個的好,所以想說就試著分析一下。

最主要的部份為 Javascript + Css + DHTML 構成,主要由Javascript帶入DOM元素計算,並更新DOM元素CSS屬性來顯示不同時間。


Live Demo | Download

HTML
<span id="day0" class="num_0">0</span>
<span id="day1" class="num_0">0</span>
<!-- day -->
<span class="hp_counter_divider">:</span>
<span id="hour0" class="num_0">0</span>
<span id="hour1" class="num_0">0</span>
<!-- hour -->
<span class="hp_counter_divider">:</span>
<span id="min0" class="num_0">0</span>
<span id="min1" class="num_0">0</span>
<!-- minute -->
<span class="hp_counter_divider">:</span>
<span id="sec0" class="num_0">0</span>
<span id="sec1" class="num_0">0</span>
<!-- second -->

Javascript

<script type="text/javascript">
// create the countdown
new Countdown({
toDate: new Date(Date.parse("07/04/2008 23:00:00 UTC")),
dayElements: [el("day0"), el("day1")],
hourElements: [el("hour0"), el("hour1")],
minuteElements: [el("min0"), el("min1")],
secondElements: [el("sec0"), el("sec1")]
});
</script>

Countdown是在Javascript中使用了OO中封裝的技巧,在Countdown Function中定義了屬性(toDate, dayElement, hourElements, minuteElements, secondElements),上由el(var el = function(n) { return document.getElementById(n); })直接帶入DOM元素中相對應的值進行計算與更新CSS屬性

counter.js

function Countdown(config) {
this.toDate = config.toDate;
this.dayElements = config.dayElements;
this.hourElements = config.hourElements;
this.minuteElements = config.minuteElements;
this.secondElements = config.secondElements;
this.timer = undefined;

/**
* Updates the countdown display.
*/
this.update = function () {
var elapsed = (this.toDate.getTime() - (new Date()).getTime()) / 1000;
this.setDisplay(
this.age(elapsed, Countdown.DAY), this.age(elapsed, Countdown.HOUR), this.age(elapsed, Countdown.MINUTE), this.age(elapsed, Countdown.SECOND));
};

/**
* returns the age
*/
this.age = function (seconds, t) {
if (seconds <= 0) {
return[0, 0];
}
var s = ((Math.floor(seconds / t.unit)) % t.length).toString();
return (s.length < 2) ? ["0", s] : [s.substring(0, 1), s.substring(1, 2)];
};

/**
* Starts the countdown timer
*/
this.setDisplay = function (day, hour, minute, second) {
this.display(day, this.dayElements);
this.display(hour, this.hourElements);
this.display(minute, this.minuteElements);
this.display(second, this.secondElements);
};

/**
* Does the display
*/
this.display = function (num, els) {
els[0].innerHTML = num[0];
els[1].innerHTML = num[1];
els[0].className = "num_" + num[0];
els[1].className = "num_" + num[1];
};

// start timer
var that = this;
this.timer = setInterval(function () {
that.update()
},
250);
return;
}

/**
* some constants
*/
Countdown.DAY = {
unit: 86400,
length: 100000
};
Countdown.HOUR = {
unit: 3600,
length: 24
};
Countdown.MINUTE = {
unit: 60,
length: 60
};
Countdown.SECOND = {
unit: 1,
length: 60
};


counter.js中,一樣利用this.property封裝屬性、function()表示Method,計算出與截止時間的時間差,換算成 DD,HH,MM,SS 格式。在this.display中動態改變DOM元素值與CSS屬性


CSS

google code jam 2008的首頁CountDown中,Days,Hours,Mins,Secs皆是利用CSS background-position 屬性來顯示,在CSS中預先定義好0-9每個數字的background-position,在DOM元素改變CSS屬性時,即可套用CSS不同數字的背景圖

/* Number "0" */
#CounterCount span.num_0 {
background - position: 0px 4px;
}
/* Number "1" */
#CounterCount span.num_1 {
background - position: 0px - 21px;
}
/* Number "2" */
#CounterCount span.num_2 {
background - position: 0px - 46px;
}



ps. OOPS implementation in JavaScript可以參考Exploring OOPS - JavaScript Style serials by mastergaurav (code project)
ps. 07/16/2008 23:00:00 UTC, UTC(Coordinated Universal Time), 台灣為東8區,所以時間為UTC+8即可

2008/06/03

Css-Switcher

6/03/2008 09:46:00 PM Posted by Unknown , , 1 comment
利用Css可以快速改變HTML的風格樣式。在網頁中載入Css的方法則可以使用3種


<link rel="stylesheet" href="css/Clean.css" type="text/css">
<!--Method2: Embed Style-->
<style type="text/css">/*Css Code*/</style>
<!--Method3: Inline Sytle-->
<p style="color: red;">this is paragraph</p>


除了使用設計好的Css樣式之外,Javascript還可以讓我們動態的改變目前網頁中使用的樣式

<link rel="stylesheet" href="css/Clean.css" type="text/css">
<link rel="alternate stylesheet" href="css/Digg.css" type="text/css" title="Digg">
<link rel="alternate stylesheet" href="css/Flickr.css" type="text/css" title="Flickr">

Clean.css為預設網頁使用樣式,Digg.css & Flickr.css則為Javascript動態載入之樣式

function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
}

function getActiveStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
return null;
}

function getPreferredStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) return a.getAttribute("title");
}
return null;
}

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < c =" ca[i];" c =" c.substring(1,c.length);" onload =" function(e)" cookie =" readCookie(" title =" cookie" onunload =" function(e)" title =" getActiveStyleSheet();" cookie =" readCookie(" title =" cookie">

在頁面中簡單的使用Hyperlink,將Css link中Title的參數指向Javascript中的setActiveStyleSheet Function

<a href="#" onclick="setActiveStyleSheet(''); return false;">預設載入的樣式</a>
<a href="#" onclick="setActiveStyleSheet('Digg'); return false;">動態載入Digg樣式</a>
<a href="#" onclick="setActiveStyleSheet('Flickr'); return false;">動態載入Flickr樣式</a>


Live Demo

2008/05/20

Showing Hyperlink Cues

5/20/2008 07:16:00 PM Posted by Unknown , 1 comment
HyperLink讓我們可以將視窗導到我們指定的頁面
包含打開特定格式之檔案、Send mail。
例如:

Google 首頁
mailto: me
View Holidays

我們都可以在HyperLink中完成這些動作

而上述3種的連結樣式若無特別指定
則會套用瀏覽器的預設值

除此之外
我們亦可以利用Css or Javascript為這些特別的連結
加上容易辦別的圖示
例如:
  • 外部連結檔案圖示
  • mailto: link 圖示

Cues With Css

利用Css為hyperlink加上小圖示
必需使用到Attribute選擇器(for IE 7, Firefox 2, Opera 9。browser-support#css)
由於IE6並不支援Attribute選擇器,所以就由Javascript來實作

a[href $='.pdf'] {
padding-right: 18px;
background: transparent url(icon_pdf.gif) no-repeat center right;
}
  1. a:Element 選擇器
  2. href:Attribute選擇器
  3. $:href 屬性以pdf結束

Cues With Javascript

由於在IE6並不支援Attribute Selector
所以就使用Javascript的語法來實作


function fileLinks() {
var fileLink;
if (document.getElementsByTagName('a')) {
for (var i = 0; (fileLink = document.getElementsByTagName('a')[i]); i++) {
if (fileLink.href.indexOf('http:') != -1) {
fileLink.setAttribute('target', '_blank');
fileLink.className = 'externalLink';
}
if (fileLink.href.indexOf('pdf') != -1){
fileLink.className = 'pdflink';
}
}
}
}
window.onload = function() {
fileLinks();
}


.externalLink {
padding-right: 14px;
background: url(App_Themes/MyTheme/Images/hyperlink.png) right center no-repeat;
}
.pdflink {
padding-right: 18px;
background: transparent url(App_Themes/MyTheme/Images/icon_ttf.gif) no-repeat center right;
}