I created a loop to check all the classes in a grid.
I have 4 boxes ( blue, orange, brown and yellow ) the blue box is moving right side in the grid and once it goes into a colored box of the grid they should swap with the yellow spot.
I am working only on the orange and yellow at the moment.
So the loop is checking the classes if found it should swap it.
The problem is that The yellow box goes into the orange one but not vice versa.
Any suggestions?
let moveCounter = 0;
let score = 0;
let obs = 10;
document.getElementById('score').textContent = '0';
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 49; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob1")
}
}
var obstacles = [];
while (obstacles.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob2")
}
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
$(drawPone).addClass("p-0")
}
}
var addPoints = $('#score');
$('#button_right').on('click', function() {
moveCounter += 1;
$pOne = $('.p-0')
$pOneNext = $pOne.next();
$pOne.removeClass('p-0');
$pOneNext.addClass('p-0');
if ($(".p-0").hasClass("ob2")) {
//alert("found")
selectElementAndCheckClass(".ex_box", "def", "ob1", "ob2")
}
});
function selectElementAndCheckClass(element, className) {
let arrOfClasses = $(element).attr('class').split(" ");
for (var i = 0; i < arrOfClasses.length; i++) {
if (arrOfClasses[i] === className) {
alert('HELP'); //SWAP CLASSES
$('.ex_box').removeClass('def');
$('.ob2').addClass('def');
$('ex_box').addClass('ob2');
$('.ob2').removeClass('ob2');
} else {
alert("not found")
}
}
}
#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;
}
.ob1 {
background-color: brown;
}
.ob2 {
background-color: orange;
}
.p-0 {
background-color: blue;
}
.move {
text-align: center;
}
.ex_box {
height: 32px;
width: 32px;
border: solid 2px black;
}
.def {
background-color: yellow;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box">
</div>
<div class="move">
<button id="button_right">right</button><br>
</div>
<div class="ex_box def" id="score">
</div>
Supposed that you want to swap color then:
$('.ob2').addClass('def');
$('.ob2').removeClass('ob2');
$('.ex_box').addClass('ob2');
$('.ex_box').removeClass('def');
Since your .def has yellow color and .ob2 has orange color.
Logic is let the orange have yellow color then remove the orange from it. Then let the yellow color has orange color then remove the yellow one.
Snippet:
let moveCounter = 0;
let score = 0;
let obs = 10;
document.getElementById('score').textContent = '0';
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 49; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob1")
}
}
var obstacles = [];
while (obstacles.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob2")
}
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
$(drawPone).addClass("p-0")
}
}
var addPoints = $('#score');
$('#button_right').on('click', function() {
moveCounter += 1;
$pOne = $('.p-0')
$pOneNext = $pOne.next();
$pOne.removeClass('p-0');
$pOneNext.addClass('p-0');
if ($(".p-0").hasClass("ob2")) {
//alert("found")
selectElementAndCheckClass(".ex_box", "def", "ob1", "ob2")
}
});
function selectElementAndCheckClass(element, className) {
let arrOfClasses = $(element).attr('class').split(" ");
for (var i = 0; i < arrOfClasses.length; i++) {
if (arrOfClasses[i] === className) {
alert('HELP'); //SWAP CLASSES
$('.ob2').addClass('def');
$('.ob2').removeClass('ob2');
$('.ex_box').addClass('ob2');
$('.ex_box').removeClass('def');
} else {
alert("not found")
}
}
}
#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;
}
.ob1 {
background-color: brown;
}
.ob2 {
background-color: orange;
}
.p-0 {
background-color: blue;
}
.move {
text-align: center;
}
.ex_box {
height: 32px;
width: 32px;
border: solid 2px black;
}
.def {
background-color: yellow;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box">
</div>
<div class="move">
<button id="button_right">right</button><br>
</div>
<div class="ex_box def" id="score">
</div>
Related
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.
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
My homework was to create a scipt that connects two marked cells of a table. My solution works fine, but the result line is a bit disproportionate.
As you can see, the last row is 4-cells long while all other rows are 3-cells long. But I'd like the middle part of a line to be the longest. Like this:
How to get the desired result and not make the code too complicated. The code itself:
function connectThem() {
if (markedCells.length == 2) {
y_distance = markedCells[0][0] - markedCells[1][0];
y_distance = Math.abs(y_distance) + 1; // vertial distance
x_distance = markedCells[0][1] - markedCells[1][1];
x_distance = Math.abs(x_distance) + 1; // horizontal distance
if (x_distance > y_distance) { // if horizontal distance greater than vertical distance
x_distance -= 0;
alert("horizontal connection");
totalRows = y_distance;
for (var row = 0; row < y_distance; row++) {
thisRowLength = Math.floor(x_distance / totalRows);
for (var c = 0; c < thisRowLength; c++) {
document.getElementById('cell-' + markedCells[0][0] + '-' + markedCells[0][1]).style.backgroundColor = "red";
markedCells[0][1] = parseInt(markedCells[0][1]) + 1;
}
markedCells[0][0] = parseInt(markedCells[0][0]) + 1;
totalRows -= 1; // vertical remaining
x_distance -= thisRowLength; // horizontal remaining
}
} else {
y_distance -= 0;
alert("vertical or horizontal connection");
totalCols = x_distance;
for (var col = 0; col < x_distance; col++) {
thisColLength = Math.floor(y_distance / totalCols);
for (var r = 0; r < thisColLength; r++) {
document.getElementById('cell-' + markedCells[0][0] + '-' + markedCells[0][1]).style.backgroundColor = "red";
markedCells[0][0] = parseInt(markedCells[0][0]) + 1;
}
markedCells[0][1] = parseInt(markedCells[0][1]) + 1;
totalCols -= 1;
y_distance -= thisColLength;
}
}
alert("x distance: " + x_distance + " y distance: " + y_distance);
} else {
alert("Can't connect " + markedCells.length + " cells together :-(")
}
}
var htmlElements = ""; // storing the whole table here
for (var r = 1; r < 41; r++) { // creating the table row by row
htmlElements += '<tr>';
for (var c = 1; c < 61; c++) { // and column by column
htmlElements += '<td class="tCell white" id="cell-' + r.toString() + '-' + c.toString() + '"></td>';
}
htmlElements += '</tr>'
}
var theTable = document.getElementById("tab");
theTable.innerHTML = htmlElements;
var allTableCells = document.querySelectorAll("td"); // adding all cells to an array
var markedCells = [] // storing marked cells here
for (var i = 0; i < allTableCells.length; i++) {
allTableCells[i].addEventListener("click", function() { // when click any cell
let stringID = this.id.split('-');
if (this.className == "tCell white") {
this.className = "tCell red";
markedCells.push([stringID[1], stringID[2]]);
} else {
this.className = "tCell white";
let index = markedCells.indexOf([stringID[1], stringID[2]]);
markedCells.splice(index, 1);
}
console.log(markedCells);
});
}
body {
background-color: #333;
}
#workspace {
position: absolute;
width: 900px;
height: 600px;
background-color: whitesmoke;
top: 50%;
left: 50%;
margin-left: -450px;
margin-top: -300px;
}
table,
tr,
td {
border: 1px solid black;
border-collapse: collapse;
padding: 0;
}
table {
width: 900px;
height: 600px;
}
.red {
background: red;
color: white;
}
.white {
background: white;
color: black;
}
#btn {
position: absolute;
width: 100px;
top: 50px;
left: 50%;
margin-left: -50px;
}
<div id="workspace">
<table id="tab">
</table>
</div>
<button id="btn" onclick="connectThem()">Connect!</button>
I am making Snake and Ladder game using JavaScript. I want to insert the game board generated from the create Board(dimension) function into a div, but [object Object] is what is appears.
var gameBoard = {
createBoard: function(dimension) {
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
document.body.appendChild(table);
output = gameBoard.enumerateBoard(table);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
len,
cells,
real,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
len = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < len; i++) {
if (odd == true) {
real = --size + rowCounter - i;
} else {
real = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = real;
rowCounter++;
}
}
return gameBoard;
}
};
//board.createBoard(10);
document.getElementById("div1").innerHTML = gameBoard.createBoard(10);
td {
border-radius: 10px;
width: 55px;
height: 55px;
line-height: 55px;
text-align: center;
border: 0px solid #FFFFFF;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
td:hover {
background: LightCyan !important;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="StyleSheet1.css" rel="stylesheet" />
</head>
<body>
<div id="div1"></div>
<script src="JavaScript1.js"></script>
</body>
</html>
I need help on how to solve this problem. Thanks in advance.
All you wanted was the gameBoard to be appended to the div#div1, correct?
Added mount parameter to createBoard() function
var mount is a selector that will be referenced as the element to which the table element will be appended to.
Comments accompany changes in the code.
I added a border around #div1 to show that the gameBoard has been successfully appended to #div1
var gameBoard = { //===============▼---▼====[This is can be any selector]
createBoard: function(dimension, mount) {
//==▼------------------------------------▼====[Object mount]
var mount = document.querySelector(mount);
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
//▼---------------------▼====[Object table append to Object mount]
mount.appendChild(table);
output = gameBoard.enumerateBoard(table);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
len,
cells,
real,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
len = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < len; i++) {
if (odd == true) {
real = --size + rowCounter - i;
} else {
real = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = real;
rowCounter++;
}
}
return gameBoard;
}
};
/*board.createBoard(10);
[On window load call createBoard with 10 rows and mount it to #div1]
▼----------------------------▼===============================*/
window.onload = (function(e) {
gameBoard.createBoard(10, '#div1');
});
td {
border-radius: 10px;
width: 55px;
height: 55px;
line-height: 55px;
text-align: center;
border: 0px solid #FFFFFF;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
td:hover {
background: LightCyan !important;
cursor: pointer;
}
#div1 {
border: 3px inset #0FF;
border-radius: 10px;
width: -moz-fit-content;
width: -webkit-fit-content;
width: fit-content;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="div1"></div>
</body>
</html>
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;
}