Bind textbox value with dynamic div's - javascript

I am trying to append / (Bind) textbox innerhtml value to the dynamic div which has the pagination. When I am trying append with textbox with the div I am getting an error.
There are two elements in my initial page First One is for no of pages and other one is for enter some text. If I enter number 2 so two div will appear dynamically. Then I enter the greeting text second text box. Text should appear in the first div and for the second div if i click the button in the bottom second div should be empty. Using Pure javascript (Vanila).
I am trying to get value from the textbox. But I was not able to bind with the p tag which was available dynamically.
Kindly help me.
var gettext_Title = document.getElementById('title_Text')
var getresult = gettext_Title.value;
//alert(result);
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function() {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
hTitle = document.createElement('p');
preview_PageSize = document.getElementById('page');
navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.setAttribute('data-page', totalCount);
navbutton.innerHTML = [1 + totalCount];
navbutton.addEventListener('click', function (e) {
var el = e.target;
var page = parseInt(el.getAttribute('data-page'), 10);
var allPages = document.querySelectorAll('.preview_windowSize_element');
Array.prototype.forEach.call(allPages, function (pageElement) {
pageElement.style.zIndex = 0;
});
var pageEl = document.querySelector('div[data-page="' + page + '"]');
pageEl.style.zIndex = 10;
});
spancount.className = "spanCount";
spancount.innerHTML = [1 + totalCount];
hTitle.setAttribute('id', ['Title' + (totalCount)]);
hTitle.className = "title_boundry";
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', ['page' + (totalCount)]);
prevPage.setAttribute('data-page', totalCount);
prevPage.appendChild(spancount);
prevPage.appendChild(hTitle);
navpageBtn.appendChild(navbutton);
preview_PageSize.insertBefore(prevPage, preview_PageSize.childNodes[0]);
totalCount++;
}
inputElement.value = "";
document.body.appendChild(fragment);
}
});
Here is the Jsfiddle Link
Thanks in advance
Kindly help me
Cheers,

If I understand correctly what you mean, try this:
main.js :
(function () {
var inputTitle,
inputElement,
current,
totalCount = 0;
document.addEventListener('DOMContentLoaded', function (e) {
inputTitle = document.getElementById('title_Text');
inputElement = document.getElementById("inputAdd_page");
inputElement.addEventListener('blur', onInputElementBlur);
inputTitle.addEventListener('blur', onInputTitleBlur);
});
function onInputTitleBlur(e) {
if (!!current) {
var title = current.querySelector('p');
title.innerText = inputTitle.value;
inputTitle.value = '';
}
}
function onInputElementBlur() {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
var fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
var spancount = document.createElement('span');
var prevPage = document.createElement('div');
var navbutton = document.createElement('button');
var hTitle = document.createElement('p');
var preview_PageSize = document.getElementById('page');
var navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', 'pag_navg' + totalCount);
navbutton.setAttribute('data-page', totalCount);
navbutton.innerHTML = 1 + totalCount;
navbutton.addEventListener('click', function (e) {
var el = e.target;
var page = parseInt(el.getAttribute('data-page'), 10);
var allPages = document.querySelectorAll('.preview_windowSize_element');
Array.prototype.forEach.call(allPages, function (pageElement) {
pageElement.style.zIndex = 0;
});
var pageEl = document.querySelector('div[data-page="' + page + '"]');
current = pageEl;
pageEl.style.zIndex = 10;
});
spancount.className = "spanCount";
spancount.innerHTML = 1 + totalCount;
hTitle.setAttribute('id', 'Title' + (totalCount));
hTitle.className = "title_boundry";
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', 'page' + (totalCount));
prevPage.setAttribute('data-page', totalCount);
prevPage.appendChild(spancount);
prevPage.appendChild(hTitle);
navpageBtn.appendChild(navbutton);
preview_PageSize.insertBefore(prevPage, preview_PageSize.childNodes[0]);
totalCount++;
}
current = document.querySelector('div[data-page="0"]');
inputElement.value = "";
document.body.appendChild(fragment);
}
}
}());
index.html :
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link id="myStyleSheet" href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<input type="text" class="form-control title_Textbox" id="title_Text" placeholder="Text">
<input type="text" class="form-control title_Textbox" id="inputAdd_page" placeholder="No Of Pages">
<div class="preview_windowSize" id="page"></div>
<div id="pageBtn" class="row pagination_btn"></div>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
style.css :
.div_navig {
background: lightGrey;
width: 24px;
height: 24px;
text-align: center;
margin-left: 5px;
color: black;
cursor: pointer;
}
.pagination_btn {
float: right;
margin: 0 20px 0 0;
padding-left: 5px;
}
.spanCount {
position: absolute;
bottom: 0;
right: 0;
padding: 0 10px 0 5px;
}
.preview_windowSize {
margin: 15px 15px 15px 15px;
height: 300px;
padding: 5px;
}
.preview_windowSize_element {
position: absolute;
background-color: lightGrey;
border: 1px solid rgb(155, 155, 155);
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
padding: 5px;
width: 93.5%;
height: 300px;
}
.title_boundry {
border: 1px dotted #000;
height: 40px;
}

Related

How can i optimise javascript pagination so that it works for any number of pages?

i am trying to create Vanilla Javascript Pagination and i have a problem because it looks like my pagination is only working when there is 7 pages,when that number switches there are small bugs but i cant find a way to optimise better my code and to make the code be usable for any number of page.Here is the code:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
crossorigin="anonymous" />
<link rel="stylesheet" href="./main.css" />
</head>
<body>
<section class="blog-listing">
<div class="container">
<div class="row">
<div class="col-6">
<input
type="search"
class="inputs"
id="searcher"
placeholder="Search" />
<input type="hidden" name="type" value="BLOG_POST" />
<input type="hidden" name="type" value="LISTING_PAGE" />
</div>
<div class="col-6"></div>
</div>
<div class="row" id="blogs"></div>
<div id="blog-pagination"></div>
<div id="buttons"></div>
</div>
</section>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4"
crossorigin="anonymous"></script>
<script src="./main.js"></script>
</body>
</html>
CSS
.blog-listing {
padding: 200px 0px;
}
.blog-listing input {
background-color: #f3f3f3;
border-radius: 40.5px;
width: 100%;
padding: 20px;
margin-bottom: 20px;
}
.blog-listing input::-moz-placeholder {
font-family: "Poppins";
font-weight: 300;
font-size: 18px;
line-height: 44px;
color: #19212f;
}
.blog-listing input:-ms-input-placeholder {
font-family: "Poppins";
font-weight: 300;
font-size: 18px;
line-height: 44px;
color: #19212f;
}
.blog-listing input::placeholder {
font-family: "Poppins";
font-weight: 300;
font-size: 18px;
line-height: 44px;
color: #19212f;
}
.blog-listing__card {
background: #ffffff;
box-shadow: 0px 0px 40px rgba(0, 0, 0, 0.105633);
border-radius: 4px;
padding-bottom: 100px;
margin-top: 50px;
}
.blog-listing__card__image img {
width: 100%;
}
.blog-listing__card__text {
padding: 30px 40px 60px;
}
.blog-listing__card__text a {
font-family: "Poppins";
font-weight: 700;
font-size: 16px;
line-height: 25px;
color: #089fd9;
}
.blog-listing__card__text p {
font-family: "Poppins";
font-weight: 700;
font-size: 16px;
line-height: 25px;
color: #878787;
padding-top: 15px;
}
.blog-listing__card__text h1,
.blog-listing__card__text h2,
.blog-listing__card__text h3 {
font-family: "Poppins";
font-weight: 700;
font-size: 22px;
line-height: 53px;
letter-spacing: -0.392857px;
color: #293241;
}
.blog-listing__card__divider {
border: 1px solid #cccccc;
}
.blog-listing__card.is-hidden {
opacity: 0;
}
.blog-listing__card__topics ul {
list-style-type: none;
}
.blog-listing__card__topics ul li a {
font-family: "Abel";
font-weight: 400;
font-size: 12px;
line-height: 25px;
color: #293241;
opacity: 0.5;
}
.blog-tag-filter {
background-color: transparent;
border: 0;
border-radius: 0;
padding: 0;
}
#media (max-width: 767px) {
.blog-tag-filter {
margin-bottom: 1.5rem;
text-align: center;
}
}
.blog-tag-filter__title {
color: #fff;
margin-right: 1.5rem;
}
.blog-tag-filter__select-wrapper {
display: inline-block;
max-width: 100%;
position: relative;
width: 100%;
}
.blog-tag-filter__select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
display: inline-block;
padding: 1.25rem 4.5rem 1.25rem 2.75rem;
background-color: #f3f3f3;
border-radius: 40.5px;
padding: 18px;
width: 100%;
max-width: 100%;
font-family: "Poppins";
font-weight: 300;
font-size: 18px;
color: #19212f;
}
.blog-tag-filter__select-wrapper:after {
color: #19212f;
content: "▾";
pointer-events: none;
position: absolute;
right: 0.7rem;
top: 50%;
transform: translateY(-50%);
}
#blog-pagination {
text-align: center;
padding: 50px 0px;
}
#buttons input {
display: inline-block;
cursor: pointer;
border: 0.75px solid #bbbbbb;
border-radius: 4px;
padding: 20px;
width: 100px;
text-align: center;
background-color: white;
color: #089fd9;
}
#buttons {
text-align: center;
}
.active {
background-color: #089fd9 !important;
color: #ffffff !important;
}
:disabled {
cursor: not-allowed !important;
color: gray !important;
background-color: #f1f1f1 !important;
}
.none {
display: none !important;
}
JS
let allBlogs = [];
allBlogs.length = 14;
let blog_div = document.getElementById("blogs");
let blogTagSelect = document.querySelector("#tag-select");
// let selectedItem = blogTagSelect.options[blogTagSelect.selectedIndex];
let countList = new Array();
let addPageList = new Array();
let presentPage = 1;
let countPerEachPage = 2;
let countOfPages = 0;
let buttons = document.getElementById("buttons");
function prepareList() {
let inputFirst = document.createElement("input");
inputFirst.setAttribute("type", "button");
inputFirst.setAttribute("id", "first");
inputFirst.setAttribute("value", "first");
inputFirst.onclick = function () {
presentPage = 1;
loadMyPaginationList();
for (let i = 0; i < pageBtns.length; i++) {
pageBtns[i].classList.remove("active");
if (Number(pageBtns[i].value) == presentPage) {
pageBtns[i].classList.add("active");
}
if (pageBtns[i].classList.contains("active")) {
pageBtns[i].classList.remove("none");
for (let j = 0; j < pageBtns.length; j++) {
if (pageBtns[j].value > 2) {
pageBtns[j].classList.add("none");
pageBtns[1].classList.remove("none");
if (pageBtns[j].value > pageBtns.length - 2) {
pageBtns[j].classList.remove("none");
}
}
}
}
}
};
let inputPrevious = document.createElement("input");
inputPrevious.setAttribute("type", "button");
inputPrevious.setAttribute("id", "previous");
inputPrevious.setAttribute("value", "previous");
inputPrevious.onclick = function () {
presentPage -= 1;
loadMyPaginationList();
for (let i = 0; i < pageBtns.length; i++) {
pageBtns[i].classList.remove("active");
if (Number(pageBtns[i].value) == presentPage) {
pageBtns[i].classList.add("active");
pageBtns[i].classList.remove("none");
if (Number(pageBtns[i].value) < Math.ceil(pageBtns.length / 2)) {
pageBtns[i + 2].classList.add("none");
}
if (Number(pageBtns[i].value) == pageBtns.length - 2) {
pageBtns[i - 1].classList.remove("none");
for (let j = 0; j < pageBtns.length; j++) {
if (pageBtns[j].value < Math.ceil(pageBtns.length / 2)) {
pageBtns[j].classList.add("none");
}
}
}
}
}
};
buttons.appendChild(inputFirst);
buttons.appendChild(inputPrevious);
for (count = 0; count < allBlogs.length; count++) {
countList.push(count);
}
countOfPages = getCountOfPages();
for (let i = 1; i <= countOfPages; i++) {
let inputButton = document.createElement("input");
inputButton.setAttribute("type", "button");
inputButton.setAttribute("class", "page-buttons");
inputButton.setAttribute("value", i);
inputButton.onclick = function () {
presentPage = Number(inputButton.value);
loadMyPaginationList();
};
buttons.appendChild(inputButton);
if (
inputButton.value > presentPage + 1 &&
inputButton.value < countOfPages - 1
) {
inputButton.classList.add("none");
if (Number(inputButton.value) == countOfPages - 2) {
let Dots = document.createElement("input");
Dots.setAttribute("value", "...");
Dots.setAttribute("class", "dots");
buttons.appendChild(Dots);
}
}
}
let inputNext = document.createElement("input");
inputNext.setAttribute("type", "button");
inputNext.setAttribute("id", "next");
inputNext.setAttribute("value", "next");
inputNext.onclick = function () {
presentPage += 1;
loadMyPaginationList();
for (let i = 0; i < pageBtns.length; i++) {
pageBtns[i].classList.remove("active");
if (Number(pageBtns[i].value) == presentPage) {
pageBtns[i].classList.add("active");
if (pageBtns[i + 1] != null) {
pageBtns[i + 1].classList.remove("none");
pageBtns[i - 1].classList.add("none");
}
if (Number(pageBtns[i].value - 1) >= Math.ceil(pageBtns.length / 2)) {
pageBtns[i - 1].classList.remove("none");
} else {
pageBtns[i - 1].classList.add("none");
}
if (pageBtns[i].classList.contains("active")) {
pageBtns[i].classList.remove("none");
if (pageBtns[i - 2] != null) {
pageBtns[i - 2].classList.add("none");
if (pageBtns[i].value > Math.ceil(pageBtns.length / 2 + 1)) {
pageBtns[i - 2].classList.remove("none");
}
}
}
}
}
};
let inputLast = document.createElement("input");
inputLast.setAttribute("type", "button");
inputLast.setAttribute("id", "last");
inputLast.setAttribute("value", "last");
inputLast.onclick = function () {
presentPage = countOfPages;
loadMyPaginationList();
for (let i = 0; i < pageBtns.length; i++) {
pageBtns[i].classList.remove("active");
if (Number(pageBtns[i].value) == presentPage) {
pageBtns[i].classList.add("active");
}
}
};
buttons.appendChild(inputNext);
buttons.appendChild(inputLast);
let pageBtns = document.querySelectorAll(".page-buttons");
for (let i = 0; i < pageBtns.length; i++) {
if (Number(pageBtns[i].value) == presentPage) {
pageBtns[i].classList.add("active");
}
pageBtns[i].addEventListener("click", function () {
let current = document.getElementsByClassName("active");
if (current.length > 0) {
current[0].classList.remove("active");
}
pageBtns[i].classList.add("active");
});
}
}
//function for creating how many how many number per each page
function getCountOfPages() {
return Math.ceil(countList.length / countPerEachPage);
}
//function for creating how to move between the pages
function loadMyPaginationList() {
let offset = (presentPage - 1) * countPerEachPage + 1 - 1;
let start = (presentPage - 1) * countPerEachPage;
let end = start + countPerEachPage;
addPageList = countList.slice(start, end);
createPageList();
validatePageCount();
}
//function for adding numbers to each page
function createPageList() {
blog_div.innerHTML = "";
let indexEnd =
presentPage * countPerEachPage <= allBlogs.length
? presentPage * countPerEachPage
: allBlogs.length;
for (let i = (presentPage - 1) * countPerEachPage; i < indexEnd; i++) {
let bootstrapDiv = document.createElement("div");
bootstrapDiv.classList = "col-lg-4 col-md-6 col-sm-12";
let card = document.createElement("div");
card.classList = "blog-listing__card";
let cardImage = document.createElement("div");
cardImage.classList = "blog-listing__card__image";
let link = document.createElement("a");
link.setAttribute("href", "#");
let img = document.createElement("img");
img.setAttribute("src", "./Bitmap.svg");
let cardText = document.createElement("div");
cardText.classList = "blog-listing__card__text";
let cardTitle = document.createElement("h2");
cardTitle.innerText = `Naslov ${i}`;
let textLink = document.createElement("a");
textLink.setAttribute("href", "#");
textLink.innerText = `Datum | Autor`;
let textText = document.createElement("p");
textText.innerText = `Opis`;
let topics = document.createElement("div");
topics.classList = "blog-listing__card__topics";
let topicList = document.createElement("ul");
let topicLi = document.createElement("li");
let topicLink = document.createElement("a");
topicLink.setAttribute("href", "#");
topicLink.innerText = `Tagovi`;
let divider = document.createElement("div");
divider.classList = "blog-listing__card__divider";
cardText.appendChild(cardTitle);
cardText.appendChild(textLink);
cardText.appendChild(textText);
link.appendChild(img);
cardImage.appendChild(link);
topicLi.appendChild(topicLink);
topicList.appendChild(topicLi);
topics.appendChild(topicList);
card.appendChild(cardImage);
card.appendChild(cardText);
card.appendChild(topics);
card.appendChild(divider);
bootstrapDiv.appendChild(card);
blog_div.appendChild(bootstrapDiv);
}
}
//function for validating real time condition like if move to last page, last page disabled etc
function validatePageCount() {
let inputFirst = document.getElementById("first");
let inputPrevious = document.getElementById("previous");
let inputNext = document.getElementById("next");
let inputLast = document.getElementById("last");
let PBtn = document.querySelectorAll(".page-buttons");
if (presentPage == 1) {
inputFirst.setAttribute("disabled", "");
inputPrevious.setAttribute("disabled", "");
} else {
inputFirst.removeAttribute("disabled");
inputPrevious.removeAttribute("disabled");
}
if (presentPage == countOfPages) {
inputNext.setAttribute("disabled", "");
inputLast.setAttribute("disabled", "");
} else {
inputNext.removeAttribute("disabled");
inputLast.removeAttribute("disabled");
}
}
//function for loading pagination functionality
function loadMyPagination() {
prepareList();
loadMyPaginationList();
}
window.onload = loadMyPagination;
function liveSearch() {
let searchQuery = document.getElementById("searcher").value;
let cards = document.querySelectorAll(".blog-listing__card");
for (let i = 0; i < cards.length; i++) {
if (cards[i].querySelector("h1, h2, h3").outerText !== null) {
if (
cards[i]
.querySelector("h1, h2, h3")
.outerText.toLowerCase()
.includes(searchQuery.toLowerCase())
) {
cards[i].classList.remove("is-hidden");
} else {
cards[i].classList.add("is-hidden");
}
}
}
}
let typingTimer;
let typeInterval = 300;
let searchInput = document.getElementById("searcher");
searchInput.addEventListener("keyup", () => {
clearTimeout(typingTimer);
typingTimer = setTimeout(liveSearch, typeInterval);
});
function blogFilter() {
if (document.querySelector("#tag-select") !== null) {
let blog_div = document.getElementById("blogs");
let blogTagSelect = document.querySelector("#tag-select");
let selectedItem = blogTagSelect.options[blogTagSelect.selectedIndex];
if (selectedItem.innerText == "Tags") {
blog_div.innerHTML = "";
for (let i = 0; i < allBlogs.length; i++) {
let bootstrapDiv = document.createElement("div");
bootstrapDiv.classList = "col-lg-4 col-md-6 col-sm-12";
let card = document.createElement("div");
card.classList = "blog-listing__card";
let cardImage = document.createElement("div");
cardImage.classList = "blog-listing__card__image";
let link = document.createElement("a");
link.setAttribute("href", "#");
let img = document.createElement("img");
img.setAttribute("src", "./Bitmap.svg");
let cardText = document.createElement("div");
cardText.classList = "blog-listing__card__text";
let cardTitle = document.createElement("h2");
cardTitle.innerText = `Naslov ${i}`;
let textLink = document.createElement("a");
textLink.setAttribute("href", "#");
textLink.innerText = `Datum | Autor`;
let textText = document.createElement("p");
textText.innerText = `Opis`;
let topics = document.createElement("div");
topics.classList = "blog-listing__card__topics";
let topicList = document.createElement("ul");
let topicLi = document.createElement("li");
let topicLink = document.createElement("a");
topicLink.setAttribute("href", "#");
topicLink.innerText = `Tagovi`;
let divider = document.createElement("div");
divider.classList = "blog-listing__card__divider";
cardText.appendChild(cardTitle);
cardText.appendChild(textLink);
cardText.appendChild(textText);
link.appendChild(img);
cardImage.appendChild(link);
topicLi.appendChild(topicLink);
topicList.appendChild(topicLi);
topics.appendChild(topicList);
card.appendChild(cardImage);
card.appendChild(cardText);
card.appendChild(topics);
card.appendChild(divider);
bootstrapDiv.appendChild(card);
blog_div.appendChild(bootstrapDiv);
}
} else {
blog_div.innerHTML = "";
for (let i = 0; i < allBlogs.length; i++) {
if (allBlogs[i].topic.includes(selectedItem.innerText)) {
let bootstrapDiv = document.createElement("div");
bootstrapDiv.classList = "col-lg-4 col-md-6 col-sm-12";
let card = document.createElement("div");
card.classList = "blog-listing__card";
let cardImage = document.createElement("div");
cardImage.classList = "blog-listing__card__image";
let link = document.createElement("a");
link.setAttribute("href", "#");
let img = document.createElement("img");
img.setAttribute("src", "./Bitmap.svg");
let cardText = document.createElement("div");
cardText.classList = "blog-listing__card__text";
let cardTitle = document.createElement("h2");
cardTitle.innerText = `Naslov ${i}`;
let textLink = document.createElement("a");
textLink.setAttribute("href", "#");
textLink.innerText = `Datum | Autor`;
let textText = document.createElement("p");
textText.innerText = `Opis`;
let topics = document.createElement("div");
topics.classList = "blog-listing__card__topics";
let topicList = document.createElement("ul");
let topicLi = document.createElement("li");
let topicLink = document.createElement("a");
topicLink.setAttribute("href", "#");
topicLink.innerText = `Tagovi`;
let divider = document.createElement("div");
divider.classList = "blog-listing__card__divider";
cardText.appendChild(cardTitle);
cardText.appendChild(textLink);
cardText.appendChild(textText);
link.appendChild(img);
cardImage.appendChild(link);
topicLi.appendChild(topicLink);
topicList.appendChild(topicLi);
topics.appendChild(topicList);
card.appendChild(cardImage);
card.appendChild(cardText);
card.appendChild(topics);
card.appendChild(divider);
bootstrapDiv.appendChild(card);
blog_div.appendChild(bootstrapDiv);
}
}
}
}
}
// blogTagSelect.addEventListener("change", blogFilter);
https://i.stack.imgur.com/M3H2N.png
I tried to optimise the code to work for all numbers of pages but I can't find a good solution
For the pagination numbers and links, try something like this:
//Element to append page numbers
let paginationElem = document.getElementbyId("yourPageElementIdHere")
//Your blogs
let allBlogs = []
//Get number of pages required
let pagesNeeded = allBlogs.length / <number of entries per-page> //May need to be rounded
//Create numbered link for each page. Begin loop at 0 to avoid printing first page as "0"
for(i=1; i < pagesNeeded + 1; i++) {
let pageNum = document.createElement("a").innerHTML = i
pageNum.html = "" //your link to page here
paginationElem.append(pageNum)
}
In case you're wondering how to select and display the relevant articles on each page, you'll need to get the clicked number of the page - as search param (?pageNum=4) in link, perhaps - then create a loop, which will store the correct articles in an array. Something like this should work:
//Your articles in an array
let allBlogs = []
let pageNum = //Get value from search param
// Array for articles to display on desired page
let articlesToDisplay = []
//Set default for first page
let firstArticle = 0
// Set number of first article/starting point for loop
if(pageNum != 0) {
firstArticle = (pageNum - 1) * 10 //or other number of articles per page
}
// Loop through articles, beginning at first article,for desired number of articles (10, here). Push into array.
for(i=firstArticle; i < firstArticle + 10; i++) {
articles.push(allBlogs[i])
}
You can loop through the articlesToDislay array, or create elements in the final loop and have these appended to somewhere in the document.

Grid if box has specific class stop JavaScript

I have a grid with a player, yellow box, and obstacles (.ob) and black boxes. I don't want the player to go in the obstacle squares when I click the 'UP' button.
I was thinking to check if the next class has .ob do not go there. Any suggestions?
let moveCounter = 0;
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 50; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 20) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob")
}
}
var playerTwo = [];
while (playerTwo.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerTwo.indexOf(randomIndex) === -1) {
playerTwo.push(randomIndex);
var drawPtwo = document.getElementById('square' + randomIndex);
$(drawPtwo).addClass("p-1")
}
};
$('#button_up').on('click', function() {
moveCounter += 1;
$pOne = $('.p-1')
var id = $pOne.attr('id')
var idNumber = +id.slice(6);
var idMove = idNumber - 10
var idUpMove = 'square' + idMove;
$pOne.removeClass('p-1');
$('#' + idUpMove).addClass('p-1');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box > div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.p-1 {
background-color: yellow;
}
.ob {
background-color: black;
}
<div id="grid-box"></div>
<div class="move">
<button id="button_up">UP</button><br>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
jsFifddle
Use the following code
$('#button_up').on('click', function() {
moveCounter += 1;
$pOne = $('.p-1')
var id = $pOne.attr('id')
var idNumber = +id.slice(6);
var idMove = idNumber - 10
var idUpMove = 'square' + idMove;
if($('#' + idUpMove).hasClass('ob')){
return false;
}
$pOne.removeClass('p-1');
$('#' + idUpMove).addClass('p-1');
});
Here we check the next selected class having ".ob" class if its return true then we stop the process if it returns false then process continues
if($('#' + idUpMove).hasClass('ob')){
return false;
}
Fiddle

Why with "array[row][col]= usedspace;" cannot increase specific columns and rows depending on the increse each variable (row or column)?

I am Michael and I am new to this forum.
What I want to ask is how through Java Script to make a character 'O' follow your character 'X' in a '.' that is a 20*20 array, but where 'X' pass '.' is replaced with 'O'.
E.g. increase some way the counters inside the if statement that relies in the for loops of row and column of "array a" ?
function start()
{
document.getElementById("wrapper").style="visibility:hidden";
var optionOne = document.getElementById("optionOne");
var display = "";
var txt1 = document.getElementById("txt1");
var mtxt1 = parseInt(txt1.value);
if (mtxt1 == 1)
{
display += "<p>Pen is currently NOT DRAWING</p>";
document.getElementById("wrapper").style="visibility:display";
}
else if (mtxt1 == 2)
{
display += "<p>Pen is DRAWING</p>";
document.getElementById("wrapper").style="visibility:display";
}
optionOne.innerHTML = display;
var button = document.getElementById("getbutton");
button.addEventListener("click",start,false );
//var displaygmb = document.getElementById("displaygmb");
//displaygmb.addEventListener("click", displaygameboard("Gameboard",array,length,arraydisplay),false );
var button2 = document.getElementById("get2button");
button2.addEventListener("click",option2(button2,mtxt1),false );
}
function option2(buttonn,symbolinput)
{
var input = symbolinput;
var usedspace = "O";
var turtle = "X";
var gameboardSymbol = ".";
var clickcountt = buttonn;
var count6 = 1;
var count5 = 1;
var count3 = 1;
var count4 = 1;
var display = "";
clickcountt.onclick = function() {
var optiontwo = document.getElementById("optiontwo");
var display2 = "";
var txt2 = document.getElementById("txt2");
var mtxt2 = parseInt(txt2.value);
if (mtxt2 == 6)
{
count6 += 1;
display2 += "<p>Turtle is moving "+count6+" places down</p>";
}
else if (mtxt2 == 5)
{
count6 -=1;
count5 +=1;
display2 += "<p>Turtle is moving "+count6+" places up</p>";
}
else if (mtxt2 == 3)
{
count3 += 1;
display2 += "<p>Turtle is moving "+count3+" places to the right</p>";
}
else if (mtxt2 == 4)
{
count3 -=1
count4 += 1;
display2 += "<p>Turtle is moving "+count3+" places to the left</p>";
}
optiontwo.innerHTML = display2;
var gameboardsize = 20;
var arraydisplay = document.getElementById("arraydisplay");
var array = new Array (gameboardsize);
var length = array.length;
for (var i = 0; i <= length; i++ )
{
array[i] = new Array(gameboardsize);
}
var arraydisplay = document.getElementById("arraydisplay");
var displaygbd = "<table id=gameb align=center><thead><th>"+"Gameboard"+"</th></thead><tbody>";
for (var row = 1; row <= length; row++)
{
//three += 1;
displaygbd += "<tr>";
for (var col = 1; col <= length; col++)
{
if (input == 1){
//four += 1;
if (((row ==count6)&&(col ==count3)))
{
array[row][col]= turtle;
}
else {
array[row][col]=gameboardSymbol;
}
}
//----------------------------
else if(input == 2)
{
if (((row == count6)&&(col ==count3)))
{
array[row][col]= turtle;
}
/*how to make 'O' follow 'X' by ibncrease the appropriate counter in the if below?*/
else if (((row <= count6)&&(col <=count3)))
{
array[row][col]= usedspace;
}
else if ((((row >= count6)||(col >= count3))))
{
array[row][col]=gameboardSymbol;
}
}//end else if
//----------------------------
displaygbd += "<th>"+array[row][col]+"\xa0"+"</th>";
}
displaygbd += "</tr>";
}
displaygbd += "</tbody></table>";
arraydisplay.innerHTML = displaygbd;
}//end clickout function
}
window.addEventListener("load",start,false);
#charset "ISO-8859-1";
#customers {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 30%;
}
#customers td, #customers th {
border: 1px solid #ddd;
padding: 8px;
}
#customers thead th {
padding-top: 12px;
padding-bottom: 12px;
text-align: center;
background-color: #4CAF50;
color: white;
}
#customers tbody th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: white;
color: black;
text-align:center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Initializing an array</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src ="tutle.js"></script>
</head>
<body>
select your first option
<input id ="txt1" type="text">
<input id = "getbutton" type ="button" value = "your option">
<div id = "optionOne"></div>
<br/>
<div id = "arraydisplay"></div>
<div id="wrapper" >
select your second option
<input id ="txt2" type="text">
<input id = "get2button" type ="button" value = "your option">
<div id = "optiontwo"></div>
</div>
<div id = "counters"></div>
<div id = "optionthree"></div>
</body>
</html>
Sharing a possible solution.
This should get you more than started.
Try running this here itself and let me know if this is ok. I'll add an explanation if required.
The 2 inputs receive the new location of 'X'. text1 receives row number and text2 receives column number. On button press, the corresponding dimension is updated.
var button1 = document.getElementById('getbutton');
var button2 = document.getElementById('get2button');
var textbox1 = document.getElementById('txt1');
var textbox2 = document.getElementById('txt2');
var gridX = 20;//table size length wise
var gridY = 20;//table size width wise
var arrayContainer = document.getElementById('arraydisplay');
var currentX = 1;//initial positions
var currentY = 1;
function init() {
var myTable = document.createElement('table');
myTable.setAttribute("id", "customers");
arrayContainer.appendChild(myTable);
//Creating initial grid
for(var i=0; i<gridX; i++) {
var row = document.createElement('tr');
for(var j=0; j<gridY; j++) {
var text = document.createTextNode('.');
var column = document.createElement('td');
column.appendChild(text);
row.appendChild(column);
}
myTable.appendChild(row);
}
//Setting initial value
document.getElementsByTagName('tr')[currentX-1].getElementsByTagName('td')[currentY-1].innerText = 'X';
}
init();
button1.onclick = clicked;
function clicked() {//1st position changed
var newX = parseInt(textbox1.value);
var newY = parseInt(textbox2.value);
moveTo(newX, newY);
}
button2.onclick = clicked;
function moveTo(newX, newY) {
//Setting old value to 'O'
var char = 'O'
if(newX == 1)
char = '.';
document.getElementsByTagName('tr')[currentX-1].getElementsByTagName('td')[currentY-1].innerText = char;
//Setting new location with 'X'
document.getElementsByTagName('tr')[newX-1].getElementsByTagName('td')[newY-1].innerText = 'X';
//Updating current location of 'X' for future use.
currentX = newX;
currentY = newY;
}
#charset "ISO-8859-1";
#customers {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 30%;
}
#customers td, #customers th {
border: 1px solid #ddd;
padding: 8px;
}
#customers thead th {
padding-top: 12px;
padding-bottom: 12px;
text-align: center;
background-color: #4CAF50;
color: white;
}
#customers tbody th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: white;
color: black;
text-align:center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Initializing an array</title>
<link rel="stylesheet" type="text/css" href="style.css">
<!-- <script src ="turtle.js"></script> -->
</head>
<body>
select your first option
<input id ="txt1" type="text">
<input id = "getbutton" type ="button" value = "your option">
<div id = "optionOne"></div>
<div id="wrapper" >
select your second option
<input id ="txt2" type="text">
<input id = "get2button" type ="button" value = "your option">
<div id = "optiontwo"></div>
</div>
<div id = "counters"></div>
<div id = "optionthree"></div>
<br>
<div id = "arraydisplay"></div>
</body>
<script src ="turtle.js"></script>
</html>

Remove form tags but maintain input functionality

I found a piece of code that works pretty close to how I want. The end result is that when you type something in the input field a list of relevant options appears below based on the text input. You can then click on one of these options instead of having to type of the full string.
The only problem is that when i try and adapt this code to my existing project it breaks because the input field is wrapped in a form. How would I modify this code so that it functions in the exact same way without having to wrap the input tag in a form element? I.e. just have an input field.
(
function()
{
var lookFor = [
"Paris",
"Canada",
"England",
"Scotland",
"Brazil",
"Manila",
"Atlanta"
];
var form = document.getElementById("theForm");
var resultsDiv = document.getElementById("results");
var searchInput = form.search;
// first, position the results:
var node = searchInput;
var x = 0;
var y = 0;
while ( node != null )
{
x += node.offsetLeft;
y += node.offsetTop;
node = node.offsetParent;
}
resultsDiv.style.left = x + "px";
resultsDiv.style.top = (y + 20) + "px";
// now, attach the keyup handler to the search field:
searchInput.onkeyup = function()
{
var txt = this.value.toLowerCase();
if ( txt.length == 0 ) return;
var txtRE = new RegExp( "(" + txt + ")", "ig" );
// now...do we have any matches?
var top = 0;
for ( var s = 0; s < lookFor.length; ++s )
{
var srch = lookFor[s];
if ( srch.toLowerCase().indexOf(txt) >= 0 )
{
srch = srch.replace( txtRE, "<span>$1</span>" );
var div = document.createElement("div");
div.innerHTML = srch;
div.onclick = function() {
searchInput.value = this.innerHTML.replace(/\<\/?span\>/ig,"");
resultsDiv.style.display = "none";
};
div.style.top = top + "px";
top += 20;
resultsDiv.appendChild(div);
resultsDiv.style.display = "block";
}
}
}
// and the keydown handler:
searchInput.onkeydown = function()
{
while ( resultsDiv.firstChild != null )
{
resultsDiv.removeChild( resultsDiv.firstChild );
}
resultsDiv.style.display = "none";
}
}
)();
.searchInput {
width: 200px;
}
#results {
display: none;
position: absolute;
width: 200px;
background-color: lightyellow;
z-index: 10;
}
#results div {
position: absolute;
width: 200px;
height: 20px;
background-color: white;
cursor: pointer;
overflow: hidden;
}
#results div:hover {background: lightblue;}
#results div span {
color: red;
font-weight: bold;
}
<form id="theForm">
Search for: <input name="search" class="searchInput"/>
</form>
<div id="results"></div>
Because in this section of code it relies on the form element to get the input element:
var form = document.getElementById("theForm");
var resultsDiv = document.getElementById("results");
var searchInput = form.search;
Other than that the form isn't needed. As such you could instead make it:
var resultsDiv = document.getElementById("results");
var searchInput = document.getElementsByClassName("searchInput")[0];
Or instead change your input element to have an id of "searchInput" instead of a class and do:
var resultsDiv = document.getElementById("results");
var searchInput = document.getElementById("searchInput");

Dynamically map button with div

I want to link a button with div dynamically using id’s for example.
I have two buttons and two div this is been dynamically created if i click the second button it has to go second div if i click first button it first button has to visible. Using pure vanila javascript.
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function() {
var count = this.value;
if(count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
preview_PageSize = document.getElementById('page');
navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.innerHTML=[1 + totalCount];
spancount.className = "spanCount";
spancount.innerHTML=[1 + totalCount];
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', ['page' + (totalCount)]);
prevPage.appendChild(spancount);
navpageBtn.appendChild(navbutton);
prevPage.setAttribute('id', ['page' + (totalCount)]);
preview_PageSize.childNodes[0]);
totalCount++;
}
inputElement.value="";
document.body.appendChild(fragment);
}
});
Here is the fiddle Link
Kindly help me actually I am trying I am not getting it
Thanks in advance
I would suggest not using a partial id or anything like that to link your elements. Instead, use an attribute specifically created for the purpose. In the following code, I'm using an attribute named data-page which is simply set to the value you're appending to the ids. I also added an event handler which just sets the z-index of all pages to 0, then sets the selected page's z-index to 10.
//create div
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function() {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
preview_PageSize = document.getElementById('page');
navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.setAttribute('data-page', totalCount);
navbutton.innerHTML = [1 + totalCount];
navbutton.addEventListener('click', function (e) {
var el = e.target;
var page = parseInt(el.getAttribute('data-page'), 10);
var allPages = document.querySelectorAll('.preview_windowSize_element');
Array.prototype.forEach.call(allPages, function (pageElement) {
pageElement.style.zIndex = 0;
});
var pageEl = document.querySelector('div[data-page="' + page + '"]');
pageEl.style.zIndex = 10;
});
spancount.className = "spanCount";
spancount.innerHTML = [1 + totalCount];
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', ['page' + (totalCount)]);
prevPage.setAttribute('data-page', totalCount);
prevPage.appendChild(spancount);
navpageBtn.appendChild(navbutton);
preview_PageSize.insertBefore(prevPage, preview_PageSize.childNodes[0]);
totalCount++;
}
inputElement.value = "";
document.body.appendChild(fragment);
}
});
.title_Textbox {
border: 1px solid rgb(152, 152, 152);
width: 230px;
padding: 5px 0 5px 5px;
}
.preview_windowSize {
margin: 15px 15px 15px 15px;
height: 300px;
padding: 5px;
}
.preview_windowSize_element {
position: absolute;
background-color: lightGrey;
border: 1px solid rgb(155, 155, 155);
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
padding: 5px;
width: 93.5%;
height: 300px;
}
<input type="text" class="form-control title_Textbox" id="inputAdd_page" placeholder="No Of Pages">
<div class="preview_windowSize" id="page">
</div>
<div id="pageBtn" class="row pagination_btn">
</div>

Categories