Sorting large number of DOM elements - javascript

I'm pulling a large number of nodes from sharepoint list and I'll try to sort them into a html table hopefully in orderly fashion. The way i need to do this is I need to split these z:rows into 5 different tables. Example should be self explanatory: https://jsfiddle.net/jse21z9d/1/
$(document).ready(function(){
$('#execB').click(function(){
$('.myUl li').each(function(){
var liText = $(this).text().toLowerCase();
var newliText = liText.replace(/[{()}]/g, "");
var textArray = newliText.split(/[,]/);
console.log(textArray);
$(textArray).each(function(index){
switch(true){
case (textArray[index].indexOf('pol') != -1):
$('#polDiv').append(liText+"<br>");
break;
case (textArray[index].indexOf('uk') != -1)
|| (textArray[index].indexOf('ire') != -1):
$('#ukDiv').append(liText+"<br>");
break;
case (textArray[index].indexOf('ger') != -1):
$('#gerDiv').append(liText+"<br>");
break;
case (textArray[index].indexOf('san') != -1):
$('#sanDiv').append(liText+"<br>");
break;
}
});
});
});
});
so that's what i got so far, and I'm wondering maybe there is a better way to do this as I think this code I wrote might slow the entire load up a lot if we are talking about 1000+ z:rows(li in this case) to go through?

I modified your own code with the following:
- Less appends: The iterations generate a string instead of multiple appends thus less actions are done over the DOM.
- Less searches: Even though a search by ID is generally an easy search. Its still better to execute the it once, and append the generated string.
Source:
https://jsfiddle.net/mamtkjw4/
$(document).ready(function(){
$('#execB').click(function(){
var polStr = "";
var ukStr = "";
var gerStr = "";
var sanStr = "";
$('.myUl li').each(function(){
var liText = $(this).text().toLowerCase();
var newliText = liText.replace(/[{()}]/g, "");
var textArray = newliText.split(/[,]/);
console.log(textArray);
$(textArray).each(function(index){
switch(true){
case (textArray[index].indexOf('pol') != -1):
polStr = polStr + liText+"<br>";
break;
case (textArray[index].indexOf('uk') != -1)
|| (textArray[index].indexOf('ire') != -1):
ukStr = ukStr + liText+"<br>";
break;
case (textArray[index].indexOf('ger') != -1):
gerStr = gerStr + liText+"<br>";
break;
case (textArray[index].indexOf('san') != -1):
sanStr = sanStr + liText+"<br>";
break;
}
});
});
if (polStr) {
$('#polDiv').append(polStr+"<br>");
}
if (ukStr) {
$('#ukDiv').append(ukStr+"<br>");
}
if (gerStr) {
$('#gerDiv').append(gerStr+"<br>");
}
if (sanStr) {
$('#sanDiv').append(sanStr+"<br>");
}
});
});
.holders{
background: gray;
width: 100px;
height: 200px;
margin-left: 15px;
margin-bottom: 15px;
float: left;
}
<button id="execB">execB</button>
<ul class="myUl">
<li>(UK/IRE, POL)</li>
<li>(UK/IRE)</li>
<li>(POL)</li>
<li>(SAN)</li>
<li>(GER, POL)</li>
<li>(GER)</li>
<li>(SAN, UK/IRE)</li>
</ul>
<div id="gerDiv" class="holders"><p>german div:</p><ul></ul></div>
<div id="ukDiv" class="holders"><p>uk/ire div:</p><ul></ul></div>
<div id="polDiv" class="holders"><p>pol div:</p><ul></ul></div>
<div id="sanDiv" class="holders"><p>san div:</p><ul></ul></div>

This is about as short and sweet as it gets. Also, this will multiply your text entry every time you click, so you can see how it handles as it gets larger.
$(document).ready(function() {
var clickCount = 1;
$("#execB").on("click", function() {
clickCount++;
$(this).text("Count("+clickCount+")");
$(".myUl li").each(function() {
var liText = new Array(clickCount).join($(this).text().toLowerCase() + "\n"),
textArray = liText.replace(/[{()}]/g, "").split(/[,]/);
$(textArray).each(function(i) {
switch (!0) {
case -1 != textArray[i].indexOf("pol"):
$("#polDiv").append(liText + "<br>");
break;
case -1 != textArray[i].indexOf("uk") || -1 != textArray[i].indexOf("ire"):
$("#ukDiv").append(liText + "<br>");
break;
case -1 != textArray[i].indexOf("ger"):
$("#gerDiv").append(liText + "<br>");
break;
case -1 != textArray[i].indexOf("san"):
$("#sanDiv").append(liText + "<br>")
}
});
});
$(document).scrollTop($(document).height());
})
});
.holders{
background: gray;
width: 100px;
height: 200px;
margin-left: 15px;
margin-bottom: 15px;
float: left;
}
button { position: fixed; top: .6em; }
ul { margin-top: 2.25em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="execB">execB</button>
<ul class="myUl">
<li>(UK/IRE, POL)</li>
<li>(UK/IRE)</li>
<li>(POL)</li>
<li>(SAN)</li>
<li>(GER, POL)</li>
<li>(GER)</li>
<li>(SAN, UK/IRE)</li>
</ul>
<div id="gerDiv" class="holders"><p>german div:</p><ul></ul></div>
<div id="ukDiv" class="holders"><p>uk/ire div:</p><ul></ul></div>
<div id="polDiv" class="holders"><p>pol div:</p><ul></ul></div>
<div id="sanDiv" class="holders"><p>san div:</p><ul></ul></div>
Also it will auto scroll so you can just keep pushing the button ...
If it helps any, on system I'm currently on [HP ProBook 650 G1 Win7 Pro64], in Chrome, it didn't start slowing down till count of clicks on button was around 100, on FF around 95 and on IE Edge, also around 100. That would be that ul text 100 times

Related

Using a text string search function on a page, is there a way to have the search ignore a specific div?

This is my search function, which works fine for my purposes.
var TRange = null;
function findString(str) {
if (parseInt(navigator.appVersion) < 4) return;
var strFound;
if (window.find) {
// CODE FOR BROWSERS THAT SUPPORT window.find
strFound = self.find(str);
if (strFound && self.getSelection && !self.getSelection().anchorNode) {
strFound = self.find(str)
}
if (!strFound) {
strFound = self.find(str, 0, 1)
while (self.find(str, 0, 1)) continue
}
} else if (navigator.appName.indexOf("Microsoft") != -1) {
// EXPLORER-SPECIFIC CODE
if (TRange != null) {
TRange.collapse(false)
strFound = TRange.findText(str)
if (strFound) TRange.select()
}
if (TRange == null || strFound == 0) {
TRange = self.document.body.createTextRange()
strFound = TRange.findText(str)
if (strFound) TRange.select()
}
} else if (navigator.appName == "Opera") {
alert("Opera browsers not supported, sorry...")
return;
}
if (!strFound) alert("String '" + str + "' not found!")
return;
};
document.getElementById('f1').onsubmit = function() {
const marquee = document.querySelector('#marquee');
let innerHTML = marquee.innerHTML;
marquee.innerHTML = '';
let found = findString(this.t1.value);
marquee.innerHTML = innerHTML;
return false;
};
This is the div I would like to have my search function ignore, if possible:
<div style="background-color: lightyellow; height:20px; border: 1.5px; border-style: groove solid solid groove; padding-top: 1px; margin-right: 10px; width: 700px;" class="noselect" id="marquee"></div>
My reason for wanting to do this is, whenever someone attempts to search the page for something rendered in my marquee div, the page locks up and becomes unresponsive, till the tab is closed and the page is reopened. So I'm assuming if I somehow told the search function to ignore that particular div, the page would no longer crash, it would just return the response, that "String not found". If anyone has some advice on how I can go about fixing this, it would be much appreciated. Thank you.
This is how I'm rendering my marquee:
"use strict";
function tick() {
const element = /*#__PURE__*/React.createElement("marquee", {
behavior: "scroll",
bgcolor: "lightyellow",
loop: "-1",
width: "700px"
}, " ", /*#__PURE__*/React.createElement("font", {
color: "blue"
}, " ", /*#__PURE__*/React.createElement("strong", null, "Today is: ", new Date().toDateString(), " and the current time is: ", new Date().toLocaleTimeString(), " "), " "), " ");
ReactDOM.render(element, document.getElementById("marquee"));
}
setInterval(tick, 1000);
A somewhat hacky idea, but maybe it will work in your situation, would be to remove the innerHTML of the div, do the find then put the innerHTML back again. It may depend on the exact structure whether this is safe to do.
const marquee = document.querySelector('#marquee');
let innerHTML = marquee.innerHTML;
marquee.innerHTML = '';
let found = findString('whatever');
marquee.innerHTML = innerHTML;
It would be preferable of course to find out why the search on a string in the marquee locks things up and cure that.

Javascript Can Push() and Pop() and Image Replacement Work within an Array

Can Push() and Pop() and Image Replacement Work within an Array?
8th Gr math teacher attempting to create a slide show of question images that pop() and push() through an image array based on student responses. If the student answers correctly the question is popped, but if they answer incorrectly it is added to the end of the queue. Additionally, since deleting elements in the DOM is bad, I am replacing the current image's src and id with that of the next element in queue. The array is then popped and pushed along, but whenever I enter in the incorrect answer twice the same image appears.
I have moved the global variable that holds the array, domEls, inside of the function retrieveAnsForImage to force it to randomize the images in the array. When I do this, the images change correctly so I believe it is the push() and pop() commands.
I included a snippet that doesn't work here, but works like a champ in Notepad ++. I just took a crash course in Javascript, HTML and CSS last month on Codecademy, I am very new to this. Thank you for reading.
//Jquery
$(document).ready(function() {
$(function() {
$('img.card').on('contextmenu', function(e) {
e.preventDefault();
//alert(this.id);
openPrompt(this.id);
});
});
});
//Provide and Shuffle array function
function shuffleImgs() {
var imgArr = [
"image1",
"image2",
"image3",
"image4",
"image5",
"image6",
"image7",
"image8",
"image9"
];
var currentIndex = imgArr.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = imgArr[currentIndex];
imgArr[currentIndex] = imgArr[randomIndex];
imgArr[randomIndex] = temporaryValue;
}
alert("shuffle");
return imgArr;
}
function arrStack() {
var imgArr = shuffleImgs();
//Map over the array to create Dom elements
var domElements = imgArr.map(function (imgName, index) {
var cardDiv = document.createElement('div');
var cardImage = document.createElement('img');
//Add img id and class
cardImage.id = imgName;
cardImage.classList.add('card');
//Set img source
cardImage.src = `images/${imgName}.jpg`;
//Put it all together
cardDiv.appendChild(cardImage);
return cardDiv;
});
//this notation to call nested function for Global var stack
this.nDomElements = function () {
stackDomEl = domElements;
return stackDomEl;
}
//Display last element in array
//this notation to call the nested function from outside the function
this.nDisplayLastArr = function displayLastArr() {
var lastImgArr = domElements[domElements.length - 1];
//alert(lastImgArr);
//Append the elements to the DOM
var modal = document.querySelector('div.modal');
modal.appendChild(lastImgArr);
return lastImgArr; //Use brackets when your are returning more than one variable
}
}
//Function called from Jquery to open prompt to answer question
function openPrompt(imageId) {
var userAns = prompt("Please enter your answer below and click OK");
if (userAns == null || userAns == "") {
alert("User cancelled the prompt. Exit and please try again!");
}
else {
/*Vain hope that I can pass imageId from click event through the user prompt
to the answer checking function retrieveAnsForImage*/
retrieveAnsForImage(imageId, userAns); //out of scope?
}
}
//Global variable
func = new arrStack();
window.domEls = func.nDomElements();
//Compare user responses with the question image by use of the click image id
function retrieveAnsForImage(imageId, userAns) {
//Change these variables to the correct answer whenever this website is reused in other assignments
var ansImage1 = "1";
var ansImage2 = "2";
var ansImage3 = "3";
var ansImage4 = "4";
var ansImage5 = "5";
var ansImage6 = "6";
var ansImage7 = "7";
var ansImage8 = "8";
var ansImage9 = "9";
//Give students a second chance to retry a question
//var hintCounter = 0; //include a while statement above the if statements to allow students a retry
/*Compare user response with correct case answer and correct clicked image.
Students may enter the right answer for the wrong image hence the &&.
Images will always be refered to as image1, image2, etc.*/
if (userAns === ansImage1 && imageId === "image1") {
correctAns(imageId);
}
else if (userAns === ansImage2 && imageId === "image2") {
correctAns(imageId);
}
else if (userAns === ansImage3 && imageId === "image3") {
correctAns(imageId);
}
else if (userAns === ansImage4 && imageId === "image4") {
correctAns(imageId);
}
else if (userAns === ansImage5 && imageId === "image5") {
correctAns(imageId);
}
else if (userAns === ansImage6 && imageId === "image6") {
correctAns(imageId);
}
else if (userAns === ansImage7 && imageId === "image7") {
correctAns(imageId);
}
else if (userAns === ansImage8 && imageId === "image8") {
correctAns(imageId);
}
else if (userAns === ansImage9 && imageId === "image9") {
correctAns(imageId);
}
else {
window.alert("Incorrect Answer");
incorrectAns();
}
function correctAns(){
//Second to last element in array
var SecLastElArr = domEls[domEls.length - 2];
//Pull image id from second to last element in array
var nextImgId = SecLastElArr.querySelector("div > img").id;
//Pull image id from document
var imgId = document.querySelector("div > img").id;
//Student incorrect answer change im
document.getElementById(imgId).src = `images/${nextImgId}.jpg`;
document.getElementById(imgId).id = nextImgId;
domEls.pop();
//Think about when the array is completely gone
//while domEls.length !== 0;
}
function incorrectAns(){
//Last element in array
var LastElArr = domEls[domEls.length - 1];
//Second to last element in array
var SecLastElArr = domEls[domEls.length - 2];
//Pull image id from second to last element in array
var nextImgId = SecLastElArr.querySelector("div > img").id;
//Pull image id from document
var imgId = document.querySelector("div > img").id;
//Student incorrect answer change image src and id to next element in queue
document.getElementById(imgId).src = `images/${nextImgId}.jpg`;
document.getElementById(imgId).id = nextImgId;
//Remove last element in array
domEls.pop();
//move the last element to the first element in the array for another attempt
domEls.push(LastElArr);
alert(domEls.length);
}
}
function overlay() {
var el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
#overlay {
visibility: hidden;
position: absolute;
left: 0px;
top: 0px;
width:100%;
height:100%;
text-align:center;
z-index: 1000;
background-color: rgba(0,191, 255, 0.8);
}
#overlay div {
width:70%;
margin: 10% auto;
background-color: #fff;
border:1px solid #000;
padding:15px;
text-align: center;
}
body {
height:100%;
margin:0;
padding:0;
}
#close-img {
float: right;
clear: right;
width: 30px;
height: 30px;
bottom: 0;
right: 0;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<span> "Left click to view any questions. Right click (two finger tap) to answer the question and claim the tile. Each player must claim 4 tiles to successfully complete the assignment."</span>
<link href="https://fonts.googleapis.com/css?family=Oswald:300,700|Varela+Round" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="Stack Rnd Temp.css">-->
<script type="text/javascript" src="Stack Rnd Temp.js"></script>
<script src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="StackRndTempjq.js"></script>
</head>
<body>
<div class="title">
<h1></h1>
</div>
<div id="gameboard"> <!--Container for all nine divs-->
<a href='#' onclick='overlay()'>Click here to show the overlay</a>
</div>
<div class="modal" id="overlay">
<p> "Right click to answer the question"</p>
<script>
func = new arrStack();
func.nDisplayLastArr();
</script>
<img src="images/close.png" id="close-img" onclick="overlay()">
</div>
</body>
</html>
Your issue is that pop removes the last element from the array while push adds the element to end of the array.
What you probably want to do is use shift to remove the the first element from the array and pop it back to the end if the answer is wrong.
Alternately, you could pop the last element and use unshift to insert back into the beginning of you want to work in the other direction.
Here's a quick mockup without images.
var currentTest = null;
function getTest() {
$('#answer').html("").hide();
if (tests.length > 0) {
currentTest = tests.shift(); // remove the first question
$('#question').fadeIn(450).html(currentTest.q);
return currentTest;
} else {
$('#answer').html("Finished").fadeIn(500);
$('#btnCorrect').unbind();
$('#btnWrong').unbind();
}
}
var tests = [];
for (var i = 0; i < 5; i++) {
var question = "Question " + i;
var answer = "Answer " + i;
tests.push({
q: question,
a: answer
});
}
$('#btnCorrect').click(function() {
$('#question').hide();
$('#answer').fadeIn(450).html("Correct!");
window.setTimeout(getTest, 750);
});
$('#btnWrong').click(function() {
$('#question').hide();
tests.push(currentTest); // put the question back in the array
$('#answer').fadeIn(450).html("Incorrect!");
window.setTimeout(getTest, 750);
});
$(document).ready(function() {
getTest();
})
* {
font-family: arial;
}
#panel {
height: 50px;
}
#answer {
border: 1px solid #cccccc;
background: #dedede;
width: 400px;
}
#question {
border: 1px solid #999999;
background: #dedede;
width: 400px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="panel">
<div id="answer"></div>
<div id="question"></div>
</div>
<input id="btnCorrect" value="Mock Correct Answer" type="button">
<input id="btnWrong" value="Mock Wrong Answer" type="button">
</body>
</html>

How to create an arcade style name input in Javascript?

I'm trying to create an arcade style name input for a highscore list. I'd like it to work using just the arrow keys on the keyboard, so up/down arrow for character selection and left/right for input box selection. I'm using a MakeyMakey for this project, so I want to keep user/keyboard interaction as minimal as possible.
Right now I'm rendering select boxes containing the entire alphabet in option tags, however, a select box always drops down, and your choice has to be confirmed using Enter or a mouse-click.
I'd like to stay at least a little semantically correct on the input, so I'm thinking 3 inputs that each select one letter, then concatenating these in a hidden input field, of which I can pass the value to Rails.
I'm using the following jQuery-plugin (from: http://ole.michelsen.dk/blog/navigate-form-fields-with-arrow-keys.html) to navigate between select boxes using the left/right arrow keys.
(function($) {
$.fn.formNavigation = function() {
$(this).each(function() {
$(this).find('select').on('keyup', function(e) {
switch (e.which) {
case 39:
$(this).closest('td').next().find('select').focus();
break;
case 37:
$(this).closest('td').prev().find('select').focus();
}
});
});
};
})(jQuery);
What I want to implement next is three input boxes that have the entire (infinitely looped) alphabet as choices, navigable by up/down arrow. I'd rather not type out the entire alphabet so I want to generate the options for each box and probably bind a keyhandler somewhere. How would I generate such an input box and integrate the required code into my existing script?
Screenshots
This is how it looks now:
Ideally, it will look like this:
I think Banana had a great answer, but I wanted to try making it look a little more expressive.
KEYCODES = { left: 37, up: 38, right: 39, down: 40 };
$('.cyclic_input').on('keydown',function(ev){
input = $(this);
val = $(this).text();
switch (ev.keyCode) {
case KEYCODES.right:
input.next().focus();
break;
case KEYCODES.left:
input.prev().focus();
break;
case KEYCODES.up:
input.text(advanceCharBy(val, 1));
break;
case KEYCODES.down:
input.text(advanceCharBy(val, -1));
break;
default:
if (ev.keyCode >= 65 && ev.keyCode <= 65 + 26) {
input.text(String.fromCharCode(ev.keyCode));
input.next().focus();
}
};
ev.preventDefault();
});
advanceCharBy = function(char, distance) {
oldCode = char.charCodeAt(0);
newCode = 65 + (oldCode - 65 + 26 + distance) % 26;
return String.fromCharCode(newCode);
};
.cyclic_input {
float: left;
padding: 1rem;
font-size: 5rem;
position: relative;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.cyclic_input:before,
.cyclic_input:after {
display: block;
position: absolute;
left: 50%;
font-size: 1rem;
transform: translateX(-50%);
}
.cyclic_input:before {
content: '▲';
top: 0;
}
.cyclic_input:after {
content: '▼';
bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cyclic_input" tabindex="0">A</div>
<div class="cyclic_input" tabindex="0">A</div>
<div class="cyclic_input" tabindex="0">A</div>
Forked Codepen but also works fine in the snippet. My thoughts:
I don't know keycodes, I don't want to know keycodes.
We're not interested in keypresses on the whole document, just the initials inputs.
If you must have branching logic, be clear how many paths there are, one.
If these are our form inputs, then they deserve at least tabindex. In reality I would use <input>s but that would have just added a bunch of CSS to the demo.
The whole point is keyboard support. I'm pretty sure we need to handle the case where a user types a letter.
Let's not jerk the page around when someone presses an arrow key.
Its rather simple, all you need is a few calculations:
if you have any questions, feel free to ask.
$(function() {
$(document).on("keydown", function(ev) {
if (ev.keyCode == 39) {
var idx = $('.active').index();
var next_idx = (+idx + 1) % $('.cyclic_input').length;
$('.active').removeClass('active');
$('.cyclic_input').eq(next_idx).addClass('active');
}
if (ev.keyCode == 37) {
var idx = $('.active').index();
var next_idx = ((+idx - 1) + $('.cyclic_input').length) % $('.cyclic_input').length;
$('.active').removeClass('active');
$('.cyclic_input').eq(next_idx).addClass('active');
}
if (ev.keyCode == 38) {
var char = $(".active").text();
var ascii = char.charCodeAt(0);
var nextAscii = 65 + (ascii + 1 - 65) % 26;
$(".active").text(String.fromCharCode(nextAscii));
}
if (ev.keyCode == 40) {
var char = $(".active").text();
var ascii = char.charCodeAt(0);
var nextAscii = 65 + ((ascii - 1 - 65) + 26) % 26;
$(".active").text(String.fromCharCode(nextAscii));
}
});
});
.cyclic_input {
width: 50px;
height: 50px;
display: inline-block;
border: 5px solid red;
font-size: 3em;
}
.active {
border-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cyclic_input active">A</div>
<div class="cyclic_input">A</div>
<div class="cyclic_input">A</div>
and here is a Fiddle
PS: the snippet here doesnt work too well, but if you test the code or check the jsfiddle it will work fine.

Checking function for sliding puzzle javascript

I created a sliding puzzle with different formats like: 3x3, 3x4, 4x3 and 4x4. When you run my code you can see on the right side a selection box where you can choose the 4 formats. The slidingpuzzle is almost done. But I need a function which checks after every move if the puzzle is solved and if that is the case it should give out a line like "Congrantulations you solved it!" or "You won!". Any idea how to make that work?
In the javascript code you can see the first function loadFunc() is to replace every piece with the blank one and the functions after that are to select a format and change the format into it. The function Shiftpuzzlepieces makes it so that you can move each piece into the blank space. Function shuffle randomizes every pieces position. If you have any more question or understanding issues just feel free to ask in the comments. Many thanks in advance.
Since I don't have enough reputation I will post a link to the images here: http://imgur.com/a/2nMlt . These images are just placeholders right now.
Here is the jsfiddle:
http://jsfiddle.net/Cuttingtheaces/vkyxgwo6/19/
As always, there is a "hacky", easy way to do this, and then there is more elegant but one that requires significant changes to your code.
Hacky way
To accomplish this as fast and dirty as possible, I would go with parsing id-s of pieces to check if they are in correct order, because they have this handy pattern "position" + it's expected index or "blank":
function isFinished() {
var puzzleEl = document.getElementById('slidingpuzzleContainer').children[0];
// convert a live list of child elements into regular array
var pieces = [].slice.call(puzzleEl.children);
return pieces
.map(function (piece) {
return piece.id.substr(8); // strip "position" prefix
})
.every(function (id, index, arr) {
if (arr.length - 1 == index) {
// last peace, check if it's blank
return id == "blank";
}
// check that every piece has an index that matches its expected position
return index == parseInt(id);
});
}
Now we need to check it somewhere, and naturally the best place would be after each move, so shiftPuzzlepieces() should be updated to call isFinished() function, and show the finishing message if it returns true:
function shiftPuzzlepieces(el) {
// ...
if (isFinished()) {
alert("You won!");
}
}
And voilà: live version.
How would I implement this game
For me, the proper way of implementing this would be to track current positions of pieces in some data structure and check it in similar way, but without traversing DOM or checking node's id-s. Also, it would allow to implement something like React.js application: onclick handler would mutate current game's state and then just render it into the DOM.
Here how I would implement the game:
/**
* Provides an initial state of the game
* with default size 4x4
*/
function initialState() {
return {
x: 4,
y: 4,
started: false,
finished: false
};
}
/**
* Inits a game
*/
function initGame() {
var gameContainer = document.querySelector("#slidingpuzzleContainer");
var gameState = initialState();
initFormatControl(gameContainer, gameState);
initGameControls(gameContainer, gameState);
// kick-off rendering
render(gameContainer, gameState);
}
/**
* Handles clicks on the container element
*/
function initGameControls(gameContainer, gameState) {
gameContainer.addEventListener("click", function hanldeClick(event) {
if (!gameState.started || gameState.finished) {
// game didn't started yet or already finished, ignore clicks
return;
}
if (event.target.className.indexOf("piece") == -1) {
// click somewhere not on the piece (like, margins between them)
return;
}
// try to move piece somewhere
movePiece(gameState, parseInt(event.target.dataset.index));
// check if we're done here
checkFinish(gameState);
// render the state of game
render(gameContainer, gameState);
event.stopPropagation();
return false;
});
}
/**
* Checks whether game is finished
*/
function checkFinish(gameState) {
gameState.finished = gameState.pieces.every(function(id, index, arr) {
if (arr.length - 1 == index) {
// last peace, check if it's blank
return id == "blank";
}
// check that every piece has an index that matches its expected position
return index == id;
});
}
/**
* Moves target piece around if there's blank somewhere near it
*/
function movePiece(gameState, targetIndex) {
if (isBlank(targetIndex)) {
// ignore clicks on the "blank" piece
return;
}
var blankPiece = findBlankAround();
if (blankPiece == null) {
// nowhere to go :(
return;
}
swap(targetIndex, blankPiece);
function findBlankAround() {
var up = targetIndex - gameState.x;
if (targetIndex >= gameState.x && isBlank(up)) {
return up;
}
var down = targetIndex + gameState.x;
if (targetIndex < ((gameState.y - 1) * gameState.x) && isBlank(down)) {
return down;
}
var left = targetIndex - 1;
if ((targetIndex % gameState.x) > 0 && isBlank(left)) {
return left;
}
var right = targetIndex + 1;
if ((targetIndex % gameState.x) < (gameState.x - 1) && isBlank(right)) {
return right;
}
}
function isBlank(index) {
return gameState.pieces[index] == "blank";
}
function swap(i1, i2) {
var t = gameState.pieces[i1];
gameState.pieces[i1] = gameState.pieces[i2];
gameState.pieces[i2] = t;
}
}
/**
* Handles form for selecting and starting the game
*/
function initFormatControl(gameContainer, state) {
var formatContainer = document.querySelector("#formatContainer");
var formatSelect = formatContainer.querySelector("select");
var formatApply = formatContainer.querySelector("button");
formatSelect.addEventListener("change", function(event) {
formatApply.disabled = false;
});
formatContainer.addEventListener("submit", function(event) {
var rawValue = event.target.format.value;
var value = rawValue.split("x");
// update state
state.x = parseInt(value[0], 10);
state.y = parseInt(value[1], 10);
state.started = true;
state.pieces = generatePuzzle(state.x * state.y);
// render game
render(gameContainer, state);
event.preventDefault();
return false;
});
}
/**
* Renders game's state into container element
*/
function render(container, state) {
var numberOfPieces = state.x * state.y;
updateClass(container, state.x, state.y);
clear(container);
var containerHTML = "";
if (!state.started) {
for (var i = 0; i < numberOfPieces; i++) {
containerHTML += renderPiece("", i) + "\n";
}
} else if (state.finished) {
containerHTML = "<div class='congratulation'><h2 >You won!</h2><p>Press 'Play!' to start again.</p></div>";
} else {
containerHTML = state.pieces.map(renderPiece).join("\n");
}
container.innerHTML = containerHTML;
function renderPiece(id, index) {
return "<div class='piece' data-index='" + index + "'>" + id + "</div>";
}
function updateClass(container, x, y) {
container.className = "slidingpuzzleContainer" + x + "x" + y;
}
function clear(container) {
container.innerHTML = "";
}
}
/**
* Generates a shuffled array of id-s ready to be rendered
*/
function generatePuzzle(n) {
var pieces = ["blank"];
for (var i = 0; i < n - 1; i++) {
pieces.push(i);
}
return shuffleArray(pieces);
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
}
body {
font-family: "Lucida Grande", "Lucida Sans Unicode", Verdana, Helvetica, Arial, sans-serif;
font-size: 12px;
color: #000;
}
#formatContainer {
position: absolute;
top: 50px;
left: 500px;
}
#formatContainer label {
display: inline-block;
max-width: 100%;
margin-bottom: 5px;
}
#formatContainer select {
display: block;
width: 100%;
margin-top: 10px;
margin-bottom: 10px;
}
#formatContainer button {
display: inline-block;
width: 100%;
}
.piece {
width: 96px;
height: 96px;
margin: 1px;
float: left;
border: 1px solid black;
}
.slidingpuzzleContainer3x3,
.slidingpuzzleContainer3x4,
.slidingpuzzleContainer4x3,
.slidingpuzzleContainer4x4 {
position: absolute;
top: 50px;
left: 50px;
border: 10px solid black;
}
.slidingpuzzleContainer3x3 {
width: 300px;
height: 300px;
}
.slidingpuzzleContainer3x4 {
width: 300px;
height: 400px;
}
.slidingpuzzleContainer4x3 {
width: 400px;
height: 300px;
}
.slidingpuzzleContainer4x4 {
width: 400px;
height: 400px;
}
.congratulation {
margin: 10px;
}
}
<body onload="initGame();">
<div id="slidingpuzzleContainer"></div>
<form id="formatContainer">
<label for="format">select format:</label>
<select name="format" id="format" size="1">
<option value="" selected="true" disabled="true"></option>
<option value="3x3">Format 3 x 3</option>
<option value="3x4">Format 3 x 4</option>
<option value="4x3">Format 4 x 3</option>
<option value="4x4">Format 4 x 4</option>
</select>
<button type="submit" disabled="true">Play!</button>
</form>
</body>
Here we have the initGame() function that starts everything. When called it will create an initial state of the game (we have default size and state properties to care about there), add listeners on the controls and call render() function with the current state.
initGameControls() sets up a listener for clicks on the field that will 1) call movePiece() which will try to move clicked piece on the blank spot if the former is somewhere around, 2) check if after move game is finished with checkFinish(), 3) call render() with updated state.
Now render() is a pretty simple function: it just gets the state and updates the DOM on the page accordingly.
Utility function initFormatControl() handles clicks and updates on the form for field size selection, and when the 'Play!' button is pressed will generate initial order of the pieces on the field and call render() with new state.
The main benefit of this approach is that almost all functions are decoupled from one another: you can tweak logic for finding blank space around target piece, to allow, for example, to swap pieces with adjacent ids, and even then functions for rendering, initialization and click handling will stay the same.
$(document).on('click','.puzzlepiece', function(){
var count = 0;
var imgarray = [];
var test =[0,1,2,3,4,5,6,7,8,'blank']
$('#slidingpuzzleContainer img').each(function(i){
var imgalt = $(this).attr('alt');
imgarray[i] = imgalt;
count++;
});
var is_same = (imgarray.length == test.length) && imgarray.every(function(element, index) {
return element === array2[index];
});
console.log(is_same); ///it will true if two array is same
});
try this... this is for only 3*3.. you pass the parameter and makethe array value as dynamically..

Random number into div and then let delete divs in sequence. How?

So, i want to make game for my child. Have low experience in JS.
Scenario:
Have for example 4 square divs with blank bg. After refresh (or win) i want to:
Generate random numbers into div (1...4). And show them in them.
Then let player delete those divs by clicking on them, but in sequence how divs are numbered.
*For example after refresh divs have those numbers 2 3 1 4. So, user has to have rights to delete first div numbered 1 (2 3 _ 4) and so on.* If he clicks on 2 it get error , div stays in place, and user can try again delete right one.
It game for learning numbers. I have the begining.
Index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
</head>
<body>
<div class="grid">
<div id="Uleft"></div>
<div id="Uright"></div>
<div id="Dleft"></div>
<div id="Dright"></div>
</div>
<script>
$(".grid").children( "div" ).on("click", function(){
$(this).css("visibility", "hidden");
});
</script>
</body>
</html>
css.css
.grid {
margin: 0 auto;
width: 430px;
}
#Uleft, #Uright, #Dleft, #Dright {
border: 1px solid black;
width: 200px;
height: 200px;
margin: 5px;
}
#Uright {
float: right;
background-color: red;
}
#Uleft {
float: left;
background-color: blue;
}
#Dleft {
float: left;
background-color: green;
}
#Dright {
float: right;
background-color: yellow;
}
So, i guess i have use jQuery as well, but i dont know how to make it dynamic and different after refresh of page. Please help :)
http://jsfiddle.net/bNa8Z/
There are a few things you have to do. First you have to create a random array which you use sort and Math.random() to do then, you need insert the text in the squares. Find the min of the visible squares and then remove/alert depending if its the min value.
// sort by random
var rnd = [1,2,3,4].sort(function() {
return .5 - Math.random();
});
// map over each div in the grid
$('.grid div').each(function(ii, div) {
$(div).text(rnd[ii]); // set the text to the ii'th rnd
});
function minVisible() {
var min = 1e10; // a big number
$('.grid div').each(function(ii, div) {
// if not visible ignore
if ($(div).css('visibility') === "hidden" ){
return;
}
// if new min, store
var curFloatValue = parseFloat($(div).text());
console.log(curFloatValue);
if (curFloatValue < min) {
min = curFloatValue;
}
});
return min;
}
$(".grid").children( "div" ).on("click", function(){
var clickedFloatValue = parseFloat($(this).text());
if (clickedFloatValue == minVisible()) {
$(this).css("visibility", "hidden");
} else {
alert("sorry little tike");
}
});
Updated jsfiddle http://jsfiddle.net/bNa8Z/2/
Roughly this is what it would look like:
var selected = {};
$('.grid div').each(function(idx){
var is_done = false;
do{
var rand = Math.floor((Math.random()*4)+1);
if( selected[rand] == undefined ){
$(this).html(rand);
selected[rand] = 1;
is_done = true;
}
}while(!is_done);
});
alert("Start the game");
var clicked = [];
$('.grid').on('click', 'div.block', function(){
var num = $(this).html();
if( num == clicked.length + 1 ){
//alert(num + " is correct!");
clicked.push(num);
$(this).addClass("hide");
}else{
alert("Failed!");
}
if( clicked.length == 4 ){
alert("You Won!");
}
});
HTML:
<div class="grid">
<div class="block" id="Uleft"></div>
<div class="block" id="Uright"></div>
<div class="block" id="Dleft"></div>
<div class="block" id="Dright"></div>
</div>
Added CSS:
#Uleft, #Uright, #Dleft, #Dright {
position:absolute;
...
}
#Uright {
left:220px;
top:0px;
background-color: red;
}
#Uleft {
left:0px;
top:0px;
background-color: blue;
}
#Dleft {
left:0px;
top:220px;
background-color: green;
}
#Dright {
left:220px;
top:220px;
background-color: yellow;
}
.hide {
display: none;
}
See the working version at
JSFiddle
You will need to re-"run" the fiddle per game.
please try it. I think that It will help you.
var generated_random_number_sequesce = function(){
var number_array = [];
var number_string = '';
var is_true = true;
while(is_true){
var ran_num = Math.round(1 + Math.random()*3);
if(number_string.indexOf(ran_num) == -1 && ran_num < 5){
number_array[number_array.length] = ran_num;
number_string = number_string + ran_num;
if(number_array.length == 4){is_true = false;}
}
}
return number_array;
}
var set_number_on_divs = function(){
var number_array = generated_random_number_sequesce();
$(".grid").children().each(function(index, element){
$(this).attr('data-div_number' , number_array[index]);
});
}
set_number_on_divs()
var clicked = 0;
$(".grid").children( "div" ).on("click", function(){
clicked += 1;
var current_div_number = $(this).attr('data-div_number');
if( parseInt(current_div_number) == clicked){
$(this).css("visibility", "hidden");
} else{
clicked -= 1;
alert('error');
}
});

Categories