Paging next button jumping by page number * 6 - javascript

I'm having a problem with my pagination. it seems to take the number of the page I am on and multiplies it by 6 when clicking the "next array" arrow function IE: "clicking on the second page then the next arrow function it jumps to page 13-18 instead of jumping to page 7-12.
next buttons, first array
second array clicking arrow buttons after click on page two jumps to the wrong section
This is the code that creates the pagination.
CreatePages() {
this.pages = [];
console.log({'this.iteration':this.iteration,'this.iteration * 6 - 6':this.iteration * 6 - 6,'this.iteration * 6':this.iteration * 6,'this.allPages':this.allPages})
for (var i = this.iteration * 6 - 6; i < this.iteration * 6 && i < this.allPages; i++) //populate the pages array
{
console.log({'this.iteration':this.iteration,'(this.iteration - 1) * 6':(this.iteration - 1) * 6})
if (i == (this.iteration - 1) ) {
this.pages.push({ id: i + 1, current: true });
}
else
this.pages.push({ id: i + 1, current: false });
}
console.log({pages:this.pages})
}
age(id: number) {
this.pages.forEach(function (p) {
if (p.id != id)
p.current = false;
else
p.current = true;
})
this.iteration =id;
this.postSearch(this.query,this.iteration,this.pagesize,this.categories)
}
PagingPrev() {
this.iteration--;
if (this.iteration <= 0) {
this.iteration = 1;
}
else
this.CreatePages();
this.Page(this.iteration)
}
PagingNext() {
this.iteration++;
if (this.iteration > Math.ceil(this.allPages / 1)) {
this.iteration = Math.ceil(this.allPages / 6);
}
else{
this.CreatePages();
}
console.log({"mattspages":this.iteration})
this.Page(this.iteration)
}

Related

JS random order showing divs delay issue

I got function within JS which is supposed to show random order divs on btn click.
However once the btn is clicked user got to wait for initial 10 seconds ( which is set by: setInterval(showQuotes, 10000) ) for divs to start showing in random order which is not ideal for me.
JS:
var todo = null;
var div_number;
var used_numbers;
function showrandomdivsevery10seconds() {
div_number = 1;
used_numbers = new Array();
if (todo == null) {
todo = setInterval(showQuotes, 10000);
$('#stop-showing-divs').css("display", "block");
}
}
function showQuotes() {
used_numbers.splice(0, used_numbers.length);
$('.container').hide();
for (var inc = 0; inc < div_number; inc++) {
var random = get_random_number();
$('.container:eq(' + random + ')').show();
}
$('.container').delay(9500).fadeOut(2000);
}
function get_random_number() {
var number = randomFromTo(0, 100);
if ($.inArray(number, used_numbers) != -1) {
return get_random_number();
} else {
used_numbers.push(number);
return number;
}
}
function randomFromTo(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
Question: How to alter the code so upon the btn click divs will start showing right away without initial waiting for 10 seconds? (take in mind I want to keep any further delay of 10 seconds in between of each div being shown)
Thank you.
Call it when you begin the interval
todo = setInterval((showQuotes(),showQuotes), 10000);

Quick sort, maximum stack call in Javascript

What is wrong with my algorithm. Is it a limitation of hardware, I am on an old computer, or is my code that is not right? The algorithm worked fined for a vector wit 3.5 thousands objects. Now I am getting maximum call stack error when using a 85 thousand object vector. I tried to find the error but I couldn't find it.
import { gastos } from './cota-parlamentar-282-mil.mjs';
function quickSort2(vetor, listaPropriedadesOrdenacao) {
quickSort(vetor, listaPropriedadesOrdenacao[0]);
}
function quickSort(vetor, propriedadeOrdenacao, ini = 0, fim = vetor.length - 1) {
if (fim > ini) {
const pivot = fim;
let div = ini - 1;
for (let i = ini; i < fim; i++) {
//I order the array based on the property specified
if (vetor[i][propriedadeOrdenacao] < vetor[pivot][propriedadeOrdenacao]) {
div++
if (i !== div) {
[vetor[i], vetor[div]] = [vetor[div], vetor[i]]
}
}
}
div++
if (vetor[pivot][propriedadeOrdenacao] < vetor[div][propriedadeOrdenacao]) {
[vetor[pivot], vetor[div]] = [vetor[div], vetor[pivot]]
}
quickSort(vetor, propriedadeOrdenacao, ini, div - 1)
//I am getting the error with the line below
quickSort(vetor, propriedadeOrdenacao, div + 1, fim)
}
}
quickSort2(gastos, ['partido', 'nome_parlamentar', 'id_documento']);
Excuse me for the naming covention and stuff I am just prototyping.
There's not enough code in the question to test, but try these changes:
quickSort(vetor, listaPropriedadesOrdenacao[0], 0, vetor.length - 1);
...
function quickSort(vetor, propriedadeOrdenacao, ini, fim) {
while (fim > ini) {
...
if((div - ini) < (fim - div)){
quickSort(vetor, propriedadeOrdenacao, ini, div - 1)
ini = div + 1
} else {
quickSort(vetor, propriedadeOrdenacao, div + 1, fim)
fim = div - 1
}

Vertical scrolling in div animation by changing css top

I'm trying to set up horizontal slider. I have div with overflow: hidden and inside I have 16 divs with height of 60px. Parent div has height so you can see only 4 childs at the time.
Now I want to change childs top: css to make them slide up and 4 new come from bottom.
Here's what I've done so far
lastAddedService.getLastAdded()
.then(function (response) {
$scope.lastAddedElements = response.data;
var i = 0, g = 0, c = 0, p = 0;
var k = 1, b = 1, h = 1;
var slider = {
step: 1,
positionTop: 0,
init: function (step) {
var that = this;
el[0].querySelectorAll('.a').forEach(function (element) {
if(step === 1) {
if(i < 16) {
that.positionTop = i * 60;
i++;
return angular.element(element).css('top', that.positionTop);
}
}
if(step === 2) {
if(i < 4) {
that.positionTop = k * 60 * -1;
i++; k++;
return angular.element(element).css('top', that.positionTop);
}
if(i >= 4) {
k = 0;
that.positionTop = g * 60;
i++; g++;
return angular.element(element).css('top', that.positionTop);
}
}
if(step === 3) {
if(i < 8) {
that.positionTop = b * 60 * -1;
i++; b++;
return angular.element(element).css('top', that.positionTop);
}
if(i >= 8) {
that.positionTop = c * 60;
i++; c++;
return angular.element(element).css('top', that.positionTop);
}
}
if(step === 4) {
if(i < 12) {
that.positionTop = h * 60 * -1;
i++; h++;
return angular.element(element).css('top', that.positionTop);
}
if(i >= 12) {
that.positionTop = p * 60;
i++; p++;
return angular.element(element).css('top', that.positionTop);
}
}
});
},
changeSlide: function (step) {
this.step = step;
this.init(this.step);
}
};
$timeout(function () {
slider.changeSlide(1);
});
setTimeout(function () {
setInterval(function () {
var q = 1;
q++;
slider.changeSlide(q);
if(q === 4) {
q = 1;
}
}, 5000);
}, 5000);
}, function (err) {
console.log('error getting last added');
});
}
So I'm gathering records from backend and then there is this slider object which has logic which I explained above.
Backend call works fine, I did console response and it's 16 records which I display in layout layer later on. Question is mainly about the logic for this sliding object.
I'm using $timeout to start code work because this code is indeed in angularJS directive and NodeList which I get by querySelectorAll would be empty otherwise because it's evaluated after async backend call finish and then DOM is fully loaded. But it's not really relevant to real logic of this script, it's just additional info.
This code looks very bad to me. How I can improve it?
It's starting to update top after around 20 seconds and 1 div has 960px I don't know why.
It's not reseting this variables values so it doesn't loop but it increase top further and further.
I add HTML from my directive if anyone want to reproduce issue
<div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
<div class="row u-no-margin">
<div class="col-lg-11 col-xs-11">
<h2 class="main__heading">
Ostatnio dodane
</h2>
<div class="main__last-added-field">
<div class="main__last-added a" data-ng-repeat="n in lastAddedElements">
<div class="row u-no-margin main__last-added-container">
<div class="col-lg-3 col-md-2 col-sm-2 col-xs-2">
<h4 class="main__last-added-heading">
{{ n.data.attributes.price }}
</h4>
</div>
<div class="col-lg-7 col-xs-8 u-no-padding">
<h4 class="main__last-added-heading u-no-padding">
{{ n.data.attributes.name }}
</h4>
</div>
<div class="col-lg-2 col-xs-2">
<button type="button" class="btn btn__primary">
Zobacz
</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-1 col-xs-1">
<div class="main__last-added-dot-container">
<span class="main__last-added-dot main__last-added-dot--active"></span>
<span class="main__last-added-dot"></span>
<span class="main__last-added-dot"></span>
<span class="main__last-added-dot"></span>
</div>
</div>
</div>
</div>
JS code is within directive link: function and the templateUrl is above HTML code.
** EDIT **
I update question I add plunker showing issue and I explain one more, step by step what I want to accomplish.
Step1: all element has top: x css so they are align vertically. I'm using overflow: hidden on parent so you see only 4 and 12 are hidden below like this
Step2 I move first 4 element to top: -x so you don't see first 4 and element 5,6,7,8 take their place so elements 5,6,7,8 now slide to the top and first 4 are hidden.
step 3 same as Step2: elements 5,6,7,8 move to negative top and you now see elements 9,10,11,12
step 4 same as Step3: elements 9,10,11,12 move to negative top and you now see elements 13,14,15,16
here's demo
I don't know why but in plunker it doesn't udpate css top of elements at all.
First of all I recommend that you use a bootstrap only solution for your html/css view because its responsive, tested and you will have cleaner code.
I have made some modification to your slider logic in a way that the logic is the as if your slider were a pagination directive.
Basically, you divide your data into pages and then you keep track of the current page to be displayed on the view.
In your elements directive you use two filters on the data (startFrom, limitTo). The 'limitTo' is a built-in filter in Angular and 'startFrom' is a custom filter that you have to create.
<div class="" data-ng-repeat="n in elements | startFrom:currentPage*pageSize | limitTo:pageSize">
This is just an ideia that might help you refactor you code such that you won't need css positioning to determine which items will be displayed. Here is my demo:
https://plnkr.co/edit/IROsQWr5z4oYgZzmR2GF?p=preview
I hope this helps!
I've done it with this code:
<div class="main__last-added a"
data-ng-repeat="n in lastAddedElements"
data-order="{{ $index+1 }}">
(function () {
'use strict';
angular
.module('igt')
.directive('lastAdded', Directive);
Directive.$inject = ['$timeout', 'lastAddedService'];
function Directive($timeout, lastAddedService) {
return {
restrict: 'E',
scope: {
destiny: '='
},
templateUrl: 'html/directives/lastAdded.html',
link: function ($scope, el) {
lastAddedService.getLastAdded()
.then(function (response) {
$scope.lastAddedElements = response.data;
$scope.slider = {
increment: 0,
step: 1,
positionTop: 0,
init: function (step) {
var that = this;
var elements = el[0].querySelectorAll('.a');
if(step === 1) {
console.log('run step 1 ..............');
this.step = 1;
elements.forEach(function (e) {
var order = angular.element(e).attr('data-order');
if(order <= 16) {
that.positionTop = order * 60 - 60;
return angular.element(e).css('top', that.positionTop);
}
});
}
if(step === 2) {
console.log('run step 2 ..............');
this.step = 2;
elements.forEach(function (e) {
var order = angular.element(e).attr('data-order');
if (order <= 4) {
that.positionTop = order * 60 * -1;
return angular.element(e).css('top', that.positionTop);
}
if (order > 4) {
that.positionTop = that.increment * 60;
that.increment++;
console.log(that.increment);
if (that.increment === 12) {
that.increment = 0;
console.log('reset inc in step 2');
}
return angular.element(e).css('top', that.positionTop);
}
});
}
if(step === 3) {
console.log('run step 3 ..............');
this.step = 3;
elements.forEach(function (e) {
var order = angular.element(e).attr('data-order');
if (order <= 8) {
that.positionTop = order * 60 * -1;
return angular.element(e).css('top', that.positionTop);
}
if (order > 8) {
that.positionTop = that.increment * 60;
that.increment++;
console.log(that.increment);
if (that.increment === 8) {
that.increment = 0;
console.log('reset inc in step 3');
}
return angular.element(e).css('top', that.positionTop);
}
});
}
if(step === 4) {
console.log('run step 4 ..............');
this.step = 4;
elements.forEach(function (e) {
var order = angular.element(e).attr('data-order');
if (order <= 12) {
that.positionTop = order * 60 * -1;
return angular.element(e).css('top', that.positionTop);
}
if (order > 12) {
that.positionTop = that.increment * 60;
that.increment++;
console.log(that.increment);
if (that.increment === 4) {
that.increment = 0;
console.log('reset inc in step 4');
}
return angular.element(e).css('top', that.positionTop);
}
});
}
},
changeSlide: function (step) {
this.step = step;
this.init(this.step);
}
};
$timeout(function () {
var i = 1;
$scope.slider.changeSlide(i);
setInterval(function () {
i++; if(i === 5) i = 1;
$scope.slider.changeSlide(i);
}, 5000);
});
}, function (err) {
console.log('error getting last added: ' + err);
});
}
}
}
})();
But this code still look very lame although it's a bit better than first version. I feel like it can be done in much much simplier way.

How to "echo" or show pictures from Javascript

I'm trying to use the below code to reflect different pictures of the moon into an HTML doc. Of course i've added the Jquery and Javascript tags.
I've been looking at this for hours and trying different things but I can't find out what to put into HTML code that will actually show or echo the pictures.
What should I put into the "moonImage.src = "pix/moon" + truncPhase + ".png";" part of the code? I don't understand how to essentially echo the photos. Help please?:
// Image max size
var IMAGE_MAX_SIZE = 196;
// Records whether or not the gadget is expanded
var poppedOut = false;
function onOpen() {
// Check once every 30 minutes
view.setInterval(onTimer, 30 * 60 * 1000);
// Initialize the gadget
onTimer();
}
// Called when the timer goes off
function onTimer() {
// Compute the moon phase each time timer is called
var cal = new Date();
// Base the computation off of UTC time, to the nearest hour
var phase = computeMoonPhase(cal.getUTCFullYear(),
cal.getUTCMonth() + 1,
cal.getUTCDate(),
cal.getUTCHours());
var truncPhase = Math.floor(phase) % 30;
// Find the text description of the current phase
var desc;
if (truncPhase === 0) {
desc = STRING_MOON_DESC_NEW;
} else if (truncPhase == 7) {
desc = STRING_MOON_DESC_FIRST_QUARTER;
} else if (truncPhase == 15) {
desc = STRING_MOON_DESC_FULL;
} else if (truncPhase == 23) {
desc = STRING_MOON_DESC_THIRD_QUARTER;
} else if (truncPhase > 0 && phase < 7) {
desc = STRING_MOON_DESC_WAXING_CRESCENT;
} else if (truncPhase > 7 && phase < 15) {
desc = STRING_MOON_DESC_WAXING_GIBBOUS;
} else if (truncPhase > 15 && phase < 23) {
desc = STRING_MOON_DESC_WANING_GIBBOUS;
} else {
desc = STRING_MOON_DESC_WANING_CRESCENT;
}
// Set the image and text component appropriately
moonImage.src = "pix/moon" + truncPhase + ".png";
moonImage.tooltip = (Math.floor(phase * 100) / 100) + " " + STRING_DAYS_OLD;
phaseAge.innerText = STRING_MOON_AGE_PREFIX + " " + moonImage.tooltip +
"\n" +
desc;
}
// Called when view is resized (recompute constituent basicElement sizes and
// locations)
function resizeView() {
setDimensions(event.width, event.height);
}
// Open the browser whenever a user double clicks (expanded or collapsed)
function onDblClick() {
var obj = new ActiveXObject("Shell.Application");
obj.Open("http://stardate.org/nightsky/moon/");
}
// Show date age in title, when gadget is minimized
function onMinimize() {
view.caption = STRING_MOON_SHORT + " - " + moonImage.tooltip;
}
// Only show the textual part (details) when popped out
function onPopout() {
poppedOut = true;
phaseAge.visible = true;
}
// Hide the textual part in restored mode, show regular title, and reset
// dimensions
function onRestore() {
view.caption = GADGET_NAME;
phaseAge.visible = false;
//moonImage.enabled = true;
poppedOut = false;
setDimensions(view.width, view.height);
}
// Called whenever the sizes and/or locations of basicElements need to change
function setDimensions(width, height) {
// Image is square, constrained by smallest dimension
var sz = Math.min(width, height);
// Make the image almost as large as the sz
moonImage.width = Math.min(IMAGE_MAX_SIZE, sz * 0.9);
moonImage.height = Math.min(IMAGE_MAX_SIZE, sz * 0.9);
if (poppedOut) {
// Align image on left, and set text location
moonImage.x = 0;
phaseAge.x = moonImage.width + 5;
phaseAge.y = (height - phaseAge.height) / 2;
} else {
// Center image horizontally
moonImage.x = (width - moonImage.width) * 0.5;
}
// Always center image vertically
moonImage.y = (height - moonImage.height) * 0.5;
}
// Compute the moon phase.
// Code is based upon Bradley E. Schaefer''s well-known moon phase algorithm.
function computeMoonPhase(year, month, day, hours) {
var MOON_PHASE_LENGTH = 29.530588853;
// Convert the year into the format expected by the algorithm
var transformedYear = year - Math.floor((12 - month) / 10);
// Convert the month into the format expected by the algorithm
var transformedMonth = month + 9;
if (transformedMonth >= 12) {
transformedMonth = transformedMonth - 12;
}
// Logic to compute moon phase as a fraction between 0 and 1
var term1 = Math.floor(365.25 * (transformedYear + 4712));
var term2 = Math.floor(30.6 * transformedMonth + 0.5);
var term3 = Math.floor(Math.floor((transformedYear / 100) + 49) * 0.75) - 38;
var intermediate = term1 + term2 + (day + (hours - 1) / 24) + 59;
if (intermediate > 2299160) {
intermediate = intermediate - term3;
}
var normalizedPhase = (intermediate - 2451550.1) / MOON_PHASE_LENGTH;
normalizedPhase = normalizedPhase - Math.floor(normalizedPhase);
if (normalizedPhase < 0) {
normalizedPhase = normalizedPhase + 1;
}
// Return the result as a value between 0 and MOON_PHASE_LENGTH
return normalizedPhase * MOON_PHASE_LENGTH;
}
HTML:
<html>
<head><title>Kendrick Moon</title>
<script src="ajax.googleapis.com/ajax/libs/jquery/1.8.3/ (etc.)
<script src="code.jquery.com/ui/1.9.2/jquery-ui.js"></script>;
<script src="main.js" type="text/javascript"></script>
<head>
<body>
<div><img src=""/> </div>
</body>
</html>
ok, well thats then easy.
first of all, you might want to check out jquery. with jquery it would be something like this.
<img src="" id="my_image" />
in javascript then (with jquery)
// the `myLinkToImage` is hopefully the variable of your path
$("#my_image").attr("src", myLinkToImage);
as you can see I´m using #. That is a typical jQuery Selector. You might check out more of them here
in javascript without jquery
document.getElementById("my_image").src = myLinkToImage;

Javascript: Make a static code, dynamic - List of inputs

I have this code, that checks some ids and enable others, the javascript is pretty clear about what it does, but since it corresponds to some specific id ranges, I cant do just a look until it finishes, but I'm looking a way to do this dynamic and save 40 lines of code (or more), since its not the best way.
function loopGroup1() {
var a = 0;
do {
$$('.selectedAuthorities-3_' + a).each(function(chk1) {
// watch for clicks
chk1.observe('click', function(evt) {
dynamicCheckbox1();
});
dynamicCheckbox1();
});
a++;
} while (a < 4);
}
function dynamicCheckbox1() {
// count how many of group_first are checked,
// doEnable true if any are checked
var doEnable = ($$('.selectedAuthorities-3_0:checked').length > 0) ? true
: false;
var doEnable1 = ($$('.selectedAuthorities-3_1:checked').length > 0) ? true
: false;
var doEnable2 = ($$('.selectedAuthorities-3_2:checked').length > 0) ? true
: false;
// for each in group_second, enable the checkbox, and
// remove the cssDisabled class from the parent label
var i = 0;
do {
$$('.selectedAuthorities-4_' + i).each(function(item) {
if (doEnable || doEnable1 || doEnable2) {
item.enable().up('li').removeClassName('cssDisabled');
} else {
item.disable().up('li').addClassName('cssDisabled');
}
});
i++;
} while (i < 4);
};
/*
*
* Loop Group 2
*
*
*/
function loopGroup2() {
var a = 0;
do {
$$('.selectedAuthorities-5_' + a).each(function(chk1) {
// watch for clicks
chk1.observe('click', function(evt) {
dynamicCheckbox2();
});
dynamicCheckbox2();
});
a++;
} while (a < 4);
}
function dynamicCheckbox2() {
// count how many of group_first are checked,
// doEnable true if any are checked
var doEnable3 = ($$('.selectedAuthorities-5_0:checked').length > 0) ? true
: false;
// for each in group_second, enable the checkbox, and
// remove the cssDisabled class from the parent label
var i = 0;
do {
$$('.selectedAuthorities-6_' + i).each(function(item) {
if (doEnable3) {
item.enable().up('li').removeClassName('cssDisabled');
} else {
item.disable().up('li').addClassName('cssDisabled');
}
});
i++;
} while (i < 4);
};
/*
*
* Loop Group 3
*
*
*/
function loopGroup3() {
var a = 0;
do {
$$('.selectedAuthorities-6_' + a).each(function(chk1) {
// watch for clicks
chk1.observe('click', function(evt) {
dynamicCheckbox3();
});
dynamicCheckbox3();
});
a++;
} while (a < 4);
}
function dynamicCheckbox3() {
// count how many of group_first are checked,
// doEnable true if any are checked
var doEnable4 = ($$('.selectedAuthorities-6_0:checked').length > 0) ? true
: false;
var doEnable5 = ($$('.selectedAuthorities-6_1:checked').length > 0) ? true
: false;
// for each in group_second, enable the checkbox, and
// remove the cssDisabled class from the parent label
var i = 0;
do {
$$('.selectedAuthorities-7_' + i).each(function(item) {
if (doEnable4 || doEnable5) {
item.enable().up('li').removeClassName('cssDisabled');
} else {
item.disable().up('li').addClassName('cssDisabled');
}
});
i++;
} while (i < 4);
};
/*
*
* Loop Group 4
*
*
*/
function loopGroup4() {
var a = 0;
do {
$$('.selectedAuthorities-9_' + a).each(function(chk1) {
// watch for clicks
chk1.observe('click', function(evt) {
dynamicCheckbox4();
});
dynamicCheckbox4();
});
a++;
} while (a < 4);
}
function dynamicCheckbox4() {
// count how many of group_first are checked,
// doEnable true if any are checked
var doEnable6 = ($$('.selectedAuthorities-9_0:checked').length > 0) ? true
: false;
var doEnable7 = ($$('.selectedAuthorities-9_1:checked').length > 0) ? true
: false;
// for each in group_second, enable the checkbox, and
// remove the cssDisabled class from the parent label
var i = 0;
do {
$$('.selectedAuthorities-10_' + i).each(function(item) {
if (doEnable6 || doEnable7) {
item.enable().up('li').removeClassName('cssDisabled');
} else {
item.disable().up('li').addClassName('cssDisabled');
}
});
i++;
} while (i < 4);
};
This isn't an answer, but there's some extra code in here:
var doEnable = ($$('.selectedAuthorities-3_0:checked').length > 0) ? true
: false;
should be
var doEnable = $$('.selectedAuthorities-3_0:checked').length > 0;
The ternary operator is just making it clumsier.

Categories