Hide page numbers in jquery paginate - javascript

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

Related

JavaScript - Set function to return all items based on 1 or 2 selected tags (NO jQUERY)

I have some JavaScrip that is meant to check if there are any media tags selected or industry tags selected--this is so the portfolio items can be sorted and displayed accordingly in the browser.
What I have almost works 100%, but I can't figure out how to make it so that if only a media tag is selected or if only an industry tag is selected, the portfolio items should still be sorted accordingly. Currently, you have to select a media tag AND an industry tag, but I'd like users to be able to search using just a media tag OR just an industry tag.
Here is what I want to accomplish: If only a media tag is selected, then get all portfolio pieces that are associated with that media tag. If only an industry tag is selected, get all portfolio items that are associated with that industry tag. If a media tag AND industry tag are selected at the same time, get all portfolio items that are associated with BOTH.
Vanilla JS isn't my strong point so forgive me if this is a dumb question, but this has had me stumped for hours now.
No jQuery answers, please, as this whole page's functionality is built using JavaScript.
Here is the function:
var update = function () {
closeDrawer();
// update ui to reflect tag changes
// get our list of items to display
var itemsToDisplay = [];
var currentMediaTag = controlsContainer.querySelector('.media.selected');
var currentIndustryTag = controlsContainer.querySelector('.industry.selected');
if (currentMediaTag != "" && currentMediaTag != null) {
selectedMediaFilter = currentMediaTag.innerHTML;
}
if (currentIndustryTag != "" && currentIndustryTag != null) {
selectedIndustryFilter = currentIndustryTag.innerHTML;
}
if (selectedMediaFilter == "" && selectedIndustryFilter == "") {
itemsToDisplay = portfolioItems.filter(function (item) {
return item.preferred;
});
} else {
itemsToDisplay = portfolioItems.filter(function (item) {
var mediaTags = item.media_tags,
industryTags = item.industry_tags;
if(industryTags.indexOf(selectedIndustryFilter) < 0){
return false;
}
else if(mediaTags.indexOf(selectedMediaFilter) < 0){
return false;
}
else{
return true;
}
});
}
renderItems(itemsToDisplay);
}
Not entirely sure it's necessary but just in case, here is the complete JS file that handles the portfolio page:
(function ($) {
document.addEventListener("DOMContentLoaded", function (event) {
// for portfolio interaction
var portfolioGrid = (function () {
var gridSize = undefined,
parentContainer = document.querySelector('.portfolio-item-container');
containers = parentContainer.querySelectorAll('.view'),
drawer = parentContainer.querySelector('.drawer'),
bannerContainer = drawer.querySelector('.banner-container'),
thumbsContainer = drawer.querySelector('.thumbs-container'),
descriptionContainer = drawer.querySelector('.client-description'),
clientNameContainer = drawer.querySelector('.client-name'),
controlsContainer = document.querySelector('.portfolio-controls-container'),
selectedMediaFilter = "", selectedIndustryFilter = "";
var setGridSize = function () {
var windowSize = window.innerWidth,
previousGridSize = gridSize;
if (windowSize > 1800) {
gridSize = 5;
} else if (windowSize > 900) {
gridSize = 4;
} else if (windowSize > 600 && windowSize <= 900) {
gridSize = 3;
} else {
gridSize = 2;
}
if (previousGridSize != gridSize) {
closeDrawer();
}
};
var attachResize = function () {
window.onresize = function () {
setGridSize();
};
};
var getRowClicked = function (boxNumber) {
return Math.ceil(boxNumber / gridSize);
};
var getLeftSibling = function (row) {
var cI = row * gridSize;
return containers[cI >= containers.length ? containers.length - 1 : cI];
};
var openDrawer = function () {
drawer.className = 'drawer';
scrollToBanner();
};
var scrollToBanner = function () {
var mainContainer = document.querySelector('#main-container'),
mainBounding = mainContainer.getBoundingClientRect(),
scrollY = (drawer.offsetTop - mainBounding.bottom) - 10,
currentTop = document.body.getBoundingClientRect().top;
animate(document.body, "scrollTop", "", document.body.scrollTop, scrollY, 200, true);
};
var animate = function (elem, style, unit, from, to, time, prop) {
if (!elem) return;
var start = new Date().getTime(),
timer = setInterval(function () {
var step = Math.min(1, (new Date().getTime() - start) / time);
if (prop) {
elem[style] = (from + step * (to - from)) + unit;
} else {
elem.style[style] = (from + step * (to - from)) + unit;
}
if (step == 1) clearInterval(timer);
}, 25);
elem.style[style] = from + unit;
}
var closeDrawer = function () {
drawer.className = 'drawer hidden';
};
var cleanDrawer = function () {
bannerContainer.innerHTML = "";
clientNameContainer.innerHTML = "";
descriptionContainer.innerHTML = "";
thumbsContainer.innerHTML = "";
};
var resetThumbs = function () {
Array.prototype.forEach.call(thumbsContainer.querySelectorAll('.thumb'), function (t) {
t.className = "thumb";
});
};
var handleBannerItem = function (item) {
bannerContainer.innerHTML = "";
if (item.youtube) {
var videoContainer = document.createElement('div'),
iframe = document.createElement('iframe');
videoContainer.className = "videowrapper";
iframe.className = "youtube-video";
iframe.src = "https://youtube.com/embed/" + item.youtube;
videoContainer.appendChild(iframe);
bannerContainer.appendChild(videoContainer);
} else if (item.soundcloud) {
var iframe = document.createElement('iframe');
iframe.src = item.soundcloud;
iframe.className = "soundcloud-embed";
bannerContainer.appendChild(iframe);
} else if (item.banner) {
var bannerImage = document.createElement('img');
bannerImage.src = item.banner;
bannerContainer.appendChild(bannerImage);
}
};
var attachClick = function () {
Array.prototype.forEach.call(containers, function (n, i) {
n.querySelector('a.info').addEventListener('click', function (e) {
e.preventDefault();
});
n.addEventListener('click', function (e) {
var boxNumber = i + 1,
row = getRowClicked(boxNumber);
var containerIndex = row * gridSize;
if (containerIndex >= containers.length) {
// we're inserting drawer at the end
parentContainer.appendChild(drawer);
} else {
// we're inserting drawer in the middle somewhere
var leftSiblingNode = getLeftSibling(row);
leftSiblingNode.parentNode.insertBefore(drawer, leftSiblingNode);
}
// populate
cleanDrawer();
var mediaFilterSelected = document.querySelector('.media-tags .tag-container .selected');
var selectedFilters = "";
if (mediaFilterSelected != "" && mediaFilterSelected != null) {
selectedFilters = mediaFilterSelected.innerHTML;
}
var portfolioItemName = '';
var selectedID = this.getAttribute('data-portfolio-item-id');
var data = portfolioItems.filter(function (item) {
portfolioItemName = item.name;
return item.id === selectedID;
})[0];
clientNameContainer.innerHTML = data.name;
descriptionContainer.innerHTML = data.description;
var childItems = data.child_items;
//We will group the child items by media tag and target the unique instance from each group to get the right main banner
Array.prototype.groupBy = function (prop) {
return this.reduce(function (groups, item) {
var val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}
var byTag = childItems.groupBy('media_tags');
if (childItems.length > 0) {
handleBannerItem(childItems[0]);
var byTagValues = Object.values(byTag);
byTagValues.forEach(function (tagValue) {
for (var t = 0; t < tagValue.length; t++) {
if (tagValue[t].media_tags == selectedFilters) {
handleBannerItem(tagValue[0]);
}
}
});
childItems.forEach(function (item, i) {
var img = document.createElement('img'),
container = document.createElement('div'),
label = document.createElement('p');
container.appendChild(img);
var mediaTags = item.media_tags;
container.className = "thumb";
label.className = "childLabelInactive thumbLbl";
thumbsContainer.appendChild(container);
if (selectedFilters.length > 0 && mediaTags.length > 0) {
for (var x = 0; x < mediaTags.length; x++) {
if (mediaTags[x] == selectedFilters) {
container.className = "thumb active";
label.className = "childLabel thumbLbl";
}
}
}
else {
container.className = i == 0 ? "thumb active" : "thumb";
}
img.src = item.thumb;
if (item.media_tags != 0 && item.media_tags != null) {
childMediaTags = item.media_tags;
childMediaTags.forEach(function (cMTag) {
varLabelTxt = document.createTextNode(cMTag);
container.appendChild(label);
label.appendChild(varLabelTxt);
});
}
img.addEventListener('click', function (e) {
scrollToBanner();
resetThumbs();
handleBannerItem(item);
container.className = "thumb active";
});
});
}
openDrawer();
});
});
};
var preloadImages = function () {
portfolioItems.forEach(function (item) {
var childItems = item.child_items;
childItems.forEach(function (child) {
(new Image()).src = child.banner;
(new Image()).src = child.thumb;
});
});
};
//////////////////////////////////// UPDATE FUNCTION /////////////////////////////////////
var update = function () {
closeDrawer();
// update ui to reflect tag changes
// get our list of items to display
var itemsToDisplay = [];
var currentMediaTag = controlsContainer.querySelector('.media.selected');
var currentIndustryTag = controlsContainer.querySelector('.industry.selected');
if (currentMediaTag != "" && currentMediaTag != null) {
selectedMediaFilter = currentMediaTag.innerHTML;
}
if (currentIndustryTag != "" && currentIndustryTag != null) {
selectedIndustryFilter = currentIndustryTag.innerHTML;
}
if (selectedMediaFilter == "" && selectedIndustryFilter == "") {
itemsToDisplay = portfolioItems.filter(function (item) {
return item.preferred;
});
} else {
itemsToDisplay = portfolioItems.filter(function (item) {
var mediaTags = item.media_tags,
industryTags = item.industry_tags;
if (industryTags.indexOf(selectedIndustryFilter) < 0) {
return false;
}
else if (mediaTags.indexOf(selectedMediaFilter) < 0) {
return false;
}
else {
return true;
}
});
}
renderItems(itemsToDisplay);
}
//////////////////////////////////// RENDERITEMS FUNCTION /////////////////////////////////////
var renderItems = function (items) {
var children = parentContainer.querySelectorAll('.view');
Array.prototype.forEach.call(children, function (child) {
// remove all event listeners then remove child
parentContainer.removeChild(child);
});
items.forEach(function (item) {
var container = document.createElement('div'),
thumb = document.createElement('img'),
mask = document.createElement('div'),
title = document.createElement('h6'),
excerpt = document.createElement('p'),
link = document.createElement('a');
container.className = "view view-tenth";
container.setAttribute('data-portfolio-item-id', item.id);
thumb.src = item.thumb;
mask.className = "mask";
title.innerHTML = item.name;
excerpt.innerHTML = item.excerpt;
link.href = "#";
link.className = "info";
link.innerHTML = "View Work";
container.appendChild(thumb);
container.appendChild(mask);
mask.appendChild(title);
mask.appendChild(excerpt);
mask.appendChild(link);
parentContainer.insertBefore(container, drawer);
});
containers = parentContainer.querySelectorAll('.view');
attachClick();
};
var filterHandler = function (linkNode, tagType) {
var prevSelection = document.querySelector("." + tagType + '.selected');
if (prevSelection != "" && prevSelection != null) {
prevSelection.className = tagType + ' tag';
}
linkNode.className = tagType + ' tag selected';
update();
};
var clearFilters = function (nodeList, filterType) {
Array.prototype.forEach.call(nodeList, function (node) {
node.className = filterType + " tag";
console.log("Clear filters function called");
});
}
var attachFilters = function () {
var mediaFilters = controlsContainer.querySelectorAll('.tag.media'),
industryFilters = controlsContainer.querySelectorAll('.tag.industry'),
filterToggle = controlsContainer.querySelectorAll('.filter-toggle');
// resets
controlsContainer.querySelector('.media-tags .reset')
.addEventListener('click',
function (e) {
e.preventDefault();
selectedMediaFilter = "";
clearFilters(controlsContainer.querySelectorAll('.media-tags a.tag'), "media");
update();
}
);
controlsContainer.querySelector('.industry-tags .reset')
.addEventListener('click',
function (e) {
e.preventDefault();
selectedIndustryFilter = "";
clearFilters(controlsContainer.querySelectorAll('.industry-tags a.tag'), "industry");
update();
}
);
Array.prototype.forEach.call(filterToggle, function (toggle) {
toggle.addEventListener('click', function (e) {
if (controlsContainer.className.indexOf('open') < 0) {
controlsContainer.className += ' open';
} else {
controlsContainer.className = controlsContainer.className.replace('open', '');
}
});
});
//Attaches a click event to each media tag "button"
Array.prototype.forEach.call(mediaFilters, function (filter) {
filter.addEventListener('click', function (e) {
e.preventDefault();
// var selectedMediaFilter = controlsContainer.querySelector('.media.selected');
//console.log("Media tag: " +this.innerHTML); *THIS WORKS*
filterHandler(this, "media");
});
});
Array.prototype.forEach.call(industryFilters, function (filter) {
filter.addEventListener('click', function (e) {
e.preventDefault();
// var selectedIndustryFilter = this.querySelector('.industry.selected');
// console.log("Industry tag: " +this.innerHTML); *THIS WORKS*
filterHandler(this, "industry");
});
});
};
return {
init: function () {
setGridSize();
attachResize();
attachClick();
preloadImages();
// portfolio page
if (controlsContainer) {
attachFilters();
}
}
};
})();
portfolioGrid.init();
});
}());
$ = jQuery.noConflict();
if(industryTags.indexOf(selectedIndustryFilter) < 0){
return false;
}
else if(mediaTags.indexOf(selectedMediaFilter) < 0){
return false;
}
That part is giving you headaches. Whenever no industry tag or media tag is selected this will exit the function.
Change to:
if(industryTags.indexOf(selectedIndustryFilter) < 0 && mediaTags.indexOf(selectedMediaFilter) < 0){
return false;
}
Now it will test if at least one tag is selected. If so then render items.
I made a change just to experiment with an idea, and this setup works:
if((selectedIndustryFilter !="" && industryTags.indexOf(selectedIndustryFilter) < 0) || (selectedMediaFilter !="" && mediaTags.indexOf(selectedMediaFilter) < 0)){
return false;
}
return true;
Not sure if it's the best solution ever but it seems to work and I'm not going to complain.

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;

Pagination using 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.

Using PhantomJS for screenshots after logging in

I am attempting to use PhantomJs to crawl our ASP.Net web app and take screenshots of a list of pages defined in a simple text file of URLs. I have been able to get it working fine for pages not behind the log-in wall, but can't seem to get my PhantomJs instance to get authenticated. Log messages show that I'm doing things in the right order with my two interval functions - any ideas how to make sure I'm logged in first?
var fs = require('fs'),
system = require('system');
var content = '',
f = null,
lines = null,
pages =null,
destinations = null,
eol = system.os.name == 'windows' ? "\r\n" : "\n";
//read in a line break separated list of urls
//page at index 0 is the login page
try {
f = fs.open(".\\urls.txt", "r");
content = f.read();
} catch (e) {
console.log(e);
}
if (f) {
f.close();
}
if (content) {
lines = content.split(eol);
pages = new Array();
destinations = new Array();
for (var i = 0, len = lines.length; i < len; i++) {
var pageName = lines[i].substring(lines[i].lastIndexOf('/') + 1);
pages[i] = pageName;
destinations[i] = ".\\NewScreenShot\\" + pageName + '.png';
}
}
console.log('Pages found: ' + pages.length);
var page = require('webpage').create();
var loginIndex = 0;
var loginInProgress = false;
var loginSteps = [
function() {
//Enter Credentials
page.evaluate(function() {
document.getElementById("txtusername").value = "ausername#mysite.com";
document.getElementById("txtpassword").value ="12345678";
return;
});
},
function() {
//Login
page.evaluate(function() {
var arr = document.getElementById("form1");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].submit();
return;
}
}
});
}
];
var LoadPage = function() {
if (!loadInProgress && pageindex < pages.length) {
console.log("image " + (pageindex + 1) + " of " + lines.length);
page.open(lines[pageindex]);
}
if (pageindex == lines.length) {
console.log("<< Image render complete! >>");
phantom.exit();
}
}
//PNG RENDER
var pageindex = 0;
var loadInProgress = false;
var interval = setInterval(LoadPage, 500);
page.onLoadStarted = function() {
loadInProgress = true;
if(pageindex == 0) {
loginInProgress = true;
}
console.log('page ' + (pageindex + 1) + ' load started');
};
page.onLoadFinished = function() {
loadInProgress = false;
if(pageindex == 0)
{
loginInProgress = false;
console.log("stopping page interval");
clearInterval(interval);
}
page.evaluate(
function () {
var scaleVal = "scale("+arguments[0] || '1.0'+")";
document.body.style.webkitTransform = scaleVal;
}
);
console.log("rendering:" + destinations[pageindex]);
page.render(destinations[pageindex]); // RENDER PAGE //
if (pageindex == 0){
var loginInterval = setInterval(function() {
if (!loginInProgress && typeof loginSteps[loginIndex] == "function") {
console.log("login step: " + loginIndex )
loginSteps[loginIndex]();
loginIndex++;
}
if (typeof loginSteps[loginIndex] != "function") {
console.log("stopping login interval");
clearInterval(loginInterval);
console.log("starting page interval");
setInterval(LoadPage, 500);
}
}, 50);
}
pageindex++;
}
Turns out the problem was form submit vs button click. working code below:
var urlsLocation = "C:\\PhantomJs\\urls.txt";
var newScreenshotFolder = "C:\\PhantomJs\\NewScreenShot\\";
var fs = require('fs'),
system = require('system');
var content = '',
f = null,
lines = null,
pages =null,
destinations = null,
eol = system.os.name == 'windows' ? "\r\n" : "\n";
//read in a return separated list of urls
try {
f = fs.open(urlsLocation, "r");
content = f.read();
} catch (e) {
console.log(e);
}
if (f) {
f.close();
}
if (content) {
lines = content.split(eol);
pages = new Array();
destinations = new Array();
for (var i = 0, len = lines.length; i < len; i++) {
var pageName = lines[i].substring(lines[i].lastIndexOf('/') + 1);
pages[i] = pageName;
destinations[i] = newScreenshotFolder + pageName.replace(/[^a-zA-Z0-9\.]/g, "") + '.png';
}
}
console.log('Pages found: ' + pages.length);
var page = require('webpage').create();
var loginIndex = 0;
var loginInProgress = false;
var loginCompleted = false;
var loginSteps = [
function() {
//Enter Credentials
page.evaluate(function() {
document.getElementById("txtusername").value = "testemail#gmail.com";
document.getElementById("txtpassword").value = "12345678";
return;
});
},
function() {
//Login
page.evaluate(function() {
document.getElementById("btnLogin").click();
return;
});
}
];
var LoadPage = function() {
if (!loadInProgress && pageindex < pages.length) {
console.log("image " + (pageindex + 1) + " of " + lines.length);
page.open(lines[pageindex]);
}
if (pageindex == lines.length) {
console.log("<< Image render complete! >>");
phantom.exit();
}
}
//PNG RENDER
var pageindex = 0;
var loadInProgress = false;
var interval = setInterval(LoadPage, 500);
page.onLoadStarted = function() {
loadInProgress = true;
if(pageindex == 0) {
loginInProgress = true;
}
console.log('page ' + (pageindex + 1) + ' load started');
};
page.onLoadFinished = function() {
loadInProgress = false;
if(pageindex == 0)
{
loginInProgress = false;
console.log("stopping page interval");
clearInterval(interval);
}
page.evaluate(
function () {
var scaleVal = "scale("+arguments[0] || '1.0'+")";
document.body.style.webkitTransform = scaleVal;
}
);
console.log("rendering:" + destinations[pageindex]);
page.render(destinations[pageindex]); // RENDER PAGE //
if (pageindex == 0){
var loginInterval = setInterval(function() {
if (!loginInProgress && typeof loginSteps[loginIndex] == "function") {
console.log("login step: " + loginIndex )
loginSteps[loginIndex]();
loginIndex++;
}
if (typeof loginSteps[loginIndex] != "function") {
console.log("stopping login interval");
clearInterval(loginInterval);
console.log("starting page interval");
setInterval(LoadPage, 1000);
}
}, 50);
}
pageindex++;
}

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