create pagination for array of objects - javascript

I have a nice list of 200 pokemons from pokeapi.co and I have tried to paginate them (20 item/page, 10 pages). I found a nice tutorial, made my own pagination based on that but at the end just doesnt works.
I have tried to call the nextPage, previousPage, firstPage and lastPage. fuctions via HTML button but I get the following error in all 4 cases:
Uncaught ReferenceError: previousPage is not defined
at HTMLButtonElement.onclick (index.html:21)
I am beginner and I dont see the whole picture as clean as a pro, I dont know lot of things and cant figure it out whats wrong with my code!
Please take a look at my code.
Thank you for your time!
//wrapping pokemonList array in an IIFE
const pokemonRepository = (function() {
const pokemonList = [];
const apiUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=200';
//Pagination
var list = new Array();
var pageList = new Array();
var currentPage = 1;
var itemPerPage = 20;
var numberOfPages = 0;
function makeList() {
for (let x = 0; x < 200; x++)
list.push(x);
numberOfPages = getNumberOfPages();
}
function getNumberOfPages() {
return Math.ceil(list.length / itemPerPage);
}
function nextPage() {
currentPage += 1;
loadTheList();
}
function previousPage() {
currentPage -= 1;
loadTheList();
}
function firstPage() {
currentPage = 1;
loadTheList();
}
function lastPage() {
currentPage = numberOfPages;
loadTheList();
}
function loadTheList() {
var begin = ((currentPage - 1) * itemPerPage);
var end = begin + itemPerPage;
pageList = list.slice(begin, end);
drawList(); //draws out our data
check(); //determines the state of the pagination button
}
function drawList() {
document.getElementById('pokemon-list').innerHTML = '';
for (let r = 0; r < pageList.length; r++) {
document.getElementById('pokemon-list').innerHTML += pageList[r] + '';
}
}
function check() {
document.getElementById("next").disabled = currentPage == numberOfPages ? true : false;
document.getElementById("previous").disabled = currentPage == 1 ? true : false;
document.getElementById("first").disabled = currentPage == 1 ? true : false;
document.getElementById("last").disabled = currentPage == numberOfPages ? true : false;
}
function load() {
makeList();
loadTheList();
}
//pagination end
return {
...
};
})();
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<div id="loading"><h1>Loading...</h1></div>
<h1 class="main-title">Pokédex</h1>
<ul class="pokemon-list" id="pokemon-list">
</ul>
<!-- buttons for pagination-->
<button id="first" onClick="firstPage()">first</button>
<button id="previous" onClick="previousPage()">previous</button>
<button id="next" onClick="nextPage()">next</button>
<button id="last" onClick="lastPage()">last</button>
<script src="js/promise-polyfill.js"></script>
<script src="js/fetch-polyfill.js"></script>
<script src="js/scripts.js"></script>
</body>
</html>

Related

javascript random gen nr + loops

I'm trying to make an program where it randomly picks 10 questions out of X questions(got 14 random ones written at the moment) without it picking the same questions again but i've been stuck for 4 hours on this junk.
My problem is with "randomNumbers()" function. This function generates random number (which marks the question respectively) and then checks if the numberArray already has generated number. If it doesnt, the number is supposed to be pushed to array.
I think I figured out the problem to be ## VERSION 1 ## for-loops if/else conditions. Any help ? :(
//edit, is while (true) correct way to handle this?
// dont mind ##VERSION 2## it was the first way I tried solving the problem.
(a lot of console logs to determine the bug :P )
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title>Testimiskeskkond</title>
<!--<link rel="stylesheet" type="text/css" href="style.css"/> -->
<script src="scripts/jquery-2.1.4.min.js"></script>
<script src="scripts/js.js"></script>
</head>
<body>
<button onclick="startQuiz()">Alusta testimist</button>
<div id="question1"></div>
<div id=questions></div>
</body>
JAVASCRIPT
var amountOfQuestions = 11;
var questionCounter = 0;
var numberArray = new Array();
var questions = new Array();
questions[0] = 'Mitu kassi elab P2rnus?',
questions[1] = 'Mis on kassi nimi?',
questions[2] = 'Mida kass teeb?',
questions[3] = 'Millal kass syndis?',
questions[4] = 'Mitu hammast kassil on?',
questions[5] = 'Mitu kyynt on kassil?',
questions[6] = 'Mitu k6rva on kassil?',
questions[7] = 'Mis v2rvi on kass?',
questions[8] = 'Tooli v2rvus?',
questions[9] = 'Laua suurus?',
questions[10] = 'Lemmik jook?',
questions[11] = 'Lemmik s88k?',
questions[12] = 'Raamatupoe nimi?',
questions[13] = 'Viinapoe nimi?';
function startQuiz() {
var setQuestions = "";
while (questionCounter < amountOfQuestions) {
var random = randomNumbers();
console.log(random + "appppppi");
if (questionCounter < amountOfQuestions) {
setQuestions += questions[random] + "<br>";
questionCounter += 1;
} else {
setQuestions += questions[random];
questionCounter += 1;
}
}
$('#questions').html(setQuestions);
}
function randomNumbers() {
var arrLength = numberArray.length;
while (true) {
console.log(arrLength);
var randomNr = Math.floor(Math.random() * 14);
console.log(randomNr + " tereeeeeeeeee");
/*
######################
########### VERSION 1
######################*/
if (arrLength == 0) {
console.log("pppppppppppp");
numberArray.push(randomNr);
break;
} else if (arrLength == 1) {
console.log("oooooooooooo");
if (numberArray[0] == randomNr) {
console.log("xxxxxxxxxxxxx");
break;
} else {
console.log("rrrrrrrrrrrrrrr");
numberArray.push(randomNr);
break;
}
} else {
for (var i = 0; i < arrLength-1; i++) {
console.log("yyyyyyyyyyyyyyyyyyyy");
if (numberArray[i] == randomNr) {
console.log("qqqqqqqqqqqqqqqqqqqq");
continue;
} else {
console.log("zzzzzzzzzzzzzz")
numberArray.push(randomNr);
break;
}
}
}
/*
######################
########### VERSION 2
######################
if (arrLength > 0) {
console.log("oooooooooooo");
for (var i = 0; i < arrLength; i++) {
console.log("yyyyyyyyyyyyyyyyyyyy");
if (numberArray[i] == randomNr) {
console.log("qqqqqqqqqqqqqqqqqqqq");
continue;
} else {
console.log("zzzzzzzzzzzzzz")
numberArray.push(randomNr);
break;
}
}
} else {
console.log("pppppppppppp");
numberArray.push(randomNr);
break;
} */
}
return randomNr;
}
let selectionCount = 10;
let randomQuestions = [];
while(randomQuestions.length < selectionCount) {
let randomNr = Math.floor(Math.random() * questionList.length);
if(!randomQuestions.includes(randomNr)) {
randomQuestions.push(randomNbr);
}
}

Error code JS with my function Game Over

I am making a game and I encounter a problem.
When I click on the hammer, the game must show a "Game Over".
However, when a hammer appear, that I don't click on the case where it was and later I click again on this same case, "Game Over" is still displayed.
var temps = 50;
var compte = temps;
var pointCounter=0;
//ONLY SELECTOR FOR DOM
var $contener = document.querySelector(".contener");
var $bestscore = document.querySelector("#bestscore");
var $compt = document.querySelector("#compt");
var $score = document.querySelector("#score");
var $button = document.querySelector('.resetBouton');
for( var i = 0; i <= 8; i++){
$contener.innerHTML += "<div class='case case" + i + "'></div>";
}
if(localStorage.getItem('score')){
$bestscore.textContent = 'Score : ' + localStorage.getItem('score');
}
else{
localStorage.setItem('score', 0);
$bestscore.textContent = 'Score : 0';
}
function decompte(){
if(compte <= 1) {
pluriel = "";
} else {
pluriel = "s";
}
$compt.innerHTML = compte + " seconde" + pluriel;
if(!compte || compte < 0) {
reset();
if(pointCounter > localStorage.getItem('score')){
localStorage.setItem('score', pointCounter);
$bestscore.textContent = 'Score : ' + pointCounter;
}
}
//decrease 1 point
compte--;
}
let timer = setInterval(decompte,1000);
let taupe = setInterval(randomPosition,1000);
//RANDOM POSITION
function randomPosition() {
var $cases = document.querySelectorAll('.case');
// cannot click 2 times
for (var i =0; i< $cases.length; i++){
$cases[i].removeEventListener('click', losePoints);
$cases[i].removeEventListener('click', earnPoints);
$cases[i].innerHTML = '';
}
var x = Math.floor(Math.random() * 9);
var min = 1;
var max = 7;
var nbrRandom = min + Math.floor(Math.random() * max);
if (nbrRandom === 2) {
$cases[x].innerHTML = '<div id="darktaupe"><img src="images/darkTaupiqueur.png" alt="darktopiqueur"/></div>';
$cases[x].addEventListener('click', losePoints);
} else if(nbrRandom ===6) {
$cases[x].innerHTML = '<div id="darktaupe"><img src="images/Marteau_TFH.png" alt="marteau"/></div>';
$cases[x].addEventListener('click', gameOver);
}
else
{
$cases[x].innerHTML = '<div id="taupe"><img src="images/Taupiqueur.png" alt="t opiqueur"/></div>';
$cases[x].addEventListener('click', earnPoints);
}
}
function losePoints(event){
/* JouerSon(); */
pointCounter -=10;
if(pointCounter <0){
pointCounter =0
}
$score.textContent = pointCounter;
event.currentTarget.removeEventListener('click', losePoints);
}
function earnPoints(event){
/* JouerSon(); */
pointCounter ++;
$score.textContent = pointCounter;
event.currentTarget.removeEventListener('click', earnPoints);
}
/*function JouerSon() {
var sound = document.getElementById("beep");
sound.play();
} */
// RESET BUTTON
function reset(){
$button.classList.remove("reset");
$button.addEventListener('click', resetGame);
clearInterval(timer);
clearInterval(taupe);
}
function resetGame(){
pointCounter = 0;
compte = temps;
$score.textContent = pointCounter;
timer = setInterval(decompte,1000);
taupe = setInterval(randomPosition,1000);
$button.removeEventListener('click', resetGame);
$button.classList.add('reset');
}
function gameOver(event){
event.currentTarget.removeEventListener('click', gameOver);
alert("GAME OVER");
reset();
}
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles/style.css">
<meta charset="utf-8"/>
</head>
<body>
<span id="compt"></span>
<span id="score">Score : </span> <span id="bestscore"></span>
<div class="contener"></div>
<button class="resetBouton reset"> reset </button>
<button class="resetBouton jouer"> Jouer </button>
<audio id="beep" src="test1.wav">
<script type='text/javascript' src="script/main.js"></script>
</body>
</html>
From a quick examination of your game, it looks like you are calling randomPosition every second, selecting a random element and then attaching one of three event handlers to it.
It looks like you are removing your losePoints and earnPoints handlers on each call to randomPosition, but never removing gameOver.

Paginition refresh issue in AngularJS

I am showing items using pagination in AngularJS.
For example, I have 12 items and number of items per page is 5. So I have 3 pages to show with the first two pages have 5 items each and the last page has two items.
When I switch pages, say from page-1 to page-2, all 10 items from both page-1 and page-2 are displayed together for a while first before the page-2 items are displayed.
Same thing happened from page-2 to page-3, all 7 items from both page-2 and page-3 are displayed together for a while first before the page-3 items are displayed.
Whenever I switch pages, the same thing is observed.
What could be wrong?
My code is as follow.
html
<div class="adds-wrapper">
<div ng-show="Available">
<div class="item-list" ng-repeat="hotel in pagedItems[currentPage]">
<!-- this is how items are displayed -->
</div>
<div class="pagination-bar">
<ul class="pagination">
<li ng-class="{disabled: currentPage == 0}">
<a class="pagination-btn" href ng-click="prevPage()">« Prev</a></li>
<li ng-repeat="n in range(pagedItems.length)" ng-class="{active: n == currentPage}" ng-click="setPage()">
<a href ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: currentPage == pagedItems.length - 1}">
<a class="pagination-btn" href ng-click="nextPage()">Next »</a></li>
</ul>
</div>
Javascript
function groupToPages() {
$scope.pagedItems = [];
for (var i = 0; i < $scope.filteredItems.length; i++) {
var j = Math.floor(i / $scope.itemsPerPage);
if (i % $scope.itemsPerPage === 0) {
$scope.pagedItems[j] = [$scope.filteredItems[i]];
} else {
$scope.pagedItems[j].push($scope.filteredItems[i]);
}
}
};
var loadPagination = function () {
$scope.sortingOrder = $scope.sortingOrder;
$scope.reverse = false;
$scope.filteredItems = [];
$scope.groupedItems = [];
$scope.itemsPerPage = 5;
$scope.pagedItems = [];
$scope.currentPage = 0;
$scope.items = $scope.HotelAndResorts;
$scope.filteredItems = $scope.HotelAndResorts;
$scope.hotelAvailable = true;
if ($scope.HotelAndResorts) {
if ($scope.HotelAndResorts.length == 0) {
$scope.hotelAvailable = false;
$scope.errorMessage = "No Post Found.";
}
} else {
$scope.hotelAvailable = false;
$scope.errorMessage = "No Post Found."
}
/*var searchMatch = function (haystack, needle) {
if (!needle) {
return true;
}
return haystack.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
};*/
groupToPages();
$scope.range = function (start, end) {
var ret = [];
if (!end) {
end = start;
start = 0;
}
for (var i = start; i < end; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function () {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.nextPage = function () {
if ($scope.currentPage < $scope.pagedItems.length - 1) {
$scope.currentPage++;
}
};
$scope.setPage = function () {
$scope.currentPage = this.n;
};
$scope.sort_by = function (newSortingOrder) {
if ($scope.sortingOrder == newSortingOrder)
$scope.reverse = !$scope.reverse;
$scope.sortingOrder = newSortingOrder;
// icon setup
$('th i').each(function () {
// icon reset
$(this).removeClass().addClass('icon-sort');
});
if ($scope.reverse)
$('th.' + new_sorting_order + ' i').removeClass().addClass('icon-chevron-up');
else
$('th.' + new_sorting_order + ' i').removeClass().addClass('icon-chevron-down');
};
}
When you paginate after updating the paged items try calling $scope.apply() this tells AngularJS to look fixup various javascript things. Angular does some sorcery under the hood to make Javascript behave asynchronously, apply makes thing sync up. I'm oversimplifying, if you like you can read the exact documentation, but I find when htis kind of thing happens 95% of the time it's because I didn't apply.

function is undefined in firefox only

ok, the following code works ok in IE7+ and Chrome.
but for some reason, xfade is undefined in firefox
<html>
<body>
<div id="slider"></div>
<script type="text/javascript">
var Klimateka = {
Slider: function () {
// Check if we have a slider div on page
var slider = document.getElementById('slider');
if (slider != null) {
var images = ["slide-image-1.jpg", "slide-image-2.jpg", "slide-image-3.jpg", "slide-image-4.jpg"];
var i = images.length;
while (i) {
i -= 1;
var img = document.createElement("img");
img.src = "images/" + images[i];
slider.appendChild(img);
}
var d = document, imgs = new Array(), zInterval = null, current = 0, pause = false;
imgs = d.getElementById("slider").getElementsByTagName("img");
for (i = 1; i < imgs.length; i++) imgs[i].xOpacity = 0;
imgs[0].style.display = "block";
imgs[0].xOpacity = .99;
setTimeout("xfade()", 3500);
function xfade() {
cOpacity = imgs[current].xOpacity;
nIndex = imgs[current + 1] ? current + 1 : 0;
nOpacity = imgs[nIndex].xOpacity;
cOpacity -= .05;
nOpacity += .05;
imgs[nIndex].style.display = "block";
imgs[current].xOpacity = cOpacity;
imgs[nIndex].xOpacity = nOpacity;
setOpacity(imgs[current]);
setOpacity(imgs[nIndex]);
if (cOpacity <= 0) {
imgs[current].style.display = "none";
current = nIndex;
setTimeout(xfade, 3500);
} else {
setTimeout(xfade, 50);
}
function setOpacity(obj) {
if (obj.xOpacity > .99) {
obj.xOpacity = .99;
return;
}
obj.style.opacity = obj.xOpacity;
obj.style.MozOpacity = obj.xOpacity;
obj.style.filter = "alpha(opacity=" + (obj.xOpacity * 100) + ")";
}
}
}
},
bar: function () {
}
};
Klimateka.Slider();
i have setup a jsfiddler for testing:
http://jsfiddle.net/rTtKh/10/
This might only apply to Firefox:
functions do not hoist when declared inside a child block.
You declare xfade inside the if block, but you are calling it prior to the declaration:
setTimeout(xfade, 3500);
Put the function declaration on top.
You have to do the same with setOpacity inside xfade. <- That is not necessary.
Fix your line that says this: setTimeout("xfade()", 3500); to match your others:
setTimeout(xfade, 3500);
Use setTimeout(xfade, 3500) instead.

javascript array cycling only first var

I am using javascript to cycle through an array of urls within an iframe and so far when the prev or next buttons are pressed it jumps to the first var in the array and both prev and next functions end. Any ideas?
<iframe id="myFrame" src="http://startpage.com" width="484px" height = "424px"></iframe>
<button onclick = "prevPage(); ">Prev</button>
<button onclick = "nextPage(); ">Next</button>
<script>
var sites=new Array();
sites[0]="http://site1.html";
sites[1]="http://site2.html";
sites[2]="http://site3.html";
sites[3]="http://site4.html";
function nextPage() {
var number = document.getElementById("myFrame").src;
number = number.substring(number.length - 4 ,number.length-3);
number = parseInt(number) + 1;
document.getElementById("myFrame").src=sites[0];
}
function prevPage() {
var number = document.getElementById("myFrame").src;
number = number.substring(number.length - 3 ,number.length-4);
number = parseInt(number) - 1;
document.getElementById("myFrame").src=sites[0];
}
</script>
Why are you using the URL as your 'position' storage? It'd be FAR easier to just use a variable:
var curPos = 0;
function nextPage() {
curPos++;
if (curPos >= sites.length) {
curPos = 0;
}
document.getElementById('myframe').src = sites[curPos];
}
function prevPage() {
curPos--;
if (curPos < 0) {
curPos = sites.length - 1;
}
document.getElementById('myframe'.).src = sites[curPos];
}
If I understood your problem correctly I think all you need to do is use document.getElementById("myFrame").src=sites[number]; instead of document.getElementById("myFrame").src=sites[0];
May be
document.getElementById("myFrame").src=sites[number-1];
is what you are trying to do in both functions.

Categories