Pagination using Javascript - javascript

Trying to implement pagination for jQuery accordion using javascript. I found this link for a javascript class to implement accordion pagination. However, it's not behaving as expected. I played with it for a while but with no result. Can someone please help me figure where the fault is? I'd appreciated so much. Here I created JSfiddle for it.
Javascript code
var paginatorHandle = null;
jQuery(document).ready(function () {
jQuery("#dalist").accordion({
autoHeight: false
});
paginatorHandle = jQuery("#dalist").paginateAccordion({
"currentPage": 0,
"itemsPerPage": 3,
"paginatorControl": jQuery("#accordionPaginator")
});
// initial paginate call
paginatorHandle.paginate();
jQuery("#accordionPaginator .nextPage").click(function () {
paginatorHandle.nextPage();
});
jQuery("#accordionPaginator .previousPage").click(function () {
paginatorHandle.previousPage();
});
jQuery("#accordionPaginator .goToPage").change(function () {
var pageIndex = parseInt($(this).val(), radix);
paginatorHandle.goToPage(pageIndex);
});
});
//this is the main class
function AccordionPaginator(element, currentPage, itemsPerPage, paginatorControl) {
this.element = element;
this.currentPage = currentPage;
this.itemsPerPage = itemsPerPage;
this.paginatorControl = paginatorControl;
// does the actual pagination (shows/hides items)
this.paginate = function () {
var index = this.currentPage * this.itemsPerPage;
element.accordion("activate", index);
element.children().hide();
if (index < 0) {
this.element.children("div:first").show();
this.element.children("h3:first").show();
} else {
this.element.children("div:eq(" + index + ")")
.show();
this.element.children("h3:eq(" + index + "),h3:gt(" + index + ")")
.filter(":lt(" + this.itemsPerPage + ")")
.show();
}
this.refreshControl();
};
// increments the currentPage var (if possible) and calls paginate
this.nextPage = function () {
if (this.currentPage + 1 >= this.getMaxPageIndex()) {
return;
}
this.currentPage++;
this.paginate();
};
// decrements the currentPage var (if possible) and calls paginate
this.previousPage = function () {
if (this.currentPage - 1 < 0) {
return;
}
this.currentPage--;
this.paginate();
};
// sets currentPage var (if possible) and calls paginate
this.goToPage = function (pageIndex) {
if ((pageIndex < 0) || (pageIndex >= this.getMaxPageIndex())) {
return;
}
this.currentPage = pageIndex;
this.paginate();
};
// returns the maximum of pages possible with the current number of items
this.getMaxPageIndex = function () {
var items = this.element.children("h3");
var fullPages = items.length / this.itemsPerPage;
var restPage = items.length % (this.itemsPerPage > 0 ? 1 : 0);
return fullPages + restPage;
};
// fills up the paginator control
this.refreshControl = function () {
if (this.paginatorControl === null) {
return;
}
var pageList = this.paginatorControl.children(".goToPage");
pageList.empty();
for (var i = 0; i < this.getMaxPageIndex(); i++) {
pageList.append("<option value=\"" + i + "\">" + (i + 1) + "</option>");
}
pageList.val(this.currentPage);
};
}
jQuery.fn.extend({
paginateAccordion: function (options) {
var currentPage = options.currentPage ?parseInt(options.currentPage, radix) : 0;
var itemsPerPage = options.itemsPerPage ? parseInt(options.itemsPerPage, radix) : 5;
var paginatorControl = options.paginatorControl;
return new AccordionPaginator(this, currentPage, itemsPerPage, paginatorControl);
}
});

I made couple of changes to your code in JSFiddle and the pagination worked.
Here is the link to the modified jsfiddle.
http://jsfiddle.net/moLwmyyr/
I removed
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
And used JSFiddle Frameworks and Extensions to include jQuery
I changed the jQuery UI include to
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
I moved the
jQuery.fn.extend({
paginateAccordion: function (options) {
var currentPage = options.currentPage ?parseInt(options.currentPage, 10) : 0;
var itemsPerPage = options.itemsPerPage ? parseInt(options.itemsPerPage, 10) : 5;
var paginatorControl = options.paginatorControl;
return new AccordionPaginator(this, currentPage, itemsPerPage, paginatorControl);
}
});
Above your document ready method.
And changed the following line.
element.accordion("activate", index);
To
element.accordion("option", "activate", index);
The pagination works.
I observed some glitch when you go to the next page and click on the section 5, it is not collapsing section 4.

Related

Hide page numbers in jquery paginate

I am using a jquery function to paginate items in my website page.
This is the function:
(function($) {
var pagify = {
items: {},
container: null,
totalPages: 1,
perPage: 3,
currentPage: 0,
createNavigation: function() {
this.totalPages = Math.ceil(this.items.length / this.perPage);
$('.pagination', this.container.parent()).remove();
var pagination = $('<div class="pagination"></div>').append('<a class="nav prev disabled" data-next="false"><</a>');
for (var i = 0; i < this.totalPages; i++) {
var pageElClass = "page";
if (!i)
pageElClass = "page current";
var pageEl = '<a class="' + pageElClass + '" data-page="' + (
i + 1) + '">' + (
i + 1) + "</a>";
pagination.append(pageEl);
}
pagination.append('<a class="nav next" data-next="true">></a>');
this.container.after(pagination);
var that = this;
$("body").off("click", ".nav");
this.navigator = $("body").on("click", ".nav", function() {
var el = $(this);
that.navigate(el.data("next"));
});
$("body").off("click", ".page");
this.pageNavigator = $("body").on("click", ".page", function() {
var el = $(this);
that.goToPage(el.data("page"));
});
},
navigate: function(next) {
// default perPage to 5
if (isNaN(next) || next === undefined) {
next = true;
}
$(".pagination .nav").removeClass("disabled");
if (next) {
this.currentPage++;
if (this.currentPage > (this.totalPages - 1))
this.currentPage = (this.totalPages - 1);
if (this.currentPage == (this.totalPages - 1))
$(".pagination .nav.next").addClass("disabled");
}
else {
this.currentPage--;
if (this.currentPage < 0)
this.currentPage = 0;
if (this.currentPage == 0)
$(".pagination .nav.prev").addClass("disabled");
}
this.showItems();
},
updateNavigation: function() {
var pages = $(".pagination .page");
pages.removeClass("current");
$('.pagination .page[data-page="' + (
this.currentPage + 1) + '"]').addClass("current");
},
goToPage: function(page) {
this.currentPage = page - 1;
$(".pagination .nav").removeClass("disabled");
if (this.currentPage == (this.totalPages - 1))
$(".pagination .nav.next").addClass("disabled");
if (this.currentPage == 0)
$(".pagination .nav.prev").addClass("disabled");
this.showItems();
},
showItems: function() {
this.items.hide();
var base = this.perPage * this.currentPage;
this.items.slice(base, base + this.perPage).show();
this.updateNavigation();
},
init: function(container, items, perPage) {
this.container = container;
this.currentPage = 0;
this.totalPages = 1;
this.perPage = perPage;
this.items = items;
this.createNavigation();
this.showItems();
}
};
// stuff it all into a jQuery method!
$.fn.pagify = function(perPage, itemSelector) {
var el = $(this);
var items = $(itemSelector, el);
// default perPage to 5
if (isNaN(perPage) || perPage === undefined) {
perPage = 3;
}
// don't fire if fewer items than perPage
if (items.length <= perPage) {
return true;
}
pagify.init(el, items, perPage);
};
})(jQuery);
$(".ff-stream-wrapper").pagify(8, ".ff-item");
now I have many pages (33 pages). In page numbers I want to only show first 5 page numbers and the last one, other pages shown if are close to current page, for example if I go to page 2, number 6 apears.
current view of page numbers:
What I want to do:
Consider referencing the implementation of the pageRange option: https://pagination.js.org/docs/index.html#pageRange
in https://github.com/superRaytin/paginationjs/blob/master/src/pagination.js

TypeError: children.size is not a function with jQuery

I found a small plugin that will allow me to add simple pages to my html table.
The first thing I did was to create a new js file and added the following code to it.
(function ($) {
$.fn.SimplePages = function (opts) {
var self = this;
var defaults = {
perPage: 10,
showPrevNext: false,
hidePageNumbers: false
};
var settings = $.extend(defaults, opts);
var listElement = self;
var perPage = settings.perPage;
var children = listElement.children();
var pager = $('.pager');
if (typeof settings.childSelector != "undefined") {
children = listElement.find(settings.childSelector);
}
if (typeof settings.pagerSelector != "undefined") {
pager = $(settings.pagerSelector);
}
var numItems = children.size();
var numPages = Math.ceil(numItems / perPage);
pager.data("curr", 0);
if (settings.showPrevNext) {
$('<li>«</li>').appendTo(pager);
}
var curr = 0;
while (numPages > curr && (settings.hidePageNumbers == false)) {
$('<li>' + (curr + 1) + '</li>').appendTo(pager);
curr++;
}
if (settings.showPrevNext) {
$('<li>»</li>').appendTo(pager);
}
pager.find('.page_link:first').addClass('active');
pager.find('.prev_link').hide();
if (numPages <= 1) {
pager.find('.next_link').hide();
}
pager.children().eq(1).addClass("active");
children.hide();
children.slice(0, perPage).show();
pager.find('li .page_link').click(function () {
var clickedPage = $(this).html().valueOf() - 1;
goTo(clickedPage, perPage);
return false;
});
pager.find('li .prev_link').click(function () {
previous();
return false;
});
pager.find('li .next_link').click(function () {
next();
return false;
});
function previous() {
var goToPage = parseInt(pager.data("curr")) - 1;
goTo(goToPage);
}
function next() {
goToPage = parseInt(pager.data("curr")) + 1;
goTo(goToPage);
}
function goTo(page) {
var startAt = page * perPage,
endOn = startAt + perPage;
children.css('display', 'none').slice(startAt, endOn).show();
if (page >= 1) {
pager.find('.prev_link').show();
}
else {
pager.find('.prev_link').hide();
}
if (page < (numPages - 1)) {
pager.find('.next_link').show();
}
else {
pager.find('.next_link').hide();
}
pager.data("curr", page);
pager.children().removeClass("active");
pager.children().eq(page + 1).addClass("active");
}
};
}( jQuery ));
Then I am trying to use this plugin like so
$(function () {
$('#UserToClientRelationTable').SimplePages(
{
pagerSelector: '#UserToClientRelationTablePager',
showPrevNext: true,
hidePageNumbers: false,
perPage: 5
});
});
Unfortunately this code keeps giving me the following error in the console
TypeError: children.size is not a function
And, yes I loaded jQuery before loading this file. In face, if I remove this code and the pagination the rest of my code give me no errors.
How can I fix this problem?
size() was deprecated a long time ago and completely removed from jQuery 3
The norm is to use length property instead
See size() docs
if you are using a version less than 3, then problem is likely elsewhere and we need more info
use length returns the number of matched elements:
https://api.jquery.com/length/
var numItems = children.length;

Starting Javascript intervals nonsynchronously and stop each after three runs

I have a function for letting blink a OpenLayer marker three times. The simplified version which only shows console messages:
function blink_three_times(layername){
var x = 0;
setTimeout(function() {
blink_in = setInterval(function() {
x = x+1;
if ( x === 3) {clearInterval(blink_in)};
console.log(layername + ' is visible');
}, 500);
}, 250);
blink_out = setInterval(function() {
if (x === 2) {clearInterval(blink_out)};
console.log(layername + ' is invisible');
}, 500);
};
It works fine, but if it is started multiple times before one has finished, the counter (x) exceeds 3 and the interval does not stop. How can I avoid that?
That is because you have funcions blink_in & blink_out in global scope. When you are calling it second time it overwrites the definitions of functions.
Define them using var to make them local.
var blink_in = setInterval(function() {..})
and
var blink_out = setInterval(function() {..})
DEMO
Your variables blink_in and blink_out are global ones so if you call the function multiple times they will override it and therefore cannot stop the interval properly.
Use them in your function scope by definining them with "var" in order to avoid the problem (see http://jsfiddle.net/cb0h8tst/)
function blink_three_times(layername){
var x = 0;
var blink_in, blink_out;
setTimeout(function() {
blink_in = setInterval(function() {
x = x+1;
if ( x === 3) {clearInterval(blink_in)};
console.log(layername + ' is visible');
}, 500);
}, 250);
blink_out = setInterval(function() {
if (x === 2) {clearInterval(blink_out)};
console.log(layername + ' is invisible');
}, 500);
};
Based on your last update question,
you could also make a more dynamic to keep track of the layers that are actually being blinked, a possible example
function Blinker(opt) {
var ts = {};
this.elementId = opt ? opt.elementId : undefined;
this.runs = (opt ? opt.runs : 3) || 3;
this.completed = (opt ? opt.completed : function() { }) || function() { };
this.start = function(arg) {
var timestamp = arg || this.elementId, that = this;
if (typeof ts[timestamp] !== 'undefined') {
console.log('Cannot run multiple times on same layer');
return;
}
ts[timestamp] = {
timestamp: timestamp,
count: 0,
element: document.getElementById(arg || this.elementId),
controller: this
};
setTimeout(function() {
ts[timestamp].showInterval = setInterval(that.setVisibility.bind(ts[timestamp], true), 500);
}, 250);
ts[timestamp].hideInterval = setInterval(this.setVisibility.bind(ts[timestamp], false), 500);
};
this.setVisibility = function(visible) {
this.element.style.visibility = visible ? 'visible' : 'hidden';
this.element.style.display = visible ? 'inherit' : 'none';
if (visible) {
this.count++;
}
if (!visible && this.count === 2)
{
clearInterval(this.hideInterval);
}
if (visible && this.count === 3)
{
clearInterval(this.showInterval);
this.controller.completed.apply(this.controller, [this.element.id]);
delete ts[this.timestamp];
}
};
}
var blinker = new Blinker({
elementId: 'blinker',
runs: 3,
completed: function(elementId) {
var log = document.getElementById('log');
log.innerHTML += '<p><strong>' + elementId + '</strong> has finished blinking</p>';
}
});
you could find the fiddle here: http://jsfiddle.net/q70w0kpx/

How to show two numbers in jQuery?

Can you please tell me how to show number all time.
Given : LastNumber
when **previous** button click .
Result: 10 11
Result: 9 10
Result: 8 9
if user click next button
Result: 9 10
Result: 10 11
http://jsfiddle.net/LyXLD/3/
function printdown(count) {
$("#pre").html('')
$("#pre").html($("#curr").html());
$("#curr").html('')
$("#curr").html(count);
// $("#pre").html(count);
}
$("#next").click(function () {
if (++file_show_counter <= lastestCountValue) {
printdown(file_show_counter);
} else {
file_show_counter--;
}
});
Use this:
$(document).ready(function () {
$('#previos').click(function () {
var prevVal = parseInt($('#pre').html());
var curVal = parseInt($('#curr').html());
$('#pre').text(prevVal - 1);
$('#curr').text(curVal - 1);
});
$('#next').click(function () {
var prevVal = parseInt($('#pre').html());
var curVal = parseInt($('#curr').html());
if (curVal < 11) {
$('#pre').text(prevVal + 1);
$('#curr').text(curVal + 1);
}
});
});
Demo:http://jsfiddle.net/LyXLD/5/
i have 11 pages.and i have to show 2 pages at one time.i just know how
many pages i have mean (11). when i go up it show 9 and 10 page.then 8
and 9 page
Update
Well now that OP has actually stated this requirement, here's an updated solution.
Prev button stops working when it gets down to 1, and the next button stops working when it reaches the page count.
DEMO
var pageCount = 11;
$("#previous").on("click", function () {
$pre = $("#pre");
$curr = $("#curr");
$count = +$pre.text();
if ($count > 1) {
$pre.text($count - 1);
$curr.text($count);
}
});
$("#next").on("click", function () {
$pre = $("#pre");
$curr = $("#curr");
$count = +$curr.text();
if ($count < pageCount) {
$pre.text($count);
$curr.text($count + 1);
}
});
I just write new code please check it on http://jsfiddle.net/shantanubhaware/LyXLD/10/
working code
var lastval = $('#curr').text();
var preval = $('#pre').text();
var i = 0;
$('#previos').click(function () {
var lastval = $('#curr').text();
var preval = $('#pre').text();
previous();
});
$('#next').click(function () {
var lastval = $('#curr').text();
var preval = $('#pre').text();
next();
});
function previous() {
if (preval >= 1) {
--lastval;
--preval;
$('#curr').text(lastval);
$('#pre').text(preval);
}
}
Please take a look. Is that what you are looking for?
JSFIDDLE DEMO
var lastestCountValue = 11,
file_show_counter = lastestCountValue - 1;
$(document).ready(function () {
$("#previos").click(function () {
if (file_show_counter > 1) {
print(--file_show_counter, file_show_counter + 1);
}
});
$("#next").click(function () {
if (file_show_counter < lastestCountValue - 1) {
print(++file_show_counter, file_show_counter + 1);
}
});
});
function print(pre, cur) {
$("#pre").html(pre);
$("#curr").html(cur);
}

Javascript not working with jquery library 1.9.1

I'm struggling trying to get this to work an be compatible with one of the later versions of the jquery library. Before I was using the version 1.3.2, but would like to update that version to 1.9.1 for the time being. I ran some tests and found out there is a few sections of javascript that also need to be updated but can't seem to figure it out - so I'm handing this over to you all - could you please help me figure this out?
EDIT:
I have two out of three main areas that are giving me troubles...I'll provide them below with where I think the issue may be... one of the parts have been solved but am still struggling with these two parts below.
JAVASCRIPT - Part 1
$(document).ready(function () {
$('.rate_widget').each(function (i) {
var widget = this;
var out_data = {
widget_id: $(widget).attr('id'),
fetch: 1
};
$.post(
'--Ratings/ratings.php',
out_data,
function (INFO) {
$(widget).data('fsr', INFO);
set_votes(widget);
},
'json');
});
$('.ratings_stars').hover(
function () {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
function () {
$(this).prevAll().andSelf().removeClass('ratings_over');
set_votes($(this).parent());
});
$('.ratings_stars').bind('click', function () {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on: $(star).attr('class'),
widget_id: $(star).parent().attr('id')
};
$.post(
'--Ratings/ratings.php',
clicked_data,
function (INFO) {
widget.data('fsr', INFO);
set_votes(widget);
},
'json');
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes); /* ===== <-- Here ===== */
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text(votes + ' votes recorded (' + exact + ' rating)');
}
JAVASCRIPT - Part 2
$(function () {
$('input.field').focus(function () {
if (this.title == this.value) {
this.value = '';
}
})
.blur(function () {
if (this.value == '') { /* ===== <-- Here ===== */
this.value = this.title;
}
});
var currentPage = 1;
$('#slider_profile .buttons_profile span').live('click', function () {
var timeout = setTimeout(function () {
$("img").trigger("slidermove") /* ===== <-- Here ===== */
}, 100);
var fragments_count = $(this).parents('#slider_profile:eq(0)').find('.fragment_profile').length;
var fragment_width = $(this).parents('#slider_profile:eq(0)').find('.fragment_profile').width();
var perPage = 1;
var numPages = Math.ceil(fragments_count / perPage);
var stepMove = fragment_width * perPage;
var container = $(this).parents('#slider_profile:eq(0)').find('.con_profile');
var firstPosition = 0;
var lastPosition = -((numPages - 1) * stepMove);
if ($(this).hasClass('next')) {
currentPage++;
if (currentPage > numPages) {
currentPage = 1;
container.animate({
'left': firstPosition
});
return;
}; /* ===== <-- Here ===== */
container.animate({
'left': -((currentPage - 1) * stepMove)
});
}; /* ===== <-- Here ===== */
if ($(this).hasClass('prev')) {
currentPage--;
if (currentPage < 1) {
currentPage = numPages;
container.animate({
'left': lastPosition
});
return;
}; /* ===== <-- Here ===== */
container.animate({
'left': -((currentPage - 1) * stepMove)
});
}; /* ===== <-- Here ===== */
});
});
I could also be completely wrong in the locations where I marked ( <-- Here ) next to where I believe is the problems that need to be fixed. So with all that in mind, could someone help me figure out how to make these parts work with one of the latest versions of jquery 1.9.1 ?
FIRST, try this
JAVASCRIPT - Part 1
$(document).ready(function () {
$('a.head').click(function () {
var a = $(this);
var section = a.attr('href');
section.removeClass('section');
$('.section').hide();
section.addClass('section');
if (section.is(':visible')) {
section.slideToggle(); /* ===== <-- 400 is the default duration ===== */
} else {
section.slideToggle();
}
});
});
JAVASCRIPT - PART 2
$(document).ready(function () {
$('.rate_widget').each(function () {
var widget = $(this);
var out_data = {
widget_id: widget.attr('id'),
fetch: 1
};
$.post(
'--Ratings/ratings.php',
out_data,
function (INFO) {
widget.data('fsr', INFO);
set_votes(widget);
},
'json');
});
$('.ratings_stars').hover(function () {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
}, function () {
$(this).prevAll().andSelf().removeClass('ratings_over');
set_votes($(this).parent());
});
$('.ratings_stars').bind('click', function () {
var star = $(this);
var widget = star.parent();
var clicked_data = {
clicked_on: star.attr('class'),
widget_id: star.parent().attr('id')
};
$.post(
'--Ratings/ratings.php',
clicked_data,
function (INFO) {
widget.data('fsr', INFO);
set_votes(widget);
},
'json');
});
});
function set_votes(widget) {
var avg = widget.data('fsr').whole_avg;
var votes = widget.data('fsr').number_votes;
var exact = widget.data('fsr').dec_avg;
console.log('and now in set_votes, it thinks the fsr is ' + widget.data('fsr').number_votes);
widget.find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
widget.find('.star_' + avg).nextAll().removeClass('ratings_vote');
widget.find('.total_votes').text(votes + ' votes recorded (' + exact + ' rating)');
}
JAVASCRIPT - PART 3
$(function () {
$('input.field').focus(function () {
if (this.title == this.value) {
this.value = '';
}
}).blur(function () {
if (this.value === '') { /* ===== <-- Here ===== */
this.value = this.title;
}
});
var currentPage = 1;
$(document).on('click', $('#slider_profile .buttons_profile span'), function () {
var timeout = setTimeout(function () {
$("img").trigger("slidermove"); /* ===== <-- Here ===== */
}, 100);
var fragments_count = $(this).parents('#slider_profile:eq(0)').find('.fragment_profile').length;
var fragment_width = $(this).parents('#slider_profile:eq(0)').find('.fragment_profile').width();
var perPage = 1;
var numPages = Math.ceil(fragments_count / perPage);
var stepMove = fragment_width * perPage;
var container = $(this).parents('#slider_profile:eq(0)').find('.con_profile');
var firstPosition = 0;
var lastPosition = -((numPages - 1) * stepMove);
if ($(this).hasClass('next')) {
currentPage++;
if (currentPage > numPages) {
currentPage = 1;
container.animate({
'left': firstPosition
});
return;
}
container.animate({
'left': -((currentPage - 1) * stepMove)
});
}
if ($(this).hasClass('prev')) {
currentPage--;
if (currentPage < 1) {
currentPage = numPages;
container.animate({
'left': lastPosition
});
return;
}
container.animate({
'left': -((currentPage - 1) * stepMove)
});
}
});
});

Categories

Resources