Limiting The Number of Shown Pages on The Pagination - javascript

I'm trying to make a pagination for my .pdf file gallery.
I'm using a free pagination template I found online. It works fine but the problem is it creates infinite page numbers.
For example, if I have 100 documents and display 4 per page; the pagination goes from 1-20 and shows them all.
I want it to show 3 at a time, not all of them.
I want something like this: "< 1 ... 5 6 7 ... 20 >" (will change of course each time the page changes).
Right now it's like this: "< 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 >"
Can you guys help me out? Thanks.
HTML:
<ul class="tilesWrap" id="paginated-list" data-current-page="1" aria-live="polite">
<li>
<h2>1</h2>
<h3>Ekim 1. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>2</h2>
<h3>Ekim 2. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>3</h2>
<h3>Ekim 3. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>4</h2>
<h3>Ekim 4. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>1</h2>
<h3>Eylül 1. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>2</h2>
<h3>Eylül 2. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>3</h2>
<h3>Eylül 3. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>4</h2>
<h3>Eylül 4. Hafta</h3>
<button>İndir</button>
</li>
</ul>
<nav class="pagination-container">
<button class="pagination-button" id="prev-button" aria-label="Previous page" title="Previous page">
<
</button>
<div class="pagination-numbers" id="pagination-numbers">
</div>
<button class="pagination-button" id="next-button" aria-label="Next page" title="Next page">
>
</button>
</nav>
Java:
<script type="text/javascript">
const paginationNumbers = document.getElementById("pagination-numbers");
const paginatedList = document.getElementById("paginated-list");
const listItems = paginatedList.querySelectorAll("li");
const nextButton = document.getElementById("next-button");
const prevButton = document.getElementById("prev-button");
const paginationLimit = 4;
const pageCount = Math.ceil(listItems.length / paginationLimit);
let currentPage = 1;
const disableButton = (button) => {
button.classList.add("disabled");
button.setAttribute("disabled", true);
};
const enableButton = (button) => {
button.classList.remove("disabled");
button.removeAttribute("disabled");
};
const handlePageButtonsStatus = () => {
if (currentPage === 1) {
disableButton(prevButton);
} else {
enableButton(prevButton);
}
if (pageCount === currentPage) {
disableButton(nextButton);
} else {
enableButton(nextButton);
}
};
const handleActivePageNumber = () => {
document.querySelectorAll(".pagination-number").forEach((button) => {
button.classList.remove("active");
const pageIndex = Number(button.getAttribute("page-index"));
if (pageIndex == currentPage) {
button.classList.add("active");
}
});
};
const appendPageNumber = (index) => {
const pageNumber = document.createElement("button");
pageNumber.className = "pagination-number";
pageNumber.innerHTML = index;
pageNumber.setAttribute("page-index", index);
pageNumber.setAttribute("aria-label", "Page " + index);
paginationNumbers.appendChild(pageNumber);
};
const getPaginationNumbers = () => {
for (let i = 1; i <= pageCount; i++) {
appendPageNumber(i);
}
};
const setCurrentPage = (pageNum) => {
currentPage = pageNum;
handleActivePageNumber();
handlePageButtonsStatus();
const prevRange = (pageNum - 1) * paginationLimit;
const currRange = pageNum * paginationLimit;
listItems.forEach((item, index) => {
item.classList.add("hidden");
if (index >= prevRange && index < currRange) {
item.classList.remove("hidden");
}
});
};
window.addEventListener("load", () => {
getPaginationNumbers();
setCurrentPage(1);
prevButton.addEventListener("click", () => {
setCurrentPage(currentPage - 1);
});
nextButton.addEventListener("click", () => {
setCurrentPage(currentPage + 1);
});
document.querySelectorAll(".pagination-number").forEach((button) => {
const pageIndex = Number(button.getAttribute("page-index"));
if (pageIndex) {
button.addEventListener("click", () => {
setCurrentPage(pageIndex);
});
}
});
});</script>
I am trying to build a pagination that works properly as I want it to.

Please use the following pagination :
$_GET["page"] is the page you want to see
totalpages (now 15) is the total number of pages
offset is the number of pages (1+offset * 2) you want to display before and after the Ellipses (if 1 it means (1+1 * 2) = 3 pages, if 2 it means (1+2 * 2)= 5 pages)
<style>
.pagination {
text-decoration:none;
color:black;
font-family:arial;
font-size:12px;
}
</style>
<script>
var totalpages=15;
var currentpage=<?php echo $_GET["page"]; ?>;
var offset=1;
var offsetnum=(offset*2) +1;
var index=0;
var index0=0;
var starttag="<a class=pagination href='testpage.php?page=";
var endtag="</a>";
if (totalpages >0) {
index0=currentpage-1;
if (index0 <1) { index0=1; }
document.write(starttag+index0+"'>"+"<" + endtag + " ");
if (totalpages <=(offsetnum+2)) {
for (index =1; index <=totalpages; index++) {
if (index !=currentpage){
document.write(starttag+index+"'>"+index + endtag + " ");
}else{
document.write("<B>"+starttag+index+"'>"+index + endtag + "</B> ");
}
}
} else {
if (currentpage<=(1+offset)) {
var startpage=2;
var endpage=2+(offsetnum)-1;
} else {
if (currentpage>=(totalpages-offset)) {
var startpage=(totalpages-1)-(offset*2);
var endpage=(totalpages-1);
} else {
var startpage=currentpage-offset;
var endpage=currentpage+offset;
}
}
if (currentpage!=1){
document.write(starttag+1+"'>1" + endtag + " ");
}else{
document.write("<B>"+starttag+1+"'>1" + endtag+"</B>" + " ");
}
if (startpage>2) document.write(".. ");
for (index =startpage; index <=endpage; index++) {
if (currentpage!=index){
document.write(starttag+index+"'>" + index + endtag + " ");
}else{
document.write("<B>" +starttag+index+"'>" + index + endtag + "</B> ");
}
}
if (endpage < (totalpages-1)) document.write(".. ");
if (currentpage!=totalpages){
document.write(starttag+totalpages+"'>" + totalpages + endtag + " ");
}else{
document.write("<B>"+starttag+totalpages+"'>" + totalpages + endtag + "</B> ");
}
}
index0=currentpage+1;
if (index0 >totalpages) { index0=totalpages; }
document.write(starttag+index0+"'>"+">" + endtag + " ");
}
</script>
Fully working sandbox link:
http://www.createchhk.com/SOanswers/testpage.php?page=10

Related

JS Counter starts on scroll

I ran into a problem with my Counter on website which Im building. I made Counter and it's working perfect, the problem is that it works constantly, not when scrolling to the section where it is located. So I want just make it to start count when it comes section where he is. Hope you guys understand me, and I would be grateful to anyone who wants to help me. Here is my JavaScript code:
var pacijenti = setInterval(pacijenata, 300);
var procenat = setInterval(procenatIzlecenosti, 60);
var klinika = setInterval(klinike, 400);
let count1 = 0;
let count2 = 0;
let count3 = 0;
function pacijenata() {
count1 = count1 += 1000;
document.querySelector("#number1").innerHTML = count1 + "+";
if( count1 === 10000 ) {
clearInterval(pacijenti);
}
}
function procenatIzlecenosti() {
count2++;
document.querySelector("#number2").innerHTML = count2 + "%";
if( count2 === 70 ) {
clearInterval(procenat);
}
}
function klinike() {
count3++;
document.querySelector("#number3").innerHTML = count3;
if( count3 === 4 ) {
clearInterval(klinika);
}
}
<section id="brojac">
<div class="counterContainer">
<ul>
<li>
<i class="fas fa-hospital-user"></i>
<p id="number1" class="number">10000</p>
<p>Pacijenata</p>
</li>
<li>
<i class="fas fa-universal-access"></i>
<p id="number2" class="number">70</p>
<p>Procenat izlečenosti</p>
</li>
<li>
<i class="fas fa-clinic-medical"></i>
<p id="number3" class="number">4</p>
<p>Klinike</p>
</li>
</ul>
</div>
</section>
What you need is a way to start the counter when a certain element comes into view:
You can use this custom code for that (adapted from this answer):
const counterSection = document.getElementById("brojac");
let counterStarted = false;
const counterScrolledIntoView = () => {
const docViewTop = window.scrollTop;
const docViewBottom = docViewTop + window.height();
const counterSectionTop = counterSection.offset().top;
const counterSectionBottom = counterSection + counterSection.height();
return ((counterSectionBottom <= docViewBottom) && (counterSectionTop >= docViewTop));
}
Then you need to attach an event listener for scroll events:
document.addEventListener('scroll', () => {
const counterInView = counterScrolledIntoView();
if (!counterStarted && counterInView) {
// The element just got scrolled into view, (re)start the counter
counterStarted = true;
/*
var pacijenti = setInterval(pacijenata, 300);
var procenat = setInterval(procenatIzlecenosti, 60);
var klinika = setInterval(klinike, 400);
let count1 = 0;
let count2 = 0;
let count3 = 0;
*/
} else if (!counterInView) {
counterStarted = false;
}
})
let count1 = 0;
let count2 = 0;
let count3 = 0;
var pacijenti = setInterval(pacijenata, 300);
var procenat = setInterval(procenatIzlecenosti, 60);
var klinika = setInterval(klinike, 400);
let scrolldown = false;
document.getElementById('brojac').addEventListener('scroll', function(e) {
scrolldown = true;
if( count1 === 10000 ) { clearInterval(pacijenti); }
if( count2 === 70 ) { clearInterval(procenat); }
if( count3 === 4 ) { clearInterval(klinika); }
setTimeout(function(){ scrolldown = false; },250);
});
function pacijenata() {
if( scrolldown === true ){
count1 += 10;
document.querySelector("#number1").innerHTML = count1 + "+";
}
}
function procenatIzlecenosti() {
if(scrolldown === true){
count2 += 1;
document.querySelector("#number2").innerHTML = count2 + "%";
}
}
function klinike() {
if( scrolldown === true ){
count3 += 1;
document.querySelector("#number3").innerHTML = count3;
}
}
#brojac{
height:100px;
overflow:scroll;
}
<section id="brojac">
<div class="counterContainer">
<ul>
<li>
<i class="fas fa-hospital-user"></i>
<p id="number1" class="number">0</p>
<p>Pacijenata</p>
</li>
<li>
<i class="fas fa-universal-access"></i>
<p id="number2" class="number">0</p>
<p>Procenat izlečenosti</p>
</li>
<li>
<i class="fas fa-clinic-medical"></i>
<p id="number3" class="number">0</p>
<p>Klinike</p>
</li>
</ul>
</div>
</section>
You can use Intersection Observer API to initiate the countdown when your target element is visible or intersected in the view port .

How do I display a function using setTimeout in JavaScript?

I have made a quiz with JavaScript and want that when the timer is up, it should not let you attempt the quiz anymore and go to the last page which displays the score. The score is displayed by calling displayResult. I have one HTML file and one JS file. When I use setTimeout, even after the time is up, it doesn’t show the score. I think the function doesn’t get called. I have tried using setInterval instead of setTimeout but still it doesn't work. Can someone tell me what I am doing wrong?
Whole code here.
//timer code in quiz.js
const startingMinutes = 1
let time = startingMinutes * 60
const countdownEl = document.getElementById('countdown')
var vri = setInterval(upd, 1000)
function upd() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
seconds = seconds < 10 ? '0' + seconds : seconds
countdownEl.innerHTML = minutes + ":" + seconds
time--
time = time < 0 ? 0 : time
if (time == 0) {
clearInterval(vri);
}
setTimeout(displayResult, 1000);
}
The function gets called you can easily check this by inserting a console.log() inside the function.
When you would like to display the results on the same page then first clear the body and append your new created element on the body.
There is still a bug that your selected elements will always be empty but I just answer your question here "How you display it."
For debugging purposes I set the timer to 6 seconds instead of 60.
(function() {
var allQuestions = [{
question: "The tree sends downroots from its branches to the soil is know as:",
options: ["Oak", "Pine", "Banyan", "Palm"],
answer: 2
}, {
question: "Electric bulb filament is made of",
options: ["Copper", "Aluminum", "lead", "Tungsten"],
answer: 3
}, {
question: "Non Metal that remains liquid at room temprature is",
options: ["Phophorous", "Bromine", "Clorine", "Helium"],
answer: 1
}, {
question: "Which of the following is used in Pencils ?",
options: ["Graphite", "Silicon", "Charcoal", "Phosphorous"],
answer: 0
}, {
question: "Chemical formula of water ?",
options: ["NaA1O2", "H2O", "Al2O3", "CaSiO3"],
answer: 1
}, {
question: "The gas filled in electric bulb is ?",
options: ["Nitrogen", "Hydrogen", "Carbon Dioxide", "Oxygen"],
answer: 0
}, {
question: "Whashing soda is the comman name for",
options: ["Sodium Carbonate", "Calcium Bicarbonate", "Sodium Bicarbonate", "Calcium Carbonate"],
answer: 0
}, {
question: "Which gas is not known as green house gas ?",
options: ["Methane", "Nitrous oxide", "Carbon Dioxide", "Hydrogen"],
answer: 3
}, {
question: "The hardest substance availabe on earth is",
options: ["Gold", "Iron", "Diamond", "Platinum"],
answer: 2
}, {
question: "Used as a lubricant",
options: ["Graphite", "Silica", "Iron Oxide", "Diamond"],
answer: 0
}];
var quesCounter = 0;
var selectOptions = [];
var quizSpace = $('#quiz');
nextQuestion();
$('#next').click(function() {
chooseOption();
if (isNaN(selectOptions[quesCounter])) {
alert('Please select an option !');
} else {
quesCounter += 5;
nextQuestion();
}
});
$('#prev').click(function() {
chooseOption();
quesCounter -= 5;
nextQuestion();
});
function createElement(index) {
var element = $('<div>', {
id: 'question'
});
var header = $('<h2>Question No. ' + (index + 1) + ' :</h2>');
element.append(header);
var question = $('<p>').append(allQuestions[index].question);
element.append(question);
var radio = radioButtons(index);
element.append(radio);
var question1 = $('<p>').append(allQuestions[index + 1].question);
element.append(question1);
var radio1 = radioButtons1(index + 1);
element.append(radio1);
var question2 = $('<p>').append(allQuestions[index + 2].question);
element.append(question2);
var radio2 = radioButtons2(index + 2);
element.append(radio2);
var question3 = $('<p>').append(allQuestions[index + 3].question);
element.append(question3);
var radio3 = radioButtons3(index + 3);
element.append(radio3);
var question4 = $('<p>').append(allQuestions[index + 4].question);
element.append(question4);
var radio4 = radioButtons4(index + 4);
element.append(radio4);
return element;
}
function radioButtons(index) {
var radioItems = $('<ul>');
var item;
var input = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += allQuestions[index].options[i];
item.append(input);
radioItems.append(item);
}
return radioItems;
}
function radioButtons1(index) {
var radioItems1 = $('<ul>');
var item1;
var input1 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item1 = $('<li>');
input1 = '<input type="radio" name="answer1" value=' + i + ' />';
input1 += allQuestions[index].options[i];
item1.append(input1);
radioItems1.append(item1);
}
return radioItems1;
}
function radioButtons2(index) {
var radioItems2 = $('<ul>');
var item2;
var input2 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item2 = $('<li>');
input2 = '<input type="radio" name="answer2" value=' + i + ' />';
input2 += allQuestions[index].options[i];
item2.append(input2);
radioItems2.append(item2);
}
return radioItems2;
}
function radioButtons3(index) {
var radioItems3 = $('<ul>');
var item3;
var input3 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item3 = $('<li>');
input3 = '<input type="radio" name="answer3" value=' + i + ' />';
input3 += allQuestions[index].options[i];
item3.append(input3);
radioItems3.append(item3);
}
return radioItems3;
}
function radioButtons4(index) {
var radioItems4 = $('<ul>');
var item4;
var input4 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item4 = $('<li>');
input4 = '<input type="radio" name="answer4" value=' + i + ' />';
input4 += allQuestions[index].options[i];
item4.append(input4);
radioItems4.append(item4);
}
return radioItems4;
}
function chooseOption() {
selectOptions[quesCounter] = +$('input[name="answer"]:checked').val();
selectOptions[quesCounter + 1] = +$('input[name="answer1"]:checked').val();
selectOptions[quesCounter + 2] = +$('input[name="answer2"]:checked').val();
selectOptions[quesCounter + 3] = +$('input[name="answer3"]:checked').val();
selectOptions[quesCounter + 4] = +$('input[name="answer4"]:checked').val();
}
function nextQuestion() {
quizSpace.fadeOut(function() {
$('#question').remove();
if (quesCounter < allQuestions.length) {
var nextQuestion = createElement(quesCounter);
quizSpace.append(nextQuestion).fadeIn();
if (!(isNaN(selectOptions[quesCounter, quesCounter + 1, quesCounter + 2, quesCounter + 3, quesCounter + 4]))) {
$('input[value=' + selectOptions[quesCounter] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 1] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 2] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 3] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 4] + ']').prop('checked', true);
}
if (quesCounter === 1) {
$('#prev').show();
} else if (quesCounter === 0) {
$('#prev').hide();
$('#next').show();
}
} else {
var scoreRslt = displayResult();
quizSpace.append(scoreRslt).fadeIn();
$('#next').hide();
$('#prev').hide();
}
});
}
const startingMinutes = 0.1;
let time = startingMinutes * 60
const countdownEl = document.getElementById('countdown')
var vri = setInterval(upd, 1000)
function upd() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
seconds = seconds < 10 ? '0' + seconds : seconds
countdownEl.innerHTML = minutes + ":" + seconds
time--
time = time < 0 ? 0 : time
console.log(time);
if (time === 0) {
clearInterval(vri);
setTimeout(displayResult, 1000);
}
}
function displayResult() {
console.log(selectOptions);
var correct = 0;
console.log(selectOptions);
for (var i = 0; i < selectOptions.length; i++) {
if (selectOptions[i] === allQuestions[i].answer) {
correct++;
}
}
document.body.innerHTML = "";
let score = document.createElement("p");
score.id = 'question';
if (correct === 0 && correct <= 5) {
let otherText = document.createTextNode("YOUR IQ SCORES LIES IN THE RANGE OF 70 and 79 WHICH IS CLASSIFIED AS BORDERLINE");
let img = document.createElement("img");
img.src = "img9b.png"
score.append(otherText)
score.append(img);
} else {
let tex = document.createTextNode("The Result is: " + correct);
score.appendChild(tex);
}
document.body.appendChild(score);
}
})();
<html>
<head>
<title>Make Quiz Website</title>
<link rel="stylesheet" href="quiz.css">
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
</head>
<body>
<div id="container">
<h1>Quiz Website Using JavaScript</h1>
<br/>
<div id="quiz"></div>
<p id="countdown">30:00</p>
</h1>
<div class="button" id="next">Next</div>
<div class="button" id="prev">Prev</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="quiz.js"></script>
</body>
</html>

Limited jquery simple pagination that create by imtech_pager

I want limit this simple jquery pagination
now is ---> 1 2 3 4 5 6 7 8 9 10
i whant convert ----> < 1 2 3... >
after click on 3 ---> < 2 3 4... >
i am use imtech_pager for pagination
<!--in imtech_pager.js -->
var Imtech = {};
Imtech.Pager = function() {
this.paragraphsPerPage = 3;
this.currentPage = 1;
this.pagingControlsContainer = '#pagingControls';
this.pagingContainerPath = '#content';
this.numPages = function() {
var numPages = 0;
if (this.paragraphs != null && this.paragraphsPerPage != null) {
numPages = Math.ceil(this.paragraphs.length / this.paragraphsPerPage);
}
return numPages;
};
this.showPage = function(page) {
this.currentPage = page;
var html = '';
this.paragraphs.slice((page-1) * this.paragraphsPerPage,
((page-1)*this.paragraphsPerPage) + this.paragraphsPerPage).each(function() {
html += '<div>' + $(this).html() + '</div>';
});
$(this.pagingContainerPath).html(html);
renderControls(this.pagingControlsContainer, this.currentPage, this.numPages());
}
var renderControls = function(container, currentPage, numPages) {
var pagingControls = 'Page: <ul style="margin-left: -10px;">';
for (var i = 1; i <= numPages; i++) {
if (i != currentPage) {
pagingControls += '<li>' + i + '</li>';
} else {
pagingControls += '<li>' + i + '</li>';
}
}
pagingControls += '</ul>';
$(container).html(pagingControls);
}
}
<!--for pagination -->
var pager = new Imtech.Pager();
$(document).ready(function() {
pager.paragraphsPerPage =12; // set amount elements per page
pager.pagingContainer = $('#content'); // set of main container
pager.paragraphs = $('div.z', pager.pagingContainer); // set of required containers
pager.showPage(1);
});
<!-- jump script -->
$(document).ready(function() {
$(".jumper").on("click", function( e ) {
e.preventDefault();
$("body, html").animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 600);
});
});
<div class="example">
<div id="content">
<div class="z">one</div>
<div class="z">tow</div>
.
.
.
<div class="z">three</div>
</div>
</div>
<div id="pagingControls"></div>
I whant convert to < 1 2 3 ... >
after click on 3 --> < 2 3 4... >
please help me
thanks

how to link pagination to pagescroll in jquery?

I have created a carousel in javascript to show multiple contents either by using page scroll or by clicking a button. I have used viewpager.js for this purpose. I have added a pagination at the bottom which works fine when the buttons are clicked. I am unable to figure out how to link it to the page scroll. Any help is appreciated. My code:
HTML
<div id='prev'>
<button id="btn-prev"><img src='img/orange-towards-left.png'></button>
</div>
<div class='pager'>
<div class='pager_items' id='info'>
</div>
</div>
<div id='next'>
<button id="btn-next"><img src='img/orange-towards-right.png'></button>
</div>
<div id='pagination'>
<ul></ul>
</div>
JS
item_container = document.querySelector('.pager_items');
view_pager_elem = document.querySelector('.pager');
w = view_pager_elem.getBoundingClientRect().width;
items = payerAccArr.length;
item_container.style.width = (items * 100)+ '%';
var child_width = (100 / items) + '%';
var html = "";
document.getElementById('monthInfo').innerHTML=payerAccArr[0].DateKey + " Bill Amount ";
for (var i = 0; i < items; i++) {
html += "<div class=toggle><h4>Payer Account Name</h4> <ul> <li>" + payerAccArr[i].PayerAccountName +
"</li></ul> _______________ <ul><li> "+(payerAccArr[i].TotalAmount).toFixed(2) +
" USD</li> </ul></div>";
}
item_container.innerHTML = html;
for(var i=0;i<items;i++)
item_container.children[i].style.width = child_width;
var htmlStr='<li class="current"></li>';
for(var i=0;i<items-1;i++){
htmlStr += '<li></li>';
}
$('#pagination ul').html(htmlStr);
vp = new ViewPager(view_pager_elem, {
pages: item_container.children.length,
vertical: false,
onPageScroll : function (scrollInfo) {
offset = -scrollInfo.totalOffset;
invalidateScroll();
},
onPageChange : function (page) {
document.getElementById('monthInfo').innerHTML=payerAccArr[page].DateKey + " Bill Amount ";
}
});
window.addEventListener('resize', function () {
w = view_pager_elem.getBoundingClientRect().width;
invalidateScroll();
});
document.getElementById('btn-prev').addEventListener('click', function (){
vp.previous();
if(index>0){
createDoughnutChart(index--);
}
var li = jQuery("li.current");
if (li.length){
var $prev = li.prev();
if($prev.length == 0)
$prev = $("#pagination li").last().addClass("current");
li.removeClass("current");
$prev.addClass("current");
}
});
Similar code for the next button also has been written.
This issue got solved. I made a change to the onPageChange function by adding the following code. I am now able to link it to both the page scroll and the buttons.
JS:
onPageChange : function (page) {
document.getElementById('monthInfo').innerHTML=payerAccArr[page].DateKey + " Bill Amount ";
// console.log('page', page);
var li = $("li.current");
var curIndex = li.index();
if(li.length){
var $prev = li.prev();
var $next = li.next();
if(page == $prev.index()){
li.removeClass("current");
$prev.addClass("current");
}
if(page==$next.index()){
li.removeClass("current");
$next.addClass("current");
}
}
}

User inputs information into text box which makes allows user to select multiple words and creates different Titles based on the selections

I am gaining user input from four different areas and I want to take those options and convert them to an array which will loop through and display different variations of the words selected. The problem I am having is that the array will not cycle through the variables when passed through it unless they are already pre-defined.
<!DOCTYPE html>
<html>
<head>
<title> Title Generation Module</title>
<script src="title.js" type="text/javascript"></script>
<script src="find.js" type="text/javascript"></script>
<script src="replace.js" type="text/javascript"></script>
<script src="search.js" type="text/javascript"></script>
<script src="generate.js" type="text/javascript"></script>
<!-- <script src="check.js" type="text/javascript"></script>--> <!-- Leaving for future usage not needed at this point -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="jquery-1.11.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="title.css">
</head>
<body>
<h1>Title Generation Module</h1>
<h2>Example</h2>
<p>When you type into Core Words you want to put words that cannot change such as: Logitech
</br> For Word Combinations you want to use words such as: Brand New or Power Adaptor
</br> For Swapped Words you might want to use: Gaming instead of Performance or vice versa
</br> For Synonyms you want to use words that mean the same thing such as for = 4 or at = #</p>
<h3>Core Words</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newCore"/>
<button id="addCore">Insert</button>
<label for="coreContain">Select as many as you like:</label>
<select id="coreContain" name="coreContain" multiple></select>
<button id="checkCore" onclick="checkCore()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addCore").click(function()
{
$("#coreContain").append('<option value="' + $("#newCore").val() + '">' + $("#newCore").val() + '</option>');
});
});
$('#coreContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var coreOptions = new Array();
$('form').submit(
function()
{
$('#coreContain > option:selected').each(
function(i)
{
coreOptions[i] = $(this).val();
});
//window.alert(coreOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs Word Combinations -->
<h3>Word Combinations</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newCombo"/>
<button id="addCombo">Insert</button>
<label for="comboContain">Select as many as you like:</label>
<select id="comboContain" name="comboContain" multiple></select>
<button id="checkCombo" onclick="checkWordCombo()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addCombo").click(function()
{
$("#comboContain").append('<option value="' + $("#newCombo").val() + '">' + $("#newCombo").val() + '</option>');
});
});
$('#comboContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var comboOptions = new Array();
$('form').submit(
function()
{
$('#comboContain > option:selected').each(
function(i)
{
comboOptions[i] = $(this).val();
});
//window.alert(comboOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs words that can swap -->
<h3>Words that can be Swapped</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newSwap"/>
<button id="addSwap">Insert</button>
<label for="swapContain">Select as many as you like:</label>
<select id="swapContain" name="comboSwap" multiple></select>
<button id="checkSwap" onclick="checkSwap()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addSwap").click(function()
{
$("#swapContain").append('<option value="' + $("#newSwap").val() + '">' + $("#newSwap").val() + '</option>');
});
});
$('#swapContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var swapOptions = new Array();
$('form').submit(
function()
{
$('#swapContain > option:selected').each(
function(i)
{
swapOptions[i] = $(this).val();
});
//window.alert(swapOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs words that can be use as Synonyms -->
<h3>Words that can be used as Synonyms</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newSyn"/>
<button id="addSyn">Insert</button>
<label for="synContain">Select as many as you like:</label>
<select id="synContain" name="comboSyn" multiple></select>
<button id="checkSyn" onclick="checkSyn()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addSyn").click(function()
{
$("#synContain").append('<option value="' + $("#newSyn").val() + '">' + $("#newSyn").val() + '</option>');
});
});
$('#synContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var synOptions = new Array();
$('form').submit(
function()
{
$('#synContain > option:selected').each(
function(i)
{
synOptions[i] = $(this).val();
});
//window.alert(synOptions);
return false;
});
</script>
</fieldset>
</form>
<button onclick="generate_title()">Generate Titles</button>
<button onclick="displayList()">Click Me</button>
<script>
function displayList()
{
alert(coreOptions+ " " +comboOptions +" " +swapOptions+ " " +synOptions);
}
</script>
<div id="display"></div>
</body>
</html>
External Javascript
var check = ["Facebook", "MySpace", "Twitter"];
//document.getElementById("coreOptions");
//var checkX = check.splice(" ");
var checkY = document.getElementById("swapOptions");
var input_keywords =
[
[check, check],
//[checkY,checkY],
["Cordless-","Wireless"],
["Rechargeable+"],
].filter(function(item){
return item.length <= 80;
});
/*[
["Men", "Women", "Unisex"],
["1", "2", "3", "fourrrrrrrrrr"],
["Candy Color"],
["Spring"],
["Ski+"],
["Crochet"],
["Hip-hop"],
["Hat Beanie-"],
["One Size+"]].filter(function(item)
{
return item.length <= 80;
});
*/
/*
var input_keywords = [
["Women Men", "Men Women", "Unisex Women Men", "Unisex Men Women", "Unisex", "Womens Mens", "Mens Womens", "Unisex Womens Mens", "Unisex Mens Womens"],
["Fashion", "Trendy", "Stylish", "Korea Style"],
["Candy Color"],
["Spring", "Summer", "Winter"],
["Ski"],
["Crochet", "Knit", "Knitted"],
["Elastic", "Strechable"],
["Hip-hop", "Dance"],
["Hat", "Cap", "Beanie", "Hat Cap", "Hat Beanie", "Hat Cap Beanie"],
["One Size"]
].filter(function(item){
return item.length <= 80;
});
*/
var limit_count = 24;
var max_char_per_title = 80;
var sub_library = ["for=4", "you=u", "at=#", "two=2", "with=w", "adapter=adpt", "Monokini=Mono 9"].map( function (item)
{ return item.split("=");});
function calc_length(title)
{
return (title
.join(" ") + " ")
.replace("- ", " ")
.replace("+ ", " ")
.replace("* ", " ")
.replace(" ", " ")
.replace("\" ", " ")
.replace(" \"", " ")
.length - 1;
}
function get_all_titles(keywords)
{
var result_titles = [];
for(var i = 0; i < keywords.length; i ++)
{
var word_count = keywords[i].length;
var words = keywords[i];
var previous_count = result_titles.length;
if (previous_count == 0)
{
previous_count = word_count;
for (var sub_ii = 0 ; sub_ii < word_count; sub_ii++)
{
result_titles[sub_ii] = [];
result_titles[sub_ii][i] = words[sub_ii];
}
}
else
{
for (var sub_i = 0; sub_i < word_count; sub_i++)
{
for (var sub_ii = 0 ; sub_ii < previous_count; sub_ii++)
{
if (result_titles[previous_count * sub_i + sub_ii] == undefined)
{
result_titles[previous_count * sub_i + sub_ii] = result_titles[sub_ii ].slice();
}
result_titles[previous_count * sub_i + sub_ii][i] = words[sub_i];
}
}
}
}
return result_titles;
}
function substitute(title)
{
for (var subs_idx = 0 ; subs_idx < sub_library.length; subs_idx++)
{
var index = title.indexOf(sub_library[subs_idx][0]);
if (index >= 0)
{
title[index] = sub_library[subs_idx][1];
}
}
return title;
}
function shorten_title_length(titles)
{
var result = [];
var count = 0;
for (var i = 0 ; i < titles.length; i++)
{
if (calc_length(titles[i]) > max_char_per_title)
{
//substitute with the word in library
titles[i] = substitute(titles[i]);
// still too long, remove possible words.
if (calc_length(titles[i]) > max_char_per_title)
{
var words = titles[i];
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx].indexOf("/") == (words[word_idx].length - 1))
{
titles[i] = titles[i].splice(word_idx, 1);
}
}
titles[i] = words
}
}
if (calc_length(titles[i]) <= max_char_per_title)
{
result[count] = titles[i];
count++;
}
else
{
console.log(titles[i].join(" \ "));
}
}
return result;
}
function change_forward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "-")
{
if (word_idx != words.length - 1)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx + 1];
words[word_idx + 1] = tmp;
word_idx ++;
}
}
}
title = words;
return title;
}
function change_backward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "+")
{
if (word_idx != 0)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx - 1];
words[word_idx - 1] = tmp;
}
}
}
title = words;
return title;
}
function finalize(titles)
{
for (var title_idx = 0 ; title_idx < titles.length; title_idx++)
{
for (var word_idx = 0 ; word_idx < titles[title_idx].length; word_idx++)
{
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '+')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '-')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '/')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '"')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '*')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
}
}
return titles;
}
function generate_title()
{
var all_titles = get_all_titles(input_keywords);
//Check keyword files provided by the user, that optional sub words are at least 24
if (all_titles.length < limit_count)
{
alert("not enough different titles");
}
//check total char per title
all_titles = shorten_title_length(all_titles);
// substitute half randomly.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = substitute(all_titles[i]);
}
}
//changing position backward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_backward_position(all_titles[i]);
}
}
//changing position forward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_forward_position(all_titles[i]);
}
}
all_titles = finalize(all_titles);
// evaluate.....
for (var i = 0 ; i < all_titles.length; i++)
{
console.log(i);
console.log(all_titles[i].join(" \ "));
console.log(all_titles[i].length);
alert(all_titles);
}
}

Categories

Resources