Last week, I got stuck in the problem about manipulating images gallery on wordpress’ sidebar. I do not want to reload the whole web page every time users click next or previous button. I have tried to use every web technology that I have known such as Ajax and Javascript etc; however, I think it is a little bit difficult if I want to learn to use them in a short time. Finally, I came across the solution by using jquery. As I used it in the first time, I found it was very interesting and useful for web designer.
This is the example that I use to manage my images list.
<script src=”jquery-1.2.6.min.js” type=”text/javascript”></script> <script type=”text/javascript”><!–
// we will add our javascript code here
(function($) {
// Add repeat method to String object
String.prototype.repeat = function(n){
return new Array(n + 1).join(this);
};
// Add leading_zeros method to jQuery
$.leading_zeros = function(n, total_digits){
n = n.toString();
return ‘0′.repeat(total_digits – n.length) + n;
};
})(jQuery);
$(document).ready(function(){
var counter = 2;
$(“div”).hide();
$(“div#1″).show();
for(var i=1; i<=counter; i++)
{
$(“div#”+i).show();
}
$(‘#next-button’).click(function(){
// increment and pad the counter
if(counter >= 5) return;
var pcounter = $.leading_zeros(counter+=2, 1);
for(var a=pcounter-1; a<=pcounter; a++)
{
$(“div#”+a).show();
}
for(var b=1; b<= pcounter-2; b++)
{
$(“div#”+b).hide();
}
});
$(‘#previous-button’).click(function(){
// decrement and pad the counter
if(counter == 2) return;
//var pcounter = $.leading_zeros(counter-=2, 1);
counter -= 2;
//alert(‘counter’+counter);
for(var x=counter+2; x>counter; x )
{
//alert(x);
$(“div#”+x).hide();
}
for(var y=counter-1; y<=counter; y++)
{
$(“div#”+y).show();
}
});
});
// –></script>
<div id=”1″><a><img alt=”" width=”100″ height=”100″ /></a></div>
<div id=”2″><a><img alt=”" width=”100″ height=”100″ /></a></div>
<div id=”3″><a><img alt=”" width=”100″ height=”100″ /></a></div>
<div id=”4″><a><img alt=”" width=”100″ height=”100″ /></a></div>
<div id=”5″><a><img alt=”" width=”100″ height=”100″ /></a></div>
<button id=”previous-button”>Previous</button>
<button id=”next-button”>Next</button>
This code is used to create next and previous function to manage the flaw of images in gallery