Solved

Add "View All" Option to jQuery Pagination script

Posted on 2011-02-27
5
1,143 Views
Last Modified: 2012-05-11
I am using the script here: http://web.enavu.com/js/jquery/jpaginate-jquery-pagination-system-plugin/ to paginate the elements in my page. I would like to add an "View All" link to the pagination for an option to view the page without pagination.

Following is the code I downloaded from the link above:


// jPaginate Plugin for jQuery - Version 0.3
// by Angel Grablev for Enavu Web Development network (enavu.com)
// Dual license under MIT and GPL :) enjoy
/*

To use simply call .paginate() on the element you wish like so:
$("#content").jPaginate(); 

you can specify the following options:
items = number of items to have per page on pagination
next = the text you want to have inside the text button
previous = the text you want in the previous button
active = the class you want the active paginaiton link to have
pagination_class = the class of the pagination element that is being generated for you to style
minimize = minimizing will limit the overall number of elements in the pagination links
nav_items = when minimize is set to true you can specify how many items to show
cookies = if you want to use cookies to remember which page the user is on, true by default
position = specify the position of the pagination, possible options: "before", "after", or "both"
equal = implements an equal height main element by using the highest possible element use true false
offset = unfortunately calculating heights with javascript isn't always 100% accurate, so please use this value to make it perfect :) its defaultly set to 50

*/
(function($){
    $.fn.jPaginate = function(options) {
        var defaults = {
            items: 4,
            next: "Next",
            previous: "Previous",
            active: "active",
            pagination_class: "pagination",
            minimize: false,
            nav_items: 6,
			cookies: true,
			position: "after",
			equal: false,
			offset: 50
        };
        var options = $.extend(defaults, options);

        return this.each(function() {
            // object is the selected pagination element list
            obj = $(this);
            // this is how you call the option passed in by plugin of items
            var show_per_page = options.items;
            //getting the amount of elements inside parent element
            var number_of_items = obj.children().size();
            //calculate the number of pages we are going to have
            var number_of_pages = Math.ceil(number_of_items/show_per_page);
            
			//create the pages of the pagination
            var array_of_elements = [];
            var numP = 0;
            var nexP = show_per_page;
			
			var height = 0;
			var max_height = 0;
            //loop through all pages and assign elements into array
            for (i=1;i<=number_of_pages;i++)
            {    
                array_of_elements[i] = obj.children().slice(numP, nexP);
				
				if (options.equal) {	
					obj.children().slice(numP, nexP).each(function(){
						height += $(this).outerHeight(); 
					});
					if (height > max_height) max_height = height;
					height = 0;
				}
				
                numP += show_per_page;
                nexP += show_per_page;
            }
			if (options.equal) {	
				max_height += options.offset;
				obj.css({"height":max_height});
			}
			
			
            // display first page and set first cookie
			if (options.cookies == true) {
				if (get_cookie("current")) {
					showPage(get_cookie("current"));
					createPagination(get_cookie("current"));
				} else {
					set_cookie( "current", "1");
					showPage(get_cookie("current"));
					createPagination(get_cookie("current"));
				}
			} else {
				showPage(1);
				createPagination(1);
			}
            //show selected page
            function showPage(page) {
                obj.children().hide();
                array_of_elements[page].show();
            }
            
            // create the navigation for the pagination 
            function createPagination(curr) {
                var start, items = "", end, nav = "";
                start = "<ul class='"+options.pagination_class+"'>";
                var previous = "<li><a class='goto_previous' href='#'>"+options.previous+"</a></li>";
                var next = "<li><a class='goto_next' href='#'>"+options.next+"</a></li>";
				var previous_inactive = "<li><a class='inactive'>"+options.previous+"</a></li>";
                var next_inactive = "<li><a class='inactive'>"+options.next+"</a></li>";
                end = "</ul><br clear='all' />"
                var after = number_of_pages - options.after + 1;
                var pagi_range = paginationCalculator(curr);
				for (i=1;i<=number_of_pages;i++)
                {
                    if (options.minimize == true) {
						var half = Math.ceil(number_of_pages/2)
                    	if (i >= pagi_range.start && i <= pagi_range.end) {
							if (i == curr) { items += '<li><a class="'+options.active+'" title="'+i+'">'+i+'</a></li>';} 
                        	else { items += '<li><a href="#" class="goto" title="'+i+'">'+i+'</a></li>';}
						} else if (curr <= half) {
							if (i >= (number_of_pages - 2)) {
								if (i == curr) { items += '<li><a class="'+options.active+'" title="'+i+'">'+i+'</a></li>';} 
                        		else { items += '<li><a href="#" class="goto" title="'+i+'">'+i+'</a></li>';}
							} 
						} else if (curr >= half) {
							if (i <= 2) {
								if (i == curr) { items += '<li><a class="'+options.active+'" title="'+i+'">'+i+'</a></li>';} 
                        		else { items += '<li><a href="#" class="goto" title="'+i+'">'+i+'</a></li>';}
							}
						}
                    } else {
                        if (i == curr) { items += '<li><a class="'+options.active+'" title="'+i+'">'+i+'</a></li>';} 
                        else { items += '<li><a href="#" class="goto" title="'+i+'">'+i+'</a></li>';}
                    }
                }
                if (curr != 1 && curr != number_of_pages) {
                    nav = start + previous + items + next + end;
                } else if (number_of_pages == 1) {
					nav = start + previous_inactive + items + next_inactive + end;
				} else if (curr == number_of_pages){
                    nav = start + previous + items + next_inactive + end;
                } else if (curr == 1) {
                    nav = start + previous_inactive + items + next + end;
                }
				if (options.position == "before") {
					obj.before(nav);
				} else if (options.position == "after") {
					obj.after(nav);
				} else {
					obj.after(nav);
					obj.before(nav)
				}
                
            }
			
			/* code to handle cookies */
			/* code to handle cookies */
			function set_cookie(c_name,value)
			{
				var expiredays = 999;
				var exdate=new Date();exdate.setDate(exdate.getDate()+expiredays);document.cookie=c_name+"="+escape(value)+
((expiredays==null)?"":";expires="+exdate.toUTCString());
			}
			function get_cookie(c_name)
			{
				if(document.cookie.length>0)
				{c_start=document.cookie.indexOf(c_name+"=");if(c_start!=-1)
				{c_start=c_start+c_name.length+1;c_end=document.cookie.indexOf(";",c_start);if(c_end==-1)c_end=document.cookie.length;return unescape(document.cookie.substring(c_start,c_end));}}
				return"";
			}
            
			function paginationCalculator(curr)  {
				var half = Math.floor(options.nav_items/2);
				var upper_limit = number_of_pages - options.nav_items;
				var start = curr > half ? Math.max( Math.min(curr - half, upper_limit), 0 ) : 0;
				var end = curr > half?Math.min(curr + half + (options.nav_items % 2), number_of_pages):Math.min(options.nav_items, number_of_pages);
				return {start:start, end:end};
			}
			
            // handle click on pagination 
            $(".goto").live("click", function(e){
                e.preventDefault();
                showPage($(this).attr("title"));
				set_cookie( "current", $(this).attr("title"));
                $(".pagination").remove();
                createPagination($(this).attr("title"));
            });
            $(".goto_next").live("click", function(e) {
                e.preventDefault();
                var act = "."+options.active;
                var newcurr = parseInt($(".pagination").find(".active").attr("title")) + 1;
                set_cookie( "current", newcurr);
				showPage(newcurr);
                $(".pagination").remove();
                createPagination(newcurr);
            });
            $(".goto_previous").live("click", function(e) {
                e.preventDefault();
                var act = "."+options.active;
                var newcurr = parseInt($(".pagination").find(".active").attr("title")) - 1;
				set_cookie( "current", newcurr);
                showPage(newcurr);
                $(".pagination").remove();
                createPagination(newcurr);
            });
        });
        
       
    };
})(jQuery);

Open in new window

0
Comment
Question by:lyeffeth
  • 2
  • 2
5 Comments
 
LVL 4

Expert Comment

by:DanDauchy
ID: 34993279
Hello,

to get this to display all i didn't modify the plug in at all.  All you need to do is the following: 1.) create a button after all of your paragraphs, 2.) give that button an ID, 3.) setup some jquery so that it displays all paragraphs when clicked.

I updated the example code shown on the plugins main page to show how i did this:
<html>
<head>
    <title></title>

  <style type="text/css">


.pagination {list-style:none; margin:0px; padding:0px;}
.pagination li{float:left; margin:3px;}
.pagination li a{   display:block; padding:3px 5px; color:#fff; background-color:#44b0dd; text-decoration:none;}
.pagination li a.active {border:1px solid #000; color:#000; background-color:#fff;}
.pagination li a.inactive {background-color:#eee; color:#777; border:1px solid #ccc;}
</style>

<script src="http://c.fzilla.com/1286136086-jquery.js"></script>
<script src="http://c.fzilla.com/1291523190-jpaginate.js"></script>
<script>
$(document).ready(function(){
    $("#content").jPaginate();                       
});

$(document).ready(function(){
    $("#view_all").click(function(){
		$("p").show("fast"); 
	});		
});


 $(document).ready(function() {
   $("#view_all").click(function(){
     $("#hidden_form").show("fast");
   });
   $("#close_btn").click(function(){
	 alert("Hello world!");
   });

 });


</script>
</head>

<body>
<div id='content'>
    <p>1Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p>Vestibulum consectetur ipsum sit amet urna euismod imperdiet aliquam urna laoreet.</p>
    <p>Curabitur a ipsum ut elit porttitor egestas non vitae libero.</p>
    <p>Pellentesque ac sem ac sem tincidunt euismod.</p>
    <p>2Duis hendrerit purus vitae nibh tincidunt bibendum.</p>
    <p>Nullam in nisi sit amet velit placerat laoreet.</p>
    <p>Nulla sed purus et tellus convallis scelerisque.</p>
    <p>Nam at justo ut ante consectetur faucibus.</p>
    <p>Proin dapibus nisi a quam interdum lobortis.</p>
    <p>Nunc ornare nisi sed mi vehicula eu luctus mauris interdum.</p>
    <p>Mauris auctor suscipit tellus, at sodales nisi blandit sed.</p>
</div>
<br><br>
<div id='view_all'>view all</div>



</body>
</html>

Open in new window

0
 
LVL 4

Accepted Solution

by:
DanDauchy earned 250 total points
ID: 34993314
and to simplify things, just create a button w/ an id of "view_all" and then do the following:

$(document).ready(function(){
    $("#view_all").click(function(){
		$("p").show("fast"); 
	});		
});

Open in new window

0
 
LVL 12

Expert Comment

by:Cyber-spy
ID: 34993390
I started to look at adding some extra buttons, to set the 'items' option to the number of children in the paginated element (#content in the example) and then resetting back to the default value.

However, looking at the page the link points at, I think this plugin is still under development. There is certainly an active conversation with the developer in the comments section at the bottom of the page, the last being just four days ago, reporting problems with it.

Consequently, I think your best course of action would be to contact the developer directly and ask him to add this as a feature to the plugin.


0
 

Author Comment

by:lyeffeth
ID: 34993738
Thanks, Dan. To keep it altogether, I incorporated your suggestion into the plugin, so that the script builds the 'View All' link along with the rest of the pagination. I also added functionality to add and remove classes as necessary when "view all" is clicked so that the first and last buttons are inactivated and the "view all" becomes active. There is probably a simpler way to handle the classes but this works. In case anyone else needs this, this is the final code. A search for "viewall" will show where I made changes.


// jPaginate Plugin for jQuery - Version 0.3
// by Angel Grablev for Enavu Web Development network (enavu.com)
// Dual license under MIT and GPL :) enjoy
/*

To use simply call .paginate() on the element you wish like so:
$("#content").jPaginate(); 

you can specify the following options:
items = number of items to have per page on pagination
next = the text you want to have inside the text button
previous = the text you want in the previous button
active = the class you want the active paginaiton link to have
pagination_class = the class of the pagination element that is being generated for you to style
minimize = minimizing will limit the overall number of elements in the pagination links
nav_items = when minimize is set to true you can specify how many items to show
cookies = if you want to use cookies to remember which page the user is on, true by default
position = specify the position of the pagination, possible options: "before", "after", or "both"
equal = implements an equal height main element by using the highest possible element use true false
offset = unfortunately calculating heights with javascript isn't always 100% accurate, so please use this value to make it perfect :) its defaultly set to 50

*/
(function($){
    $.fn.jPaginate = function(options) {
        var defaults = {
            items: 4,
            next: "Next",
            previous: "Previous",
            active: "active",
            pagination_class: "pagination",
            minimize: false,
            nav_items: 6,
			cookies: true,
			position: "after",
			equal: false,
			offset: 50
        };
        var options = $.extend(defaults, options);

        return this.each(function() {
            // object is the selected pagination element list
            obj = $(this);
            // this is how you call the option passed in by plugin of items
            var show_per_page = options.items;
            //getting the amount of elements inside parent element
            var number_of_items = obj.children().size();
            //calculate the number of pages we are going to have
            var number_of_pages = Math.ceil(number_of_items/show_per_page);
            
			//create the pages of the pagination
            var array_of_elements = [];
            var numP = 0;
            var nexP = show_per_page;
			
			var height = 0;
			var max_height = 0;
            //loop through all pages and assign elements into array
            for (i=1;i<=number_of_pages;i++)
            {    
                array_of_elements[i] = obj.children().slice(numP, nexP);
				
				if (options.equal) {	
					obj.children().slice(numP, nexP).each(function(){
						height += $(this).outerHeight(); 
					});
					if (height > max_height) max_height = height;
					height = 0;
				}
				
                numP += show_per_page;
                nexP += show_per_page;
            }
			if (options.equal) {	
				max_height += options.offset;
				obj.css({"height":max_height});
			}
			
			
            // display first page and set first cookie
			if (options.cookies == true) {
				if (get_cookie("current")) {
					showPage(get_cookie("current"));
					createPagination(get_cookie("current"));
				} else {
					set_cookie( "current", "1");
					showPage(get_cookie("current"));
					createPagination(get_cookie("current"));
				}
			} else {
				showPage(1);
				createPagination(1);
			}
            //show selected page
            function showPage(page) {
                obj.children().hide();
                array_of_elements[page].show();
            }
            
            // create the navigation for the pagination 
            function createPagination(curr) {
                var start, items = "", end, nav = "";
                start = "<ul class='"+options.pagination_class+"'>";
                var previous = "<li><a class='goto_previous' href='#'>"+options.previous+"</a></li>";
                var next = "<li><a class='goto_next' href='#'>"+options.next+"</a></li>";
				var previous_inactive = "<li><a class='inactive'>"+options.previous+"</a></li>";
                var next_inactive = "<li><a class='inactive'>"+options.next+"</a></li>";
                end = "<li class='active' id='viewall'><a href='#'>View All</a></li></ul>"
                var after = number_of_pages - options.after + 1;
                var pagi_range = paginationCalculator(curr);
				for (i=1;i<=number_of_pages;i++)
                {
                    if (options.minimize == true) {
						var half = Math.ceil(number_of_pages/2)
                    	if (i >= pagi_range.start && i <= pagi_range.end) {
							if (i == curr) { items += '<li><a class="'+options.active+'" title="'+i+'">'+i+'</a></li>';} 
                        	else { items += '<li><a href="#" class="goto" title="'+i+'">'+i+'</a></li>';}
						} else if (curr <= half) {
							if (i >= (number_of_pages - 2)) {
								if (i == curr) { items += '<li><a class="'+options.active+'" title="'+i+'">'+i+'</a></li>';} 
                        		else { items += '<li><a href="#" class="goto" title="'+i+'">'+i+'</a></li>';}
							} 
						} else if (curr >= half) {
							if (i <= 2) {
								if (i == curr) { items += '<li><a class="'+options.active+'" title="'+i+'">'+i+'</a></li>';} 
                        		else { items += '<li><a href="#" class="goto" title="'+i+'">'+i+'</a></li>';}
							}
						}
                    } else {
                        if (i == curr) { items += '<li><a class="'+options.active+'" title="'+i+'">'+i+'</a></li>';} 
                        else { items += '<li><a href="#" class="goto" title="'+i+'">'+i+'</a></li>';}
                    }
                }
                if (curr != 1 && curr != number_of_pages) {
                    nav = start + previous + items + next + end;
                } else if (number_of_pages == 1) {
					nav = start + previous_inactive + items + next_inactive + end;
				} else if (curr == number_of_pages){
                    nav = start + previous + items + next_inactive + end;
                } else if (curr == 1) {
                    nav = start + previous_inactive + items + next + end;
                }
				if (options.position == "before") {
					obj.before(nav);
				} else if (options.position == "after") {
					obj.after(nav);
				} else {
					obj.after(nav);
					obj.before(nav)
				}
                
            }
			
			/* code to handle cookies */
			/* code to handle cookies */
			function set_cookie(c_name,value)
			{
				var expiredays = 999;
				var exdate=new Date();exdate.setDate(exdate.getDate()+expiredays);document.cookie=c_name+"="+escape(value)+
((expiredays==null)?"":";expires="+exdate.toUTCString());
			}
			function get_cookie(c_name)
			{
				if(document.cookie.length>0)
				{c_start=document.cookie.indexOf(c_name+"=");if(c_start!=-1)
				{c_start=c_start+c_name.length+1;c_end=document.cookie.indexOf(";",c_start);if(c_end==-1)c_end=document.cookie.length;return unescape(document.cookie.substring(c_start,c_end));}}
				return"";
			}
            
			function paginationCalculator(curr)  {
				var half = Math.floor(options.nav_items/2);
				var upper_limit = number_of_pages - options.nav_items;
				var start = curr > half ? Math.max( Math.min(curr - half, upper_limit), 0 ) : 0;
				var end = curr > half?Math.min(curr + half + (options.nav_items % 2), number_of_pages):Math.min(options.nav_items, number_of_pages);
				return {start:start, end:end};
			}
			
            // handle click on pagination 
            $(".goto").live("click", function(e){
                e.preventDefault();
                showPage($(this).attr("title"));
				set_cookie( "current", $(this).attr("title"));
                $(".pagination").remove();
                createPagination($(this).attr("title"));
                $('#viewall').removeClass('inactive');
            });
            $(".goto_next").live("click", function(e) {
                e.preventDefault();
                var act = "."+options.active;
                var newcurr = parseInt($(".pagination").find(".active").attr("title")) + 1;
                set_cookie( "current", newcurr);
				showPage(newcurr);
                $(".pagination").remove();
                createPagination(newcurr);
                $('#viewall').removeClass('inactive');
            });
            $(".goto_previous").live("click", function(e) {
                e.preventDefault();
                var act = "."+options.active;
                var newcurr = parseInt($(".pagination").find(".active").attr("title")) - 1;
				set_cookie( "current", newcurr);
                showPage(newcurr);
                $(".pagination").remove();
                createPagination(newcurr);
                $('#viewall').removeClass('inactive');
            });
            $("#viewall a").live("click", function(e) {
				e.preventDefault();
				$("#grid li").show();
				$("li").find('.active').removeClass('active').addClass('goto').attr('href','#');
				$("li").find('.goto_previous').removeClass('goto_previous').addClass('inactive');
				$("li").find('.goto_next').removeClass('goto_next').addClass('inactive');
               $(this).addClass('active');
			});

       });
        
       
    };
})(jQuery);

Open in new window

0
 

Author Closing Comment

by:lyeffeth
ID: 34993742
This solved the problem but it wasn't incorporated to work with the plugin.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now