I'm trying to add some pagination numbers in Javascript. I already achieved the pagination, I also can show all the pagination numbers but I would like to show only three numbers from all the numbers. Let my show you what I achieved until now:
var values = [{name : "a"}, {name : "b"}, {name : "c"}, {name : "d"}, {name : "e"}, {name : "f"}, {name : "g"}, {name : "h"}, {name : "i"}, {name : "j"}];
var current_page = 1;
var records_per_page = 6;
if (values.length <= 6) {
btn_prev.style.display = "none";
btn_next.style.display = "none";
}
function prevPage() {
if (current_page > 1) {
current_page--;
changePage(current_page);
}
}
function nextPage() {
if (current_page < numPages()) {
current_page++;
changePage(current_page);
}
}
function changePage(page) {
var btn_next = document.getElementById("btn_next");
var btn_prev = document.getElementById("btn_prev");
var listing_table = document.getElementById("poi-cat-id");
var page_span = document.getElementById("page");
var pageNum = document.getElementById("pageNum");
// Validate page
if (page < 1) page = 1;
if (page > numPages()) page = numPages();
listing_table.innerHTML = "";
var href = getRootWebSitePath();
for (var i = (page - 1) * records_per_page; i < (page * records_per_page) && i < values.length; i++) {
var nametoslug1 = values[i].name;
var slug1 = convertToSlug(nametoslug1);
listing_table.innerHTML += '<div class="event-desc"><p>' + values[i].name + '</p></div>';
}
if (page == 1) {
btn_prev.style.color = "#404141";
} else {
btn_prev.style.visibility = "visible";
btn_prev.style.color = "#0c518a";
}
if (page == numPages()) {
btn_next.style.color = "#404141";
} else {
btn_next.style.visibility = "visible";
btn_next.style.color = "#0c518a";
}
male();
maen();
}
//this is where I add all the numbers of the pagination
var totnum = numPages();
for (var i = 0; i < numPages() + 2; i++) {
// We do not want page 0. You could have started with i = 1 too.
$('#page-num-container').append('' + (i + 1) + '');
}
======EDIT=====
function newPage(){
$('.pageClick').on('click', function (e) {
e.preventDefault();
changePage($(this).index() + 1);
});
} //when I click the number the pages won't change
function numPages() {
return Math.ceil(values.length / records_per_page);
}
window.onload = function () {
changePage(1);
};
and this is my html :
<div>
<ul class="content-full" id="poi-cat-id"></ul>
<div class="pagination-poi-arrows">
<div class="prev">
<img src="~/img/left-arrow-pagination.svg" />
</div>
<div class="page-num-container" id="page-num-container">
</div>
<div class="nex">
<img src="~/img/right-arrow-pagination.svg" />
</div>
</div>
<div class="pagination-poi-arrows" id="pager"></div>
</div>
Can anybody help would be highly appreciated since I've been stuck with this for a while.
If you want to show the adjacent page numbers, then you have to start iterating at i=current_page until i=current_page + 2.
However, it seems that in your code, you start counting at 1 with your pages. I advise you to start at 0.
Now, back to your code. You need to replace the loop with the following (if you're counting from 1):
function updatePagination(page) {
for (var i = page - 1; i < page + 1; i++) {
$('#page-num-container').append('<a href="javascript:pagesNr()"
class="pageClick">' + (i + 1) + '</a>');
}
}
// you need to clear the element before you update it
function clearPagination() {
$('#page-num-container').empty();
}
You would call both of these methods at the end of the changePage() method.
Related
I Am Trying to make a popover with a bootstrap carousel and where the carousel items are to be generated and appended from a script but I get the carousel but I am unable to append the item. I tried hard but I didn't come up with a solution.
the HTML initialized is as below
HTML:
<div class="popup" data-popup="popup-1">
<div class="popup-inner">
<i class="fas fa-bars"></i>
<div class="frame">
<div id='carousel' class='carousel slide' data-bs-ride='carousel'>
<div class='carousel-inner items-slider1'>
</div>
</div>
</div>
</div>
</div>
the script I have tried was
Javascript:
function findallchord(currentchord , currenttype) {
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord ,currenttype,i)) {
Raphael.chord("div3", Raphael.chord.find(currentchord , currenttype,i), currentchord +' ' +currenttype).element.setSize(75, 75);
}
}
}
var getChordRoots = function (input) {
if (input.length > 1 && (input.charAt(1) == "b" || input.charAt(1) == "#"))
return input.substr(0, 2);
else
return input.substr(0, 1);
};
$('.popup').on('shown.bs.popover', function () {
$('.carousel-inner').carousel();
});
$('[data-bs-toggle="popover"]').popover({
html: true,
content: function() {
return $('.popup').html();
}}).click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
});
I have also tried appendTo also as
$(theDiv).appendTo('.items-slider1');
Please Help to solve this
This is the output I get, the appended elements are not in the carousel
Note: I am using Bootstrap 5
Try instantiating the carousel after you've set it up
/*
$('.popup').on('shown.bs.popover', function () {
$('.carousel-inner').carousel();
});
*/
$('[data-bs-toggle="popover"]').popover({
html: true,
content: function() {
return $('.popup').html();
}}).click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
$('.carousel-inner').carousel();
});
It was needed to do call the click function first before popover as below
$('[data-bs-toggle="popover"]').click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
}).popover({
html: true,
content: function() {
return $('.popup').html();
}});
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>
In this prototype, I have "products" that are each individually stored in a div along with their price. I have added four buttons that sort the divs containing the products in alphabetical order (A-Z AND Z-A) as well as by price (lowest to highest and highest to lowest). These sorting functions work perfectly by themselves. I also have a search bar that acts as a search engine if you like an upon entering each character into the input field, will eliminate the products (div's) by name if they do not contain that letter(s). I have done this using a regular expression. This also worked by itself until I adapted it to try and work in conjunction with the sorting mechanisms.
Problem
I would like to be able to search for "products" using the search functionality to display the correct results regardless of what order the products have been sorted into.
Question
How is it possible to be able to display only the div's that contain the letter(s) searched for in the search bar regardless of the ordering (e.g. Z to A).
I think I ruined the search function itself by adding the index variable but you can't do list.name[i].match(res) can you? There is something wrong with the logic behind the search function. I believe the function that needs serious fixing is the searchProducts function.
The code AFTER I adapted the searchProducts function is below...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div id="resultsSpan"></div>
<div id="product0" style="height:60px; width:60px; background-color:blue;"></div>
<div id="product1" style="height:60px; width:60px; background-color:blue;"></div>
<div id="product2" style="height:60px; width:60px; background-color:blue;"></div>
<div id="product3" style="height:60px; width:60px; background-color:blue;"></div>
<button onclick="sortprods()">
Sort A-Z
</button>
<button onclick="sortprods2()">
Sort Z-A
</button>
<button onclick="sortprods3()">
Price (low to high)
</button>
<button onclick="sortprods4()">
Price (high to low)
</button>
<input type="text" id="searchbar" onkeyup="searchProducts()"/>
</body>
</html>
<script>
var list = [
{name: "Apple", price: 31},
{name: "Banana", price: 22},
{name: "Orange", price: 46},
{name: "Strawberry", price:76}
];
list.sort(AtoZ);
for (var i = 0; i<list.length; i++) {
document.getElementById("product" + i).innerHTML = list[i].name + ", " + list[i].price;
}
function AtoZ(a,b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
function ZtoA(a,b) {
if (a.name < b.name)
return 1;
if (a.name > b.name)
return -1;
return 0;
}
function LowtoHigh(a,b) {
if (a.price < b.price)
return -1;
if (a.price > b.price)
return 1;
return 0;
}
function HightoLow(a,b) {
if (a.price < b.price)
return 1;
if (a.price > b.price)
return -1;
return 0;
}
function sortprods(){
list.sort(AtoZ);
currentSort = "AtoZ";
for (var i = 0; i < list.length; i++) {
document.getElementById("product" + i).innerHTML = list[i].name + ", " + list[i].price;
}
}
function sortprods2(){
list.sort(ZtoA);
currentSort = "ZtoA";
for (var j = 0; j < list.length; j++) {
document.getElementById("product" + j).innerHTML = list[j].name + ", " + list[j].price;
}
}
function sortprods3(){
currentSort = "LowtoHigh";
list.sort(LowtoHigh);
for (var k = 0; k < list.length; k++) {
document.getElementById("product" + k).innerHTML = list[k].name + ", " + list[k].price;
}
}
function sortprods4(){
currentSort = "HightoLow";
list.sort(HightoLow);
for (var l = 0; l < list.length; l++) {
document.getElementById("product" + l).innerHTML = list[l].name + ", " + list[l].price;
}
}
var input = "";
var index = [];
var currentSort = "AtoZ";
function searchProducts(){
input = document.getElementById("searchbar").value;
if(input == ""){
document.getElementById("product0").style.display = "block";
document.getElementById("product1").style.display = "block";
document.getElementById("product2").style.display = "block";
document.getElementById("product3").style.display = "block";
}else{
switch(currentSort){
case "AtoZ":
list.sort(AtoZ);
for(var a = 0; a < list.length; a++){
document.getElementById("product" + a).innerHTML = list[a].name + ", " + list[a].price;
index.push(list[a].name);
}
index.sort();
break;
case "ZtoA":
list.sort(ZtoA);
for(var b = 0; b < list.length; b++){
document.getElementById("product" + b).innerHTML = list[b].name + ", " + list[b].price;
index.push(list[b].name);
}
index.sort();
index.reverse();
break;
case "LowtoHigh":
list.sort(LowtoHigh);
for(var c = 0; c < list.length; c++){
index.push(list[c].price);
}
index.sort(function(a, b){return a-b});
break;
case "HightoLow":
list.sort(HightoLow);
for(var d = 0; d < list.length; d++){
index.push(list[d].price);
}
index.sort(function(a, b){return b-a});
break;
}
test = input;
re = new RegExp(test, 'gi');
for(var e=0; e<index.length; e++){
if(index[e].match(re)){
document.getElementById("product"+e).style.display = "block";
}else{
document.getElementById("product"+e).style.display = "none";
}
}
}
}
</script>
The code before I adapted the searchProducts function (THAT WORKED PERFECTLY BEFORE ADAPTION) is...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<input type="text" id="searchbar" onkeyup="searchProducts()"/>
<div id="demo"></div>
<div id="demo2">
<div id="product1" style="background-color:red; height:100px; width:100px; float:left">chocolate<br /><button onClick="grow()" id="button1">Show Info</button></div>
<div id="product2" style="background-color:blue; height:100px; width:100px; float:left">Mint</div>
<div id="product3" style="background-color:green; height:100px; width:100px; float:left">Caramel</div>
</div>
</body>
</html>
<script>
var index = ["Chocolate", "Mint", "Caramel"];
var input = "";
var currentLog = [];
function searchProducts(){
currentLog = [];
input = document.getElementById("searchbar").value;
/*function searchStringInArray(str, strArray){
for (var j = 0; j < strArray.length; j++) {
if (strArray[j].match(str)){
var temp = strArray.slice(j, (j + 1));
currentLog.push(temp);
console.log(j);
}
}
document.getElementById("demo").innerHTML = currentLog.join("<br />");
if(currentLog.length < 1){
document.getElementById("demo").innerHTML = "No results were found.";
}
}*/
test = input;
re = new RegExp(test, 'gi');
/*if(!index[0].match(re)){
document.getElementById("product1").style.display = "none";
}
if(!index[1].match(re)){
document.getElementById("product2").style.display = "none";
}
if(!index[2].match(re)){
document.getElementById("product3").style.display = "none";
}*/
for(var e=0; e<index.length; e++){
if(!index[e].match(re)){
document.getElementById("product"+(e+1)).style.display = "none";
}else{
document.getElementById("product"+(e+1)).style.display = "block";
}
}
if(document.getElementById("product1").style.display == "none" && document.getElementById("product2").style.display == "none" && document.getElementById("product3").style.display == "none"){
document.getElementById("demo").innerHTML = "no results";
}else{
document.getElementById("demo").innerHTML = "";
}
/*searchStringInArray(input, index);*/
}
function grow(){
if(document.getElementById('product1').style.height == "200px"){
document.getElementById('product1').style.height = '100px';
document.getElementById('button1').innerHTML = "Show Info";
}else{
document.getElementById('product1').style.height = "200px";
document.getElementById('button1').innerHTML = "Hide Info";
}
}
</script>
The issue is that when you sort your list when a filter was applied earlier, you only move the data, not the visibility of the containers of those data.
Instead you could re-execute the regex matching, every time you display the content according to the current sort order. That way you are sure the right data are visible at all times.
You have a lot of duplication in your code, with several places where you have the same loop, or code that only differs in one aspect. You should always try to "Don't Repeat Yourself" (DRY).
I would suggest to have one function for displaying content only. You could pass it the sort function to apply. Note that this means the HTML also changes where you have specified the event handlers. There are many other such simplifications, which are too many to mention all.
Check this snippet:
var list = [
{name: "Apple", price: 31},
{name: "Banana", price: 22},
{name: "Orange", price: 46},
{name: "Strawberry", price:76}
];
var currentRegex = /./; // any character matches
var currentSort = AtoZ;
// Call the function we have for applying the initial sort order and filter
searchProducts(document.getElementById('searchbar').value);
// Shorter ways to compare:
function AtoZ(a,b) { return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; }
function ZtoA(a,b) { return AtoZ(b,a) }
function LowtoHigh(a,b) { return a.price - b.price }
function HightoLow(a,b) { return b.price - a.price }
// One function for all sort orders: pass sort order as function
function sortprods(sorter) {
var showCount = 0;
currentSort = sorter;
list.sort(currentSort);
for (var i = 0; i < list.length; i++) {
var product = document.getElementById("product" + i);
// use textContent, not innerHTML
product.textContent = list[i].name + ", " + list[i].price;
var show = !!list[i].name.match(currentRegex);
product.style.display = show ? "" : "none";
showCount += show;
}
document.getElementById('resultsSpan').textContent =
showCount ? '' : 'no results';
}
function searchProducts(input){
// Argument is value of input
// No need to `switch` on currentSort. Can do this with generic code.
// Deal with empty input by using all-matching `.` regexp.
// `g` not needed.
currentRegex = new RegExp(input.length ? input : '.', 'i');
sortprods(currentSort);
}
<div id="resultsSpan"></div>
<div id="product0" style="height:45px; width:60px; background-color:lightblue;"></div>
<div id="product1" style="height:45px; width:60px; background-color:lightblue;"></div>
<div id="product2" style="height:45px; width:60px; background-color:lightblue;"></div>
<div id="product3" style="height:45px; width:60px; background-color:lightblue;"></div>
<button onclick="sortprods(AtoZ)">Sort A-Z</button>
<button onclick="sortprods(ZtoA)">Sort Z-A</button>
<button onclick="sortprods(LowtoHigh)">Price (low to high)</button>
<button onclick="sortprods(HightoLow)">Price (high to low)</button>
<input type="text" id="searchbar" onkeyup="searchProducts(this.value)"/>
About the ternary operator:
You asked in comments about the ternary operator:
product.style.display = list[i].name.match(currentRegex) ? "" : "none";
The above is equivalent to this:
var temp;
if (list[i].name.match(currentRegex)) {
temp = "";
} else {
temp = "none";
}
product.style.display = temp;
... except that no temp variable is created of course.
The other occurrence:
currentRegex = new RegExp(input.length ? input : '.', 'i');
... is equivalent to:
var temp;
if (input.length) { // if length is defined and not 0
temp = input;
} else {
temp = ".";
}
currentRegex = new RegExp(temp, 'i');
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");
}
}
}
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);
}
}