Wondering if anyone can help me. I'm trying to put together a weekly photo competition page by pulling in photos from a Flickr gallery, but I can't get the images to display. It works OK for groups, but having some problems with the gallery code. Getting the correct JSON response, but can't get the results to display on the page as good as the group images do.
Here's my Javascript:
$(function() {
var map;
var markers = [];
var infowindow;
// Get gallery photos
var visibleGallery;
$.getJSON("http://api.flickr.com/services/rest/" +
"?method=flickr.galleries.getPhotos" +
"&api_key=XXXX" +
"&photoset_id=XXXX" +
"&extras=geo,tags,url_sq,url_t,url_s,url_m,url_o" +
"&format=json&jsoncallback=?", function(data, textStatus) {
var htmlString = '<div id="weekContainer">';
var weeks = sortIntoWeekArrays(data.photos.photo);
$.each(weeks, function(i, week)
{
var weekNumber = i + 1;
var numberOfWeeks = weeks.length - 1;
htmlString += '<div id="week' + weekNumber + '">';
htmlString += '<ul class="weeks">';
if(i < numberOfWeeks)
{
htmlString += '<li><a class="weekLinksNext" href="#"><span>Next</span></a></li>';
}
var sunday = new Date(week.monday.toUTCString());
sunday.setDate(week.monday.getDate() + 6);
htmlString += '<li class="weekTitle">Week ' + weekNumber + ':</li><li class="weekDate"> ' + week.monday.format("ddd d mmm") + ' — ' + sunday.format("ddd d mmm") + '</li>';
if(i > 0)
{
htmlString += '<li><a class="weekLinksPrev" href="#"><span>Previous</span></a></li>';
}
htmlString += '</ul>';
if(week.winner !== undefined)
{
htmlString += '<p class="galleryTitleFirst">Photo of the Week</p>';
htmlString += '<ul class="imagesWinners">';
htmlString += '<li class="winner"><a href="http://www.flickr.com/photos/' + week.winner.owner + '/' + week.winner.id + '" target="_blank">';
htmlString += '<img title="' + week.winner.title + '" src="' + week.winner.url_m + '" alt="' + week.winner.title + '" />';
htmlString += '</a></li>';
htmlString += '<li class="name">' + week.winner.title + '</li>';
htmlString += '<li class="owner">' + 'by ' + week.winner.ownername + '</li>';
htmlString += '</ul>';
}
htmlString += '<p class="galleryTitle">Our other favourites this week</p>';
htmlString += '<ul class="imagesRunnersUp">';
$.each(week.images, function(i, item)
{
htmlString += '<li><a href="http://www.flickr.com/photos/' + item.owner + '/' + item.id + '" target="_blank">';
htmlString += '<img title="' + item.title + '" src="' + item.url_sq + '" alt="' + item.title + '" />';
htmlString += '</a></li>';
if(item.longitude == "0" && item.latitude == "0")
{
return true;
}
var latlng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker(
{
position: latlng,
map: map,
title:item.title
});
marker.content = '<img title="' + item.title + '" src="' + item.url_s + '" alt="' + item.title + '" />';
markers.push(marker);
});
htmlString += '</ul>';
htmlString += '</div>';
});
htmlString += '</div>';
$('div#weekViewer').append(htmlString);
$('div#weekContainer > div').css('float', 'left').css('margin-right', '30px');
$('div#weekContainer').width(weeks.length * 450);
$('div#weekContainer .weekLinksPrev')
.click(function(){
$('div#weekViewer').animate({scrollLeft: '-=450'}, 'slow');
return false;
});
$('div#weekContainer .weekLinksNext')
.click(function(){
$('div#weekViewer').animate({scrollLeft: '+=450'}, 'slow');
return false;
});
});
});
function sortIntoWeekArrays(items)
{
var weeks = [];
// Returns single dimension array containing single dimension arrays
$(items).each(function(i, item)
{
var monday = new Date(item.dateadded * 1000);
monday.setDate(monday.getDate() - monday.getDay() + 1);
monday.setHours(0,0,0,0);
var week, thisWeek;
for (i in weeks)
{
week = weeks[i];
if(week.monday - monday == 0)
{
thisWeek = week;
break;
}
}
if(thisWeek === undefined)
{
thisWeek =
{
monday: monday,
images: []
};
weeks.push(thisWeek);
}
if($.inArray('winner', item.tags.split(" ")) > -1)
{
thisWeek.winner = item;
}
else
{
thisWeek.images.push(item);
}
});
return weeks.sort(function(first, second)
{
return (first.monday > second.monday) - (first.monday < second.monday);
});
}
Any help would be fantastic :)
Regards,
David
Worked it out after some help from a friend. I was missing the date_upload value in the extras argument and item.dateadded needed to change to item.upload.
Related
I am trying to create an ID to use as a selector for a modal that I will then be able to access the display properties.
$.ajax({
url: 'https://randomuser.me/api/?results=12',
dataType: 'json',
success: function(data) {
console.log(data);
employees = data.results;
$.each(employees, function (i, employee) {
newHTML += '<div id="' + i + '" class="container">';
newHTML += '<div class="employee-img-container">';
newHTML += '<img class="employee-img" src="' + employee.picture.large + '" alt="employee image">';
newHTML += '</div>';
newHTML += '<div class="employee-info-container">';
newHTML += '<h3 class="employee-name">' + employee.name.first + ' ' + employee.name.last + '</h3>';
newHTML += '<p class="employee-email">' + employee.email + '</p>';
newHTML += '<p class="employee-location">' + employee.location.city + ', ' + employee.location.state + '</p>';
newHTML += '</div></div></div></div>';
employeeArr.push(employee);
modalHTML += '<div id="modal' + i + '" class="modal">';
modalHTML += '<div class="modal-content">';
modalHTML += '<div class="modal-header">';
modalHTML += '<span class="close">×</span>';
modalHTML += '<img class="employee-img" src="' + employee.picture.large + '" alt="employee image">';
modalHTML += '<h2 class= emp-modal-name>' + employee.name.first + ' ' + employee.name.last + '</h2>';
modalHTML += '</div';
modalHTML += '<div class="modal-body">';
modalHTML += '<p>Employee Info</p>';
modalHTML += '</div></div></div>';
modalArr.push(employee);
});
$('.grid-container').html(newHTML);
$('.modal-container').html(modalHTML);
$('.container').on('click', function (event) {
console.log(event.currentTarget.id);
let newId = '#modal' + event.currentTarget.id;
let displayModal = $(newId)
let display = document.querySelector(newId);
//displayModal.style.display = 'block';
console.log(displayModal);
console.log(display);
console.log(newId);
});
}
});
When I log the event.currentTarget.id I get a number, and I can also create a string that I want to use as a selector. I can't figure out how to use it as the actual sector though. Not sure if I need to use an if statement to compare it to the id of the modal class that i want to display. Thanks!
Try like this
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});
I would like to style json feed output. I want to be able to arrange it as I want. So far this is my javascript code. I would like to achieve something like this IMG, information's such as age number etc would be possible to change location etc. I want this to work on jquery mobile as i am building an application.
function listPosts(data) {
var output = '<ul data-role="listview" data-filter="true">';
$.each(data.posts, function(key, val)
{
var tempDiv = document.createElement("tempDiv");
tempDiv.innerHTML = val.excerpt;
$("a", tempDiv).remove();
var excerpt = tempDiv.innerHTML;
output += '<li>';
output += '<a href="#blogpost" onclick = "showPost('+ val.id +') ">';
output += '<h3>' + val.title + "</h3>";
output += (val.thumbnail) ?
'<img src="' + val.thumbnail + '" alt="' + val.title + '">':
'<img src="images/itblogo.png" alt="ITB Logo">';
output += '<h3>' + val.custom_fields.gender + "</h3>";
output += '<h3>' + val.custom_fields.age + "</h3>";
output += '</a>';
output += '</li>';
}); //go through each post
output += "</ul>";
$('#postlist').html(output);
} //listPosts
function showPost(id) {
$.getJSON('http://www.pawmatch.info?json=get_post&post_id=' + id + '&callback=?', function(data) {
var
output ='<img src="'+data.post.thumbnail + '">'
output += '<h3>' + data.post.custom_fields.dogs_name + '</h3>'
output +='<h3>'+data.post.custom_fields.dog_size + '</h3>'
output +='<h3>'+data.post.custom_fields.age + '</h3>'
output +='<h3>'+data.post.custom_fields.gender + '</h3>'
output +='<h3>'+data.post.custom_fields.breed + '</h3>'
output +='<h3>'+data.post.custom_fields.extra_information + '</h3>'
$('#mypost').html(output);
});
}
I have code below that renders a few products on a page. Each of these products shares the same data attribute "data-item-upc". There is also a button that is rendered for each product on the page (6 total buttons to be exact). They all share this same data-item-upc data attribute.
I am able to successfully grab the value of the data atrribute and match it to the item with the same UPC value in the second database. But for some reason only the first button works and shows the modal. Not sure whats going on. Hoping someone can help me out would really appreciate it.
//declare variable to store JSON data
var product_data = {};
var nutritional_data = {};
$(document).ready(function() {
'use strict';
//grab product data
$.ajax({
dataType: "jsonp",
url: 'path to URL',
cache: true,
success: function(data){
//assign JSON to product data variable
product_data = JSON.parse(JSON.stringify(data).replace(/"\s+|\s+"/g,'"'));
//grab nutrional data
$.ajax({
dataType: "jsonp",
url: 'path to URL',
cache: true,
success: function(json){
//assign JSON to product data variable
nutritional_data = JSON.parse(JSON.stringify(json).replace(/"\s+|\s+"/g,'"'));
//declare divs to store data
var productDivOne = '';
var productDivTwo = '';
$.each(product_data, function(i, item) {
//convert JSON strings to uppercase for comparison
var brandLetter = item.itemBrandLetter.toUpperCase();
var foodService = item.itemDeli.toUpperCase();
var brandItem = item.itemName;
if (brandLetter == "LB" && foodService == "N") {
if (brandItem.indexOf("Panettone") >= 0) {
productDivOne +=
'<div class="item col-xs-12 col-sm-4 col-md-4 col-lg-4">' +
'<div class="thumbnail">' +
'<img class="scale-down-seperate-prods" src="' + item.imageURL + '" alt="' + item.itemName + '" />' +
'<div class="caption">' + '<br>' +
'<h3 class="group inner list-group-item-heading">' + item.itemName + '</h3>' +
'<h4 class="group inner list-group-item-text">' + item.itemFullUPC.slice(1, -1) + ' • ' + item.itemPackSize.toLowerCase().substring(item.itemPackSize.lastIndexOf("/") + 1) + '</h4>' +
'<button type="button" class="btn btn-info btn-lg showNutritionFacts" data-item-upc="' + item.itemFullUPC + '" value="itemFullUPC">Nutrition Facts</button>' +
'</div>' +
'</div>' +
'</div>';
}
if (brandItem.indexOf("Egg") >= 0) {
productDivTwo +=
'<div class="item col-xs-12 col-sm-4 col-md-4 col-lg-4">' +
'<div class="thumbnail">' +
'<img class="scale-down-seperate-prods" src="' + item.imageURL + '" alt="' + item.itemName + '" />' +
'<div class="caption">' + '<br>' +
'<h3 class="group inner list-group-item-heading">' + item.itemName + '</h3>' +
'<h4 class="group inner list-group-item-text">' + item.itemFullUPC.slice(1, -1) + ' • ' + item.itemPackSize.toLowerCase().substring(item.itemPackSize.lastIndexOf("/") + 1) + '</h4>' +
'<button type="button" class="btn btn-info btn-lg showNutritionFacts" data-item-upc="' + item.itemFullUPC + '" value="itemFullUPC">Nutrition Facts</button>' +
'</div>' +
'</div>' +
'</div>';
}
}
});
//show nutritional information on button click
$("body").on('click', ".showNutritionFacts", function(event){
//get passed data from other function
var clickedItemUPC = $(this).data('item-upc');
alert(clickedItemUPC);
//declare variables to store data
var servingSize = '';
var servingPerContainer = '';
var calories = '';
var caloriesFat = '';
var totalFatGrams = '';
var totalFatPercentage = '';
var saturatedFatGrams = '';
var saturatedFatPercentage = '';
var transFatGrams = '';
var polyunsaturatedFatGrams = '';
var monounsaturatedFatGrams = '';
var cholesterolGrams = '';
var cholesterolPercentage = '';
var sodiumGrams = '';
var sodiumPercentage = '';
var totalCarbohydrateGrams = '';
var totalCarbohydratePercentage = '';
var dietaryFiberGrams = '';
var dietaryFiberPercentage = '';
var sugarGrams = '';
var sugarGramsAdded = '';
var sugarGramsAddedPercentage = '';
var proteinGrams = '';
var vitaminAPercentage = '';
var vitaminCGrams = '';
var vitaminCPercentage = '';
var vitaminDGrams = '';
var vitaminDPercentage = '';
var calciumGrams = '';
var calciumPercentage = '';
var ironGrams = '';
var ironPercentage = '';
var potassiumGrams = '';
var potassiumPercentage = '';
var thiamineGrams = '';
var thiaminePercentage = '';
var riboflavinGrams = '';
var riboflavinPercentage = '';
var niacinGrams = '';
var niacinPercentage = '';
var ingredients = '';
//comparison UPC variable
var compareNutUPC;
$.each(nutritional_data, function (i, item) {
//assign comparison UPC to itemNum
compareNutUPC = item.itemNum;
//compare product UPC in nutritional and product data
if (clickedItemUPC == compareNutUPC) {
servingSize += item.servingSize;
servingPerContainer += item.itemServings;
calories += item.itemCalories;
caloriesFat += item.itemCaloriesFromFat;
transFatGrams += item.itemTransFat + 'g';
polyunsaturatedFatGrams += item.itemPolyUnsatFat + 'g';
monounsaturatedFatGrams += item.itemMonoUnsatFat + 'g';
saturatedFatGrams += item.itemSaturFat + 'g';
saturatedFatPercentage += item.itemSaturFatPerc + '%';
totalFatGrams += item.itemTotalFat + 'g';
totalFatPercentage += item.itemTotalFatPerc + '%';
cholesterolGrams += item.itemCholesterol + 'mg';
cholesterolPercentage += item.itemCholesterolPerc + '%';
sodiumGrams += item.itemSodium + 'mg';
sodiumPercentage += item.itemSodiumPerc + '%';
totalCarbohydrateGrams += item.itemTotalCarb + 'g';
totalCarbohydratePercentage += item.itemTotalCarbPerc + '%';
sugarGrams += item.itemSugars + 'g';
sugarGramsAdded += item.itemSugarsAdded + 'g';
sugarGramsAddedPercentage += item.itemSugarsAddedPerc + '%';
dietaryFiberGrams += item.itemDietFiber + 'g';
dietaryFiberPercentage += item.itemDietFiberPerc + '%';
proteinGrams += item.itemProtein + 'g';
vitaminAPercentage += item.itemVitaminA + '%';
vitaminCPercentage += item.itemVitaminC + '%';
vitaminDGrams += item.itemVitaminDMeasure;
vitaminDPercentage += item.itemVitaminD + '%';
calciumGrams += item.itemCalciumMeasure;
calciumPercentage += item.itemCalcium + '%';
ironGrams += item.itemIronMeasure;
ironPercentage += item.itemIron + '%';
thiaminePercentage += item.itemThiamin + '%';
riboflavinPercentage += item.itemRiboflavin + '%';
niacinPercentage += item.itemNiacin + '%';
potassiumGrams += item.itemPotassium;
potassiumPercentage += item.itemPotassiumPerc + '%';
ingredients += item.itemIngredients;
}
});
$(".servingSize").html(servingSize.replace(/\s+(?=g)/g, '').toLowerCase());
$(".servingPerContainer").html(servingPerContainer);
$(".calories").html(calories);
$(".caloriesFat").html(caloriesFat);
$(".transFatGrams").html(transFatGrams);
$(".polyunsaturatedFatGrams").html(polyunsaturatedFatGrams);
$(".monounsaturatedFatGrams").html(monounsaturatedFatGrams);
$(".saturatedFatGrams").html(saturatedFatGrams);
$(".saturatedFatPercentage").html(saturatedFatPercentage);
$(".totalFatGrams").html(totalFatGrams);
$(".totalFatPercentage").html(totalFatPercentage);
$(".cholesterolGrams").html(cholesterolGrams);
$(".cholesterolPercentage").html(cholesterolPercentage);
$(".sodiumGrams").html(sodiumGrams);
$(".sodiumPercentage").html(sodiumPercentage);
$(".totalCarbohydrateGrams").html(totalCarbohydrateGrams);
$(".totalCarbohydratePercentage").html(totalCarbohydratePercentage);
$(".sugarGrams").html(sugarGrams);
$(".sugarGramsAdded").html(sugarGramsAdded);
$(".sugarGramsAddedPercentage").html(sugarGramsAddedPercentage);
$(".dietaryFiberGrams").html(dietaryFiberGrams);
$(".dietaryFiberPercentage").html(dietaryFiberPercentage);
$(".proteinGrams").html(proteinGrams);
$(".vitaminAPercentage").html(vitaminAPercentage);
$(".vitaminCPercentage").html(vitaminCPercentage);
$(".vitaminDGrams").html(vitaminDGrams);
$(".vitaminDPercentage").html(vitaminDPercentage);
$(".calciumGrams").html(calciumGrams);
$(".calciumPercentage").html(calciumPercentage);
$(".ironGrams").html(ironGrams);
$(".ironPercentage").html(ironPercentage);
$(".thiaminePercentage").html(thiaminePercentage);
$(".riboflavinPercentage").html(riboflavinPercentage);
$(".niacinPercentage").html(niacinPercentage);
$(".potassiumGrams").html(potassiumGrams);
$(".potassiumPercentage").html(potassiumPercentage);
$(".ingredients").html(ingredients.toUpperCase());
//determine which modal to show
if ($('.vitaminDGrams:contains("mcg")').length > 0 && $('.calciumGrams:contains("mg")').length > 0 && $('.ironGrams:contains("mg")').length > 0) {
$('.nutritionPopupAlternate').modal('show');
} else if (servingSize == 0) {
$('.nutritionPopupNoInfo').modal('show');
} else {
$('.nutritionPopupStandard').modal('show');
}
});
//append to appropriate div
$('#productDivOne').html(productDivOne);
$('#productDivTwo').html(productDivTwo);
}
});
//end of prod data
}
});
//end of nut data
});
Thanks to Sandy i was able to minify my code and find the issue. Turns out it was looking for something that was added later from a different source code that I took, after editing the DIV it works perfectly now.
I have an html <table> that I need to fill with data from a database query. The query returns 10 rows and then sends the data to the method fill(data) to fill the table:
function getTopQ() {
alert("Get top Qs");
callServer('fill', 'checkConnection', false, 'SelectTopQues.php');
}
function fill(data) {
alert("ready to fill now");
$('#table').html('');
var search = '#table';
for (var i = 0; i < data.length; i++) {
$('#table').listview("refresh");
var Questions = data[i];
var str = '<td " ID="' + Questions[0] +
'" Question="' + Questions[1] +
'" UserID="' + Questions[2] +
'"CategoryId"' + '" SubCategoryId"' + '" DatePosted"' + '"';
str += '">'; //end li
str += '<a href="" data-transition="fade">';
str += Questions[1];
str += '</a>';
//str += '<span class="hiddenData">' + item[13] + '</span>';
str += '</td>';
$('#table').append(str);
$('#table').listview("refresh");
}
console.log(data);
console.log($('#table'));
$('#table').listview("refresh");
}
I am trying to render a catalog from an XML document and everything works, although when trying to show a default image if there is no image present in the XML node, it disables the parent node therefore forcing it not to show any of it and it reads me an error in my console saying:
Uncaught TypeError: Cannot read property 'getElementsByTagName' of
undefined
Which is pointing to this part of the code:
if (records[i].getElementsByTagName("IMAGE")[0].childNodes.length > 0)
{
So my question is where in my code below is my error causing it to not load the XML node?
PS: If anybody needs more of my code please let me know, and I would be happy to post it.
for (var i = fromItem; i < nextMaxItem; i++) {
if (records[i].getElementsByTagName("IMAGE")[0].childNodes.length > 0) {
xmlContent += '<article class="post all ' + records[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue + '" id="">'
+ '<div class="col-sm-4 col-lg-4 col-md-4"><div class="thumbnail img-hover">'
+ '<a class="fancybox" rel="group" href="' + records[i].getElementsByTagName("BIGIMAGE")[0].childNodes[0].nodeValue + '" title="'+ records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue +'">'
+ '<img class="product-image" src="' + records[i].getElementsByTagName("IMAGE")[0].childNodes[0].nodeValue + '" alt="' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '" />'
+ '<div class="caption">'
+ '<h4>' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '</h4>'
+ '<p>' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '</p>'
+ '</div>'
+ "</a></div></div></article>";
} else {
xmlContent += '<article class="post all ' + records[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue + '" id="">'
+ '<div class="col-sm-4 col-lg-4 col-md-4"><div class="thumbnail img-hover">'
+ '<a class="fancybox" rel="group" href="' + records[i].getElementsByTagName("BIGIMAGE")[0].childNodes[0].nodeValue + '" title="'+ records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue +'">'
+ '<img class="product-image" src="/images/Products/no-preview.jpg" alt="No Preview Available" />'
+ '<div class="caption">'
+ '<h4>' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '</h4>'
+ '<p>' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '</p>'
+ '</div>'
+ "</a></div></div></article>";
}
}
Here is the whole JavaScript code:
var page = 1, perPage = 12, content = document.getElementById('content'),
pagination = document.getElementById('pagination'), records;
function paganation(page) {
var nextMaxItem = perPage * page,
fromItem = (page - 1) * perPage,
maxPages = Math.ceil(records.length / perPage);
var xmlContent = '<div class="row">';
for (var i = fromItem; i < nextMaxItem; i++) {
if (records[i].getElementsByTagName("IMAGE")[0].childNodes.length > 0) {
xmlContent += '<article class="post all ' + records[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue + '" id="">'
+ '<div class="col-sm-4 col-lg-4 col-md-4"><div class="thumbnail img-hover">'
+ '<a class="fancybox" rel="group" href="' + records[i].getElementsByTagName("BIGIMAGE")[0].childNodes[0].nodeValue + '" title="' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '">'
+ '<img class="product-image" src="' + records[i].getElementsByTagName("IMAGE")[0].childNodes[0].nodeValue + '" alt="' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '" />'
+ '<div class="caption">'
+ '<h4>' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '</h4>'
+ '<p>' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '</p>'
+ '</div>'
+ "</a></div></div></article>";
} else {
xmlContent += '<article class="post all ' + records[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue + '" id="">'
+ '<div class="col-sm-4 col-lg-4 col-md-4"><div class="thumbnail img-hover">'
+ '<a class="fancybox" rel="group" href="' + records[i].getElementsByTagName("BIGIMAGE")[0].childNodes[0].nodeValue + '" title="' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '">'
+ '<img class="product-image" src="/images/Products/no-preview.jpg" alt="No Preview Available" />'
+ '<div class="caption">'
+ '<h4>' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '</h4>'
+ '<p>' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '</p>'
+ '</div>'
+ "</a></div></div></article>";
}
}
xmlContent += "</div>";
content.innerHTML = xmlContent;
var paginationContent = '<nav><ul class="pagination">';
if (page > 1) {
paginationContent += '<li>';
paginationContent += '<span aria-hidden="true">«</span>';
paginationContent += '</li>';
} else {
paginationContent += '<li class="disabled">';
paginationContent += '<span aria-hidden="true">«</span>';
paginationContent += '</li>'
}
var prevPosition = page - 3;
var nextPosition = page + 3;
for (var i = 1; i <= maxPages; i++) {
if (i != page) {
if (i >= prevPosition && i <= nextPosition) {
var linkToPage = i == prevPosition ? 1 : i == nextPosition ? maxPages : i;
var linkText = i == prevPosition ? "..." : i == nextPosition ? "..." : i;
paginationContent += "<li>";
paginationContent += '' + linkText + '';
paginationContent += "</li>";
}
} else {
paginationContent += "<li class='active'>";
paginationContent += '' + i + '';
paginationContent += "</li>";
}
}
var next = page + 1;
if (next <= maxPages) {
paginationContent += '<li>';
paginationContent += '<span aria-hidden="true">»</span>';
paginationContent += '</li>';
} else {
paginationContent += '<li class="disabled">';
paginationContent += '<span aria-hidden="true">»</span>';
paginationContent += '</li>';
}
paginationContent += '</ul></nav>';
pagination.innerHTML = paginationContent;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", xmlUrl, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
records = xmlDoc.getElementsByTagName(xmlNode);
records = Array.prototype.slice.call(records).sort(function () {
return Math.random() > 0.5 ? 1 : -1
});
paganation(1);
If we imagine that records was of length 18, then for the second page, you would have:
fromItem - 12
nextMaxItem - 24
You are iterating i from fromItem to nextMaxItem, but as soon as you go past i = 18, you've gone past the end of records. You need to make sure that doesn't happen. You need to ensure that you don't iterate past the end of your array:
var max = Math.min(nextMaxItem, records.length);
for (var i = fromItem; i < max; i++) {
....
}