Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Thursday, September 29, 2011

Cài đặt Accordion Slider tự động cho nhãn

Gần đây mình có thử nghiệm một plugin gọi là liteAccordion của tác giả Nicola Hibbert dành cho website để tạo hiệu ứng đàn xếp. Mình đã nghiên cứu và áp dụng tự động thành công cho blogspot, tạo hiệu ứng đàn xếp trượt theo chiều ngang với bài viết mới nhất theo nhãn tích hợp thành một slider thật mượt mà.



DEMO

Để cài đặt tiện ích bạn hãy thực hiện theo các bước sau đây:

Bước 1. Đăng nhập Blogger, vào Design >> Edit HTML (không chọn mở rộng mẫu tiện ích). Đặt đoạn code sau đây vào trước thẻ </body>. Đoạn code này chính là thư viện jQuery giúp tạo hiệu ứng đàn xếp.

  1. <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'/>
  2. <script type='text/javascript'>
  3. //<![CDATA[
  4. /*************************************************
  5. *
  6. * project: liteAccordion - horizontal accordion plugin for jQuery
  7. * author: Nicola Hibbert
  8. * url: http://nicolahibbert.com/horizontal-accordion-jquery-plugin
  9. * demo: http://www.nicolahibbert.com/demo/liteAccordion
  10. *
  11. * Version: 1.1.3
  12. * Copyright: (c) 2010-2011 Nicola Hibbert
  13. *
  14. /*************************************************/
  15. ;(function($) {
  16. $.fn.liteAccordion = function(options) {
  17. // defaults
  18. var defaults = {
  19. containerWidth : 940,
  20. containerHeight : 320,
  21. headerWidth : 48,
  22. firstSlide : 1,
  23. onActivate : function() {},
  24. slideSpeed : 800,
  25. slideCallback : function() {},
  26. autoPlay : false,
  27. pauseOnHover : false,
  28. cycleSpeed : 6000,
  29. theme : 'basic', // basic, light*, dark, stitch*
  30. rounded : false,
  31. enumerateSlides : false
  32. },
  33. // merge defaults with options in new settings object
  34. settings = $.extend({}, defaults, options),
  35. // define key variables
  36. $accordion = this,
  37. $slides = $accordion.find('li'),
  38. slideLen = $slides.length,
  39. slideWidth = settings.containerWidth - (slideLen * settings.headerWidth),
  40. $header = $slides.children('h2'),
  41. // core utility and animation methods
  42. utils = {
  43. getGroup : function(pos, index) {
  44. if (this.offsetLeft === pos.left) {
  45. return $header.slice(index + 1, slideLen).filter(function() { return this.offsetLeft === $header.index(this) * settings.headerWidth });
  46. } else if (this.offsetLeft === pos.right) {
  47. return $header.slice(0, index + 1).filter(function() { return this.offsetLeft === slideWidth + ($header.index(this) * settings.headerWidth) });
  48. }
  49. },
  50. nextSlide : function(slideIndex) {
  51. var slide = slideIndex + 1 || settings.firstSlide;
  52. // get index of next slide
  53. return function() {
  54. return slide++ % slideLen;
  55. }
  56. },
  57. play : function(slideIndex) {
  58. var getNext = utils.nextSlide((slideIndex) ? slideIndex : ''), // create closure
  59. start = function() {
  60. $header.eq(getNext()).click();
  61. };
  62. utils.playing = setInterval(start, settings.cycleSpeed);
  63. },
  64. pause : function() {
  65. clearInterval(utils.playing);
  66. },
  67. playing : 0,
  68. sentinel : false
  69. };
  70. // set container heights, widths, theme & corner style
  71. $accordion
  72. .height(settings.containerHeight)
  73. .width(settings.containerWidth)
  74. .addClass(settings.theme)
  75. .addClass(settings.rounded && 'rounded');
  76. // set tab width, height and selected class
  77. $header
  78. .width(settings.containerHeight)
  79. .height(settings.headerWidth)
  80. .eq(settings.firstSlide - 1).addClass('selected');
  81. // ie :(
  82. if ($.browser.msie) {
  83. if ($.browser.version.substr(0,1) > 8) {
  84. $header.css('filter', 'none');
  85. } else if ($.browser.version.substr(0,1) < 7) {
  86. return false;
  87. }
  88. }
  89. // set initial positions for each slide
  90. $header.each(function(index) {
  91. var $this = $(this),
  92. left = index * settings.headerWidth;
  93. if (index >= settings.firstSlide) left += slideWidth;
  94. $this
  95. .css('left', left)
  96. .next()
  97. .width(slideWidth)
  98. .css({ left : left, paddingLeft : settings.headerWidth });
  99. // add number to bottom of tab
  100. settings.enumerateSlides && $this.append('<b>' + (index + 1) + '</b>');
  101. });
  102. // bind event handler for activating slides
  103. $header.click(function(e) {
  104. var $this = $(this),
  105. index = $header.index($this),
  106. $next = $this.next(),
  107. pos = {
  108. left : index * settings.headerWidth,
  109. right : index * settings.headerWidth + slideWidth,
  110. newPos : 0
  111. },
  112. $group = utils.getGroup.call(this, pos, index);
  113. // set animation direction
  114. if (this.offsetLeft === pos.left) {
  115. pos.newPos = slideWidth;
  116. } else if (this.offsetLeft === pos.right) {
  117. pos.newPos = -slideWidth;
  118. }
  119. // check if animation in progress
  120. if (!$header.is(':animated')) {
  121. // activate onclick callback with slide div as context
  122. if (e.originalEvent) {
  123. if (utils.sentinel === this) return false;
  124. settings.onActivate.call($next);
  125. utils.sentinel = this;
  126. } else {
  127. settings.onActivate.call($next);
  128. utils.sentinel = false;
  129. }
  130. // remove, then add selected class
  131. $header.removeClass('selected').filter($this).addClass('selected');
  132. // get group of tabs & animate
  133. $group
  134. .animate({ left : '+=' + pos.newPos }, settings.slideSpeed, function() { settings.slideCallback.call($next) })
  135. .next()
  136. .animate({ left : '+=' + pos.newPos }, settings.slideSpeed);
  137. }
  138. });
  139. // pause on hover
  140. if (settings.pauseOnHover) {
  141. $accordion.hover(function() {
  142. utils.pause();
  143. }, function() {
  144. utils.play($header.index($header.filter('.selected')));
  145. });
  146. }
  147. // start autoplay, call utils with no args = start from firstSlide
  148. settings.autoPlay && utils.play();
  149. return $accordion;
  150. };
  151. })(jQuery);
  152. //]]>
  153. </script>
  154. <script>
  155. //<![CDATA[
  156. $('#one').liteAccordion({
  157. onActivate : function() {
  158. this.find('figcaption').fadeOut();
  159. },
  160. slideCallback : function() {
  161. this.find('figcaption').fadeIn();
  162. },
  163. autoPlay : true,
  164. pauseOnHover : true,
  165. theme : 'dark',
  166. rounded : true,
  167. enumerateSlides : true
  168. }).find('figcaption:first').show();
  169. //]]>
  170. </script>

Bước 2. Tìm thẻ <div id='content-wrapper'> (thẻ này chứa phần Main và phần Sidebar) rồi đặt trước nó bằng đoạn code bên dưới (tạo phần này để bố trí hiển thị Slider):

<div id='crosscol-wrapper'>
<b:section class='crosscol' id='crosscol' preferred='yes'>
</b:section>
</div>

Lưu Template.

Bước 3. Vào Page Elements. Thêm một tiện ích HTML/Javascript ở phần crosscol vừa tạo ở Bước 2 rồi đặt vào phần nội dung tiện ích bằng đoạn code bên dưới:

<link rel="stylesheet" href="http://www.nicolahibbert.com/demo/liteAccordion/css/liteaccordion.css" type="text/css"/>
<style type="text/css">
.prs {width:745px;}
.prs_pagi_label {background-color:#F0F0F0;float:left;height:120px;margin:0 2px;outline:1px solid #404951;padding:5px;position:relative;width:135px;}
.prs_pagi_label img {background-color:#000;float:left;height:55px;margin:0 8px 0 0;width:55px;}
.prs_pagi_label img.notxt {display:block;floatnone;height:90px;margin:0 auto;width:90px;}
.prs_pagi_label p {color:#888;font-size:11px;line-height:1;}
.prs_pagi_label h6 {bottom:10px;font-family:Artifika,Arial,serif;font-size:11px;font-weight:normal;line-height:1;position:absolute;text-align:center;width:140px;}
.prs_pagi_label h6 a {color:#006699;}
.pr_navi_label {clear:both;color:#BBB;font-family:Tahoma;font-size:18px;margin:0 auto;padding-top:10px;text-align:center;width:243px;}
.pr_navi_label a {color:#BBB !important;display:block;font-family:Tahoma;font-size:18px;padding:5px 10px;}
.pr_navi_label a:hover {color:#FFF !important;}
.pr_navi_label span {padding:5px 10px;}
.pr_navi_label span.deshabilitado {color:#666 !important;}
.pr_navi_label .next {float:right;}
.pr_navi_label .previous {float:left;}
.pr_navi_label .first {text-align:center;}
</style>
<script type='text/javascript'>
//<![CDATA[
// Label Post Accordion Slider for Blogspot by www.vntai.com
var post_per_page = 10;
var list_label=new Array();
list_label[0]="Tên nhãn 1";
list_label[1]="Tên nhãn 2";
list_label[2]="Tên nhãn 3";
list_label[3]="Tên nhãn 4";
var pr_flagfirst=new Array();
pr_flagfirst[0]=0;pr_flagfirst[1]=0;pr_flagfirst[2]=0;pr_flagfirst[3]=0;
var url_prev=new Array();
var url_next=new Array();

function knowwhat(json) {
for (var k = 0; k < json.feed.link.length; k++) {
if (json.feed.link[k].rel == 'self') {
if(json.feed.link[k].href.indexOf("Tên nhãn 1")!=-1) {num_label = 0;}
if(json.feed.link[k].href.indexOf("Tên nhãn 2")!=-1) {num_label = 1;}
if(json.feed.link[k].href.indexOf("Tên nhãn 3")!=-1) {num_label = 2;}
if(json.feed.link[k].href.indexOf("Tên nhãn 4")!=-1) {num_label = 3;}
}
}
return num_label;
}

function showpagelabel(json) {
var entry, posttitle, posturl, postimg, postcontent, postcat;
var strx_out = "";
num_label = knowwhat(json);
url_prev[num_label] = "";
url_next[num_label] = "";
for (var k = 0; k < json.feed.link.length; k++) {
if (json.feed.link[k].rel == 'previous') {
url_prev[num_label] = json.feed.link[k].href;
}
if (json.feed.link[k].rel == 'next') {
url_next[num_label] = json.feed.link[k].href;
}
}
for (var i = 0; i < post_per_page; i++) {
if (i == json.feed.entry.length) { break; }
entry = json.feed.entry[i];
posttitle = getJSONtitle(entry);
posturl = getJSONurl(entry);
postcat = entry.category[0].term;
postcontent = getJSONcontent(entry,100);
postimg = getJSONthumbnail(entry);
strx_out += "<div class='prs_pagi_label'>";
strx_out += "<a href='" + posturl + "' target='_blank'>";
if(postcat=="Tên nhãn 2" || postcat=="Tên nhãn 3") {
strx_out += "<img class='notxt' alt='' src='" + postimg + "' />";
} else {
strx_out += "<img alt='' src='" + postimg + "' />";
}
strx_out += "</a>";
if(postcat=="Tên nhãn 1" || postcat=="Tên nhãn 4") {
strx_out += "<p>" + postcontent + "</p>";
}
strx_out += "<h6><a href='" + posturl + "' target='_blank'>" + posttitle + "</a></h6>";
strx_out += "</div>";
}
document.getElementById("prs" + String(num_label)).innerHTML = strx_out;
strx_out = "";
if(url_prev[num_label]) {
strx_out += "<a href='javascript:navi_pagi_label(" + num_label + ",-1);' class='previous'>Prev</a>";
} else {
strx_out += "<span class='disabled previous'>Prev</span>";
}
if(url_next[num_label]) {
strx_out += "<a href='javascript:navi_pagi_label(" + num_label + ",1);' class='next'>Next</a>";
} else {
strx_out += "<span class='disabled next'>Next</span>";
}
strx_out += "<a href='javascript:navi_pagi_label(" + num_label + ",0);' class='first'>First</a>";
document.getElementById("pr_navi_label" + String(num_label)).innerHTML = strx_out;
}

function navi_pagi_label(num_label, direction) {
var p, parameters;
if(direction==-1) {
p = url_prev[num_label].indexOf("?");
parameters = url_prev[num_label].substring(p);
} else if (direction==1) {
p = url_next[num_label].indexOf("?");
parameters = url_next[num_label].substring(p);
} else {
parameters = "?start-index=1&max-results=" + post_per_page + "&orderby=published&alt=json-in-script"
}
parameters += "&callback=showpagelabel";
if(pr_flagfirst[num_label]==1) {
var that = document.getElementById("LABELTEMPORAL" + String(num_label));
var father = that.parentNode;
father.removeChild(that);
}
document.getElementById("prs" + String(num_label)).innerHTML = "";
document.getElementById("pr_navi_label" + String(num_label)).innerHTML = "";
var archivefeeds = "http://huynh-nhat-ha.blogspot.com/feeds/posts/default/-/" + list_label[num_label] + parameters; // thay huynh-nhat-ha bằng tên blogspot của bạn
var nouvo = document.createElement('script');
nouvo.setAttribute('type', 'text/javascript');
nouvo.setAttribute('src', archivefeeds);
nouvo.setAttribute('id', 'LABELTEMPORAL' + String(num_label));
document.getElementsByTagName('head')[0].appendChild(nouvo);
pr_flagfirst[num_label] = 1;
}

function getJSONtitle(entry,res) {
var t = entry.title.$t;
if(res) {
t = t.substring(0,res);
}
return t;
}
function getJSONurl(entry) {
var url;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
url = entry.link[k].href;
break;
}
}
return url;
}
function getJSONcontent(entry,res) {
var c = "";
if ("content" in entry) {
c = entry.content.$t;
} else if ("summary" in entry) {
c = entry.summary.$t;
}
if(res) {
c = removeHtmlTag(c,res);
}
return c;
}
function getJSONthumbnail(entry) {
var s, a, b, c, d;
var theimg = "";
s = entry.content.$t;
a = s.indexOf("<img");
b = s.indexOf("src=\"",a);
c = s.indexOf("\"",b+5);
d = s.substr(b+5,c-b-5);
if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")) {
theimg = d;
} else {
var cat = entry.category[0].term;
if(cat=="Tên nhãn 1"){theimg = "URL_ảnh đại diện_nhãn1"}
if(cat=="Tên nhãn 2"){theimg = "URL_ảnh đại diện_nhãn2"}
if(cat=="Tên nhãn 3"){theimg = "URL_ảnh đại diện_nhãn3"}
if(cat=="Tên nhãn 4"){theimg = "URL_ảnh đại diện_nhãn4"}
}
return theimg;
}
function removeHtmlTag(strx,chop) {
var r = strx.split("<");
for(var i=0;i<r.length;i++){
if(r[i].indexOf(">")!=-1){
r[i] = r[i].substring(r[i].indexOf(">")+1,r[i].length);
}
}
r = r.join("");
var sss = "", p;
var r2 = r.split(" ");
for(var i=0;i<r2.length;i++){
p = sss + r2[i] + " "
if(p.length>=chop) {break;}
sss = p;
}
sss += "&hellip;"
return sss;
}

onload=function() {navi_pagi_label(0,0);navi_pagi_label(1,0);navi_pagi_label(2,0);navi_pagi_label(3,0);}

//]]>
</script>
<div id="one" class="accordion">
<ol>
<li>
<h2><span>Tên nhãn 1</span></h2>
<div class='slide-inner'>
<div class="prs" id="prs0"></div>
<div class="pr_navi_label" id="pr_navi_label0"></div></div>
</li>
<li>
<h2><span>Tên nhãn 2</span></h2>
<div class='slide-inner'>
<div class="prs" id="prs1"></div>
<div class="pr_navi_label" id="pr_navi_label1"></div></div>
</li>
<li>
<h2><span>Tên nhãn 3</span></h2>
<div class='slide-inner'>
<div class="prs" id="prs2"></div>
<div class="pr_navi_label" id="pr_navi_label2"></div></div>
</li>
<li>
<h2><span>Tên nhãn 4</span></h2>
<div class='slide-inner'>
<div class="prs" id="prs3"></div>
<div class="pr_navi_label" id="pr_navi_label3"></div></div>
</li>
</ol>
<noscript>
<p>Please enable JavaScript to get the full experience.</p>
</noscript>
</div>

Trong đoạn code trên thì đoạn script chính có sự tương đồng với script dùng trong thủ thuật Tiện ích Bài viết liên quan mới nhất cho nhãn trên sidebar (bạn có thể đọc lại bài viết để tìm hiểu thêm). Ở đây mình gán thêm ảnh dại diện riêng cho từng nhãn. Bạn cần tùy biến những phần được đánh dấu đỏ, lần lượt thay thế các tên nhãn áp dụng Slider.

Tuesday, July 19, 2011

Tạo hộp thoại thông báo với hiệu ứng trượt

Một hộp thoại thông báo rất cần thiết cho bất kỳ website hay webblog, có tác dụng đặt một đoạn text với nội dung chào mừng bạn đọc hoặc gửi lời nhắn đến bạn đọc về một vấn đề gì đó. Có nhiều cách để tạo một thông báo như vậy, trong số đó nổi bật nhất có sử dụng thư viện jQuery để tạo hiệu ứng trượt, như bạn có thể thấy tại trang Demo (kéo xuống đáy trang).

Nếu bạn muốn tạo một hộp thoại thông báo như vậy, bạn hãy thực hiện như sau:

Bước 1. Đăng nhập Blogger, vào Design >> Edit HTML. Đặt đoạn code bên dưới vào trước thẻ </head>.
<style>
#slidebox{
width:400px;
height:100px;
padding:10px;
background-color:#fff;
border-top:3px solid #E28409;
position:fixed;
bottom:0px;
right:-430px;
-moz-box-shadow:-2px 0px 5px #aaa;
-webkit-box-shadow:-2px 0px 5px #aaa;
box-shadow:-2px 0px 5px #aaa;
}
</style>

Bước 2. Đặt đoạn code bên dưới vào trước thẻ </body>.
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js ' type='text/javascript'></script>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
$(window).scroll(function(){
var distanceTop = $('#last').offset().top - $(window).height();

if ($(window).scrollTop() > distanceTop)
$('#slidebox').animate({'right':'0px'},300);
else
$('#slidebox').stop(true).animate({'right':'-430px'},100);
});

$('#slidebox .close').bind('click',function(){
$(this).parent().remove();
});
});
//]]>
</script>

Bước 3. Đặt đoạn code bên dưới vào trước thẻ <div id='footer'>.
<p id='last'/>
<div id="slidebox">
<a class="close">[×]</a>
<p>Nội dung thông báo.</p>
</div>

Lưu Template.

Hy vọng bạn sẽ hài lòng với thủ thuật nhỏ này và mong nhận ý kiến góp ý của bạn đọc để có thêm ý tưởng mới.

Wednesday, October 27, 2010

Tạo plugin Twitter cập nhật tweet mới nhất bằng jQuery

Bạn muốn theo dõi những bình luận mới nhất từ trang Twitter? Plugin Twitter sẽ giúp tải những bình luận mới nhất của người dùng Twitter trên toàn cầu với chức năng lọc ngôn ngữ thô tục để tránh những nội dung xấu trên trang web của bạn.Plugin này còn có chức năng hỗ trợ tìm kiếm nhiều người dùng, hiển thị hình Avatar và đặc biệt là không làm chậm trang web khi các tweet đang hạ tải.


Xem Demo.
Sau đây là các bước cài đặt:

1. Đặt các file jQuery và javasctipt bên dưới vào trước thẻ </head>.
<style type="text/css">
/*JUITTER PLUGIN CSS*/
#juitter{width:550px;float:left;}
#juitterSearch{clear:both;padding:7px 0 5px 0;}
#juitterSearch P{font-size:1.2em;color:#2CAF1D}
#juitterSearch INPUT{padding:4px;border:solid 1px #666;width:250px;color:#666}

#juitterContainer{} /*Juitter container*/

#juitterContainer .twittList{margin:0;padding:0;} /* UL that will contain the list of tweets */

/* Bellow the list of tweets "<li>" */

#juitterContainer .twittLI{list-style:none;background:#EEFDEA;margin:0;padding:5px 0 0 0;border-bottom:dashed 1px #CAF8C9;padding:3px;clear:both;height:55px;}
#juitterContainer .twittList SPAN.time{color:#777;font-size:0.9em}
#juitterContainer .twittList A{color:#006600;} /*Links inside the tweets list */

/* Bellow the CSS for the avatar image */

#juitterContainer .juitterAvatar{float:left;border:solid 1px #D3EECA;background:#FFF;margin-right:5px;padding:2px;width:48px;;height:48px;}

#juitterContainer .jRM{float:right;clear:both} /*read it on twitter link*/

#juitterContainer .extLink{} /*CSS for the external links*/

#juitterContainer .hashLink{} /*CSS for the hash links*/

/*end of Juitter CSS*/
</style>

<script language="javascript" src="http://juitter.com/app/js/jquery-1.3.1.min.js" type="text/javascript"></script>

<script language="javascript" src="http://juitter.com/app/js/jquery.juitter.js" type="text/javascript"></script>

<script language="javascript" src="http://juitter.com/app/js/system.js" type="text/javascript"></script>
Các các file trên thì file jquery-1.3.1.min.js là phần lõi jQuery để làm cho plugin hoạt động, file jquery.juitter.js là file lõi và cấu hình plugin, file system.js là file mẫu về cách làm cho plugin hoạt động trên trang web của bạn.

Tiếp đến cần tạo phần chứa nội dung plugin, đặt thành phần div với định dạng id như sau:
<div id="juitter">
<form method="post" id="juitterSearch" action="">
<p>Search Twitter: <input type="text" class="juitterSearch" value="Type a word and press enter" />
</p>
</form>
<div id="juitterContainer"></div>
</div>
Đặt phần code ở trên vào phần thân của trang web (giữa 2 thẻ <body>, </body>).

Tuesday, October 26, 2010

Phân trang cho bài viết sử dụng jQuery

Với sự hỗ trợ của jQuery, việc phân trang ngay trong bài viết giúp cho không gian trong trang web được bố trí hài hòa hơn nhờ thanh Pagination khá giống với phân trang cho cả một website hoặc webblog.


Xem Demo.

Trong thủ thuật này chúng ta cần dùng thẻ <div> để tạo các trang nhỏ và thẻ
để phân bố đều các đoạn văn trong trang nhỏ ấy.

Trước tiết cần đặt phần code CSS và Javascript vào trước thẻ </div>.
<style type='text/css'>
.pagination {
font-size: 80%;
}
.pagination a {
text-decoration: none;
border: solid 1px #AAE;
color: #15B;
}
.pagination a, .pagination span {
display: block;
float: left;
padding: 0.3em 0.5em;
margin-right: 5px;
margin-bottom: 5px;
}
.pagination .current {
background: #26B;
color: #fff;
border: solid 1px #AAE;
}
.pagination .current.prev, .pagination .current.next{
color:#999;
border-color:#999;
background:#fff;
}
#Searchresult {
margin-top:15px;
margin-bottom:15px;
border:solid 1px #eef;
padding:5px;
background:#eef;
width:40%;
}
#Searchresult p { margin-bottom:1.4em;}
</style>
<script type="text/javascript" src="http://d-scribe.de/webtools/jquery-pagination/lib/jquery/jquery.min.js"></script>
<script type="text/javascript" src="http://d-scribe.de/webtools/jquery-pagination/lib/jquery_pagination/jquery.pagination.js"></script>
<script type="text/javascript">

// This is a very simple demo that shows how a range of elements can
// be paginated.

/**
* Callback function that displays the content.
*
* Gets called every time the user clicks on a pagination link.
*
* @param {int}page_index New Page index
* @param {jQuery} jq the container with the pagination links as a jQuery object
*/
function pageselectCallback(page_index, jq){
var new_content = $('#hiddenresult div.result:eq('+page_index+')').clone();
$('#Searchresult').empty().append(new_content);
return false;
}

/**
* Callback function for the AJAX content loader.
*/
function initPagination() {
var num_entries = $('#hiddenresult div.result').length;
// Create pagination element
$("#Pagination").pagination(num_entries, {
num_edge_entries: 2,
num_display_entries: 8,
callback: pageselectCallback,
items_per_page:1
});
}

// Load HTML snippet with AJAX and insert it into the Hiddenresult element
// When the HTML has loaded, call initPagination to paginate the elements
$(document).ready(function(){
initPagination();
});



</script>
* Chú ý: Dòng items_per_page:1, số 1 thể hiện 1 thành phần div trên mỗi trang, bạn có thể đặt 2, 3, 4, ... tùy theo số lượng thành phần div cần hiển thị.

Ở phần nội dung phân trang, thiết lập cấu trúc HTML như sau:
<div id="Pagination"></div>
<br style="clear:both;" />
<div id="Searchresult">
This content will be replaced when pagination inits.
</div>

<!-- Container element for all the Elements that are to be paginated -->
<div id="hiddenresult" style="display:none;">
<div class="result">
<p>Nội dung đoạn văn bản thứ 1 – trang 1.</p>
<p>Nội dung đoạn văn bản thứ 2 – trang 1.</p>
</div>
<div class="result">
<p>Nội dung đoạn văn bản thứ 1 – trang 2</p>
<p>Nội dung đoạn văn bản thứ 2 – trang 2.</p>
</div>
<div class="result">
<p>Nội dung đoạn văn bản thứ 1 – trang 3</p>
<p>Nội dung đoạn văn bản thứ 2 – trang 3.</p>
</div>
</div>
(Còn cập nhật)

Sunday, October 17, 2010

Tạo hiệu ứng accordion sử dụng jQuery

jQuery rất hữu ích trong thiết kế web. Các plugin jQuery ngày càng được ưa chuộng nhờ những tính năng hiệu ứng nổi bật của chúng.


Hiệu ứng accordion là một kiểu hiệu ứng khá đẹp mắt cho phép ẩn hiện nội dung web một cách chuyên nghiệp.

Xem Demo.

Bạn có thể áp dụng hiệu ứng này cho website của mình theo hướng dẫn dưới đây:
Chèn đoạn code dưới đây vào giữa phần <head> … </head> của trang HTML.

<script type="text/javascript" src="/jquery.js"></script>

<script type="text/javascript">
$(document).ready(function(){

$(".accordion h3:first").addClass("active");
$(".accordion p:not(:first)").hide();

$(".accordion h3").click(function(){
$(this).next("p").slideToggle("slow")
.siblings("p:visible").slideUp("slow");
$(this).toggleClass("active");
$(this).siblings("h3").removeClass("active");
});

});
</script>

<style type="text/css">
body {
margin: 10px auto;
width: 570px;
font: 75%/120% Arial, Helvetica, sans-serif;
}
.accordion {
width: 480px;
border-bottom: solid 1px #c4c4c4;
}
.accordion h3 {
background: #e9e7e7 url(/images/arrow-square.gif) no-repeat right -51px;
padding: 7px 15px;
margin: 0;
font: bold 120%/100% Arial, Helvetica, sans-serif;
border: solid 1px #c4c4c4;
border-bottom: none;
cursor: pointer;
}
.accordion h3:hover {
background-color: #e3e2e2;
}
.accordion h3.active {
background-position: right 5px;
}
.accordion p {
background: #f7f7f7;
margin: 0;
padding: 10px 15px 20px;
border-left: solid 1px #c4c4c4;
border-right: solid 1px #c4c4c4;
}
</style>

Bạn nên tải về file jquery.js và file arrow-square.gif rồi thiết lập URL cho đúng. Ngoài ra bạn có thể chỉnh độ rộng (width) phù hợp với yêu cầu website của bạn.

Kế đến bạn thiết kế nội dung hiệu ứng theo như bên dưới và đặt vào phần thân của trang HTML, giữa 2 thẻ <body> … </body>.

<div class="accordion">
<h3>Sample Heading 1</h3>
<p>This is a demo content for Sample Heading 1. You should replace it with your own customized content. You can add as many sample headings with their corresponding content as you like.</p>
<h3> Sample Heading 2</h3>
<p> This is a demo content for Sample Heading 2. You should replace it with your own customized content. You can add as many sample headings with their corresponding content as you like.</p>
<h3> Sample Heading 3</h3>
<p> This is a demo content for Sample Heading 3. You should replace it with your own customized content. You can add as many sample headings with their corresponding content as you like.</p>
<h3> Sample Heading 4</h3>
<p> This is a demo content for Sample Heading 4. You should replace it with your own customized content. You can add as many sample headings with their corresponding content as you like.</p>
<h3> Sample Heading 5</h3>
<p> This is a demo content for Sample Heading 5. You should replace it with your own customized content. You can add as many sample headings with their corresponding content as you like.</p>
</div>

Nằm giữa 2 thẻ <h3>, </h3> là phần tiêu đề. Nằm giữa 2 thẻ <p>, </p> là phần nội dung tương ứng cho tiêu đề. Bạn có thể thêm tiêu đề và nội dung tương ứng tùy thích.

Hiệu ứng này có thể áp dụng cho Blogger. Chỉ cần đặt toàn bộ 2 phần code nêu trên vào một tiện ích HTML là xong.

Hiệu ứng tham khảo theo Webdesignerwall.

Kiểu trình chiếu phiên bản s3Slider sử dụng jQuery

s3Slider jQuery plugin được thực hiện theo ý tưởng script slideshow mượt và được phát triển bởi lập trình viên Boban Karišik tại Serbia.


Bạn có thể xem trình chiếu demo tại trang web này: kruskica.net.

Sử dụng plugin này rất dễ dàng. Trước tiên là kèm vào thư viện jQuery rồi thêm vào javascript s3Slider ở phần <head> của trang web.

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/s3Slider.js" type="text/javascript"></script>

Bạn có thể hạ tải file js/jquery.js js/s3Slider.js.

Kế đến cần thiết lập HTML cho trang trình chiếu.

<div id="s3slider">
<ul id="s3sliderContent">
<li class="s3sliderImage">
<img src="#" />
<span>Your text comes here</span>
</li>
<li class="s3sliderImage">
<img src="#" />
<span>Your text comes here</span>
</li>
<div class="clear s3sliderImage"></div>
</ul>
</div>

Sau nữa là phải tạo các khai báo CSS:

#s3slider {
width: 400px; /* important to be same as image width */
height: 300px; /* important to be same as image height */
position: relative; /* important */
overflow: hidden; /* important */
}

#s3sliderContent {
width: 400px; /* important to be same as image width or wider */
position: absolute; /* important */
top: 0; /* important */
margin-left: 0; /* important */
}

.s3sliderImage {
float: left; /* important */
position: relative; /* important */
display: none; /* important */
}

.s3sliderImage span {
position: absolute; /* important */
left: 0;
font: 10px/15px Arial, Helvetica, sans-serif;
padding: 10px 13px;
width: 374px;
background-color: #000;
filter: alpha(opacity=70); /* here you can set the opacity of box with text */
-moz-opacity: 0.7; /* here you can set the opacity of box with text */
-khtml-opacity: 0.7; /* here you can set the opacity of box with text */
opacity: 0.7; /* here you can set the opacity of box with text */
color: #fff;
display: none; /* important */
top: 0;

/*
if you put
top: 0; -> the box with text will be shown at the top of the image
if you put
bottom: 0; -> the box with text will be shown at the bottom of the image
*/
}

.clear {
clear: both;
}

Nếu hiểu về CSS thì bạn có thể điều chỉnh các thuộc tính và giá trị cho phù hợp với trang web của mình.

Cuối cùng bạn cần phải thiết lập thời gian bao lâu để một bức hình được chiếu lên trang.

$(document).ready(function() {
$('#s3slider').s3Slider({
timeOut: 4000
});
});

Như vậy toàn bộ phần chức năng hiệu ứng slider được đặt như sau:

<head>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/s3Slider.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#s3slider').s3Slider({
timeOut: 4000
});
});
</script>
</head>

Hy vọng rằng bạn sẽ hài lòng với kiểu trình chiếu này.

Cách hoạt động của jQuery

jQuery là gì?

JQuery là một nền tảng hỗ trợ các lập trình viên trong việc phát triển các ứng dụng trên nền tảng web. Khẩu hiệu của JQuery là "Viết ít, làm được nhiều" quả thật rất ấn tượng với những ai đã và đang sử dụng nó cho công việc của mình. JQuery được bắt đầu được phát triển từ tháng 5 / 2005. JQuery được phân phối, phát triển và bảo đảm tuân thủ theo một trong hai giấy phép là GPL & MIT.

jQuery là một thư viện JavaScript nhanh và súc tích giúp đơn giản hóa các công đoạn xây dựng tài liệu HTML đồng thời làm cho quá trình phát triển web trở nên nhanh chóng hơn. jQuery được thiết kế nhằm thay đổi cách mà bạn viết JavaScript.


Lý thuyết cơ bản về jQuery

Đây là phần lý thuyết cơ bản nhằm giúp bạn bắt đầu sử dụng jQuery. Nếu bạn chưa tạo một trang thí nghiệm, hãy tạo một trang HTML mới với nội dung như sau:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// Your code goes here
</script>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
</body>
</html>

Sửa thuộc tính src trong thẻ script để trỏ tới nguồn file jquery.js. Ví dụ, nếu file jquery.js ở cùng thư mục với file HTML, thì bạn có thể dùng:

<script type="text/javascript" src="jquery.js"></script>

Bạn có thể hạ tải bản sao jQuery từ trang Downloading jQuery.

Chạy mã khi tài liệu sẵn sàng


Thứ đầu tiên mà hầu hết các lập trình viên Javascript thực hiện là thêm một số mã vào chương trình của họ, tương tự như sau:

window.onload = function(){ alert("welcome"); }

Bên trong đó là mã mà bạn cần chạy đúng khi trang được tải. Tuy nhiên vấn đề là ở chỗ mã Javascript không chạy cho đến khi tất cả các hình ảnh trong trang được tải xong (kể cả banner quảng cáo). Lý do cho việc sử dụng chức năng window.onload trước tiên là tài liệu HTML vẫn chưa được tải xong khi bạn cố gắng chạy mã của mình.

Để tránh cả 2 vấn đề này, jQuery có một câu lệnh đơn giản kiểm tra tài liệu và đợi cho đến khi nó được thực hiện, gọi là sự kiện sẵn sàng:

$(document).ready(function(){
// Your code here
});

Bên trong sự kiện sẵn sàng nêu trên, thêm chức năng quản lý kích trỏ cho liên kết:

$(document).ready(function(){
$("a").click(function(event){
alert("Thanks for visiting!");
});
});

Lưu file HTML và tải lại trang thử nghiệm trên công cụ trình duyệt. Kích trỏ vào liên kết trên trang và trình duyệt sẽ hiện ra thông báo pop-up trước khi đến trang chính có jQuery.

Đối với các sự kiện kích trỏ và phần lớn các sự kiện khác, bạn có thể ngăn chặn cách chạy mặc định - ở đây, theo liên kết đến jquery.com – bằng cách gọi chức năng event.preventDefault() trong bộ quản lý sự kiện:

$(document).ready(function(){
$("a").click(function(event){
alert("As you can see, the link no longer took you to jquery.com");
event.preventDefault();
});
});

Ví dụ đầy đủ

Sau đây là ví dụ về những gì mà file HTML đầy đủ có thể có được nếu bạn sử dụng script này trong file của bạn. Chú ý rằng nó luên kết đến mạng phân phối nội dung (CDN) của Google để tải file cốt lõi của jQuery. Ngoài ra trong khi script tùy biến được kèm trong thẻ <head>, nhìn chung ưu tiên đặt nó trong một file riêng và đảm bảo rằng file có thuộc tính scr trong thành phần script.

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function(event){
alert("As you can see, the link no longer took you to jquery.com");
event.preventDefault();
});
});

</script>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
</body>
</html>

Thêm và bỏ một lớp CSS

Quan trọng: Các ví dụ jQuery còn lại sẽ cần được đặt trong sự kiện sẵn sàng để mà chúng hoạt động được khi tài liệu sẵn sàng hoạt động. Xem phần Chạy mã khi tài liệu sẵn sàng ở trên.

Một tác vụ phố biến là thêm (hoặc bỏ) một lớp CSS.

Trước tiên, thêm một số thông tin phong cách trong thẻ <head> trong tài liệu, trông như thế này:

<style type="text/css">
a.test { font-weight: bold; }
</style>

Kế đến thêm chức năng gọi thêm lớp (addClass) cho script của bạn:

$("a").addClass("test");

Tất cả các thành phần a trong tài liệu lúc này đều in đậm. Để loại bỏ lớp này, sử dụng chức năng loại bỏ lớp (removeClass):

$("a").removeClass("test");

Chú ý: CSS cho phép nhiều lớp được thêm vào một thành phần.

Các hiệu ứng đặc biệt

Trong jQuery, có 2 hiệu ứng sẵn có, thực sự giúp website của bạn trở nên nổi bật. Để đặt hiệu ứng này vào trang thử nghiệm, thay đổi chức năng kích trỏ mà bạn đã thêm vào lúc đầu:

$("a").click(function(event){
event.preventDefault();
$(this).hide("slow");
});

Lúc này, nếu bạn kích trỏ vào bất kỳ một liên kết thì nó sẽ biến mất từ từ.

Triệu gọi và chức năng
Triệu gọi là một chức năng được xem là đối số đến một chức năng khác và được thực thi sau khi chức năng cha đã hoàn thành. Điều đặc biệt vầ hàm triệu gọi là các chức năng xuất hiện sau khi chức năng cha có thể hoạt động trước khi chức năng triệu gọi hoạt động. Một điều quan trọng nữa cần biết là cách thức thông qua chức năng triệu gọi một cách hợp lý.

Triệu gọi không có đối số

Đối với chức năng triệu gọi không có đối số, bạn nên đặt nó như thế này:

$.get('myhtmlpage.html', myCallBack);

Chú ý rằng tham số thứ 2 ở đây đơn giản chỉ là tên chức năng (nhưng không phải là một chuỗi và không có dấu ngoặc đơn).

Tác giả: John Resig – Dịch giả: Huỳnh Nhật Hà