Add clicks when differents div are clicked - javascript

Im working on a project and i have basically some troubles with things for my website.
This one is a bit hard for me, i have some ideas but i dont know how to do them in my javascript code.
I have 98 divs (it's a calendar where you can select everyday differents hours to book slots).
There is a Summary (kinda same thing on commercial website) which i want that it says how many slots you selected. But the problem is that i have like I said 98div so i wanna do it in one function.
On the slots you want to book, you can click on it (it selects it) and if you click on it again it deselects it.
I want that you can select as many slots that you want, and the summary shows how many you selected then you can go to next step.
Here is my code if you guys have some ideas !
function x1(e) {
var target = e.target,
count = +target.dataset.count;
target.style.backgroundColor = count === 1 ? "#707070" : 'black';
target.dataset.count = count === 1 ? 0 : 1;
target.innerHTML = count === 1 ? '' : 'réserver';
target.classList.toggle('Resatxt');
target.classList.toggle('unselectable');
}
Actually this code is for the selection of the slots (it's going background black when you clicl on it, and then back to the normal color when you deselect it).
But i think i can do what i want with this.
I thinked about incrementing +1 when we click on the div but the problem that i dont know how to figure it out is when you deselect it you have to do -1 but im a bit lost.
I tried to be clear but ik that is not really.
If you guys have some ideas, go for it.
Thanks a lot

it's nice to see that your joining the programming community. I hope I understood you correctly and made a simple and minimal example to present you how can you achieve what you want. This is just an idea, don't take it too serious and write your own logic to handle the functionality!
const divs = 98;
const list = document.querySelector("#list");
const selectedList = document.querySelector("#selectedList");
let selected = [];
let elementsAdded = 1;
const onSelectDiv = (element) => {
const elementCopy = element.cloneNode(true);
elementCopy.id += "-copy";
selected = [
...selected,
{
id: elementsAdded,
elementId: element.id
}
];
elementsAdded += 1;
selectedList.appendChild(elementCopy);
};
const onClick = (e) => {
if (e.target.className.includes("selected")) {
e.target.classList.remove("selected");
elementsAdded -= 1;
const elementToDelete = selected.findIndex(
(x) => e.target.id === x.elementId
);
selectedList.removeChild(selectedList.childNodes[elementToDelete + 1]);
selected = selected.filter((x) => x.elementId !== e.target.id);
return;
}
onSelectDiv(e.target);
e.target.className += " selected";
};
for (let i = 0; i < divs; i++) {
const div = document.createElement("div");
div.innerHTML += i;
div.className += "div";
div.id = i;
div.addEventListener("click", function (event) {
onClick(event);
});
list.appendChild(div);
}
.view {
display: flex;
flex-direction: 'column';
}
#list {
display: flex;
width: 400px;
max-width: 500px;
flex-wrap: wrap;
}
.div {
padding: 5px;
background-color: black;
cursor: pointer;
color: white;
border-radius: 10px;
margin: 10px;
}
.selected {
background-color: red;
color: white;
}
<div class="view">
<div>
<p>Elements:</p>
<div id="list">
</div>
</div>
<div>
<p>Selected:</p>
<div id="selectedList">
</div>
</div>
</div>

Related

repeat putting input element randomly between user's text

I have a text element that is built when the user clicks a button. In the middle of that text, I added an input element.I want to make this process repeats seven times but it looks complicated. I actually made a lot of things but here are the important ones So, First I made an input element and a button when the user enter input and click the button what he wrote will be displayed in a h1 element with a random missing word Then,I made an input element in the that the missing word should've been in.What I want is that this to repeat this process seven times.
function myFunction() {
var x = document.getElementById("input").value;
x = x + " ";
var y = document.getElementById("inputed");
var a,b = "c";
const c=[];
const d=[];
var e;
var f = 0;
const array = [];
const z = x.length;
for (let index = 0; index < 7; index++) {
a= "c";
b= "c";
c.push(0);
d.push(0);
c[index] = 0;
d[index] = 0;
e = 1;
f = 0;
//Here the program will get a random space location and the space after it
while (a != " ") {
c[index] = Math.floor(Math.random() * x.length - 2);
a = x.charAt(c[index]);
}
d[index] = c[index];
//The variable d will be the same as c and will increase until its value corrspends to a space
while (b != " ") {
d[index]++;
b = x.charAt(d[index]);
}
//I want the y.innerHTML to write from the 0 to c[0] then display the input element then from d[0] //to c[1] and display the input element again and form d[1] to c[2] until 7
y.innerHTML = `${x.slice(
0,
c[0]
)}<input type="text" style="color: gray;border:2px solid;border-radius: 10px;outline: none;
font-size: x-large;height:40px;width: 100px;" >${x.slice(d[0], z)} `;
}
}
I had problems understanding perfectly your code so I couldn't answer trying to address the exact problems affecting your specific algorithm.
Anyway I made an attempt trying to understand your description and as far as I could get I tried to implement a demo beginning from a input text filled by the user and:
When the button PARSE SENTENCE gets clicked, the procedures parses the
input text splitting its content by white spaces to find out the
words.
Then it determines how many random words he wants to "remove" from
the string and at which index.
Then it creates a span element for each of those words and put all of them
in a separate array
Such spans, will have the word in their innerText, the default class
word and an added class that will be kept-word if that's a word not
to remove and removed-word otherwise. Plus they will keep track of that original word inside a data attribute called data-original
Those spans get appended to the #transformed element, and at this
stage, if the word belongs to the class .removed-word its
innerText gets emptied and its contenteditable attribute
activated.
In the end, after the parsing of the sentence, the exact spans code
will be shown in the <pre> element to give evidence of what's going
on
I know it's very far from what you have asked.. considering I didn't strictly stressed the algorithm aspect and mostly used shortcut like split, includes, contains and more importantly I totally changed your logics and used spans for words parsed and didn't use the input at all but contenteditable.
I sincerely hope it will anyway give some inspiration
function transform(){
const input = document.getElementById('input').value.trim();
const words = input.split(" ");
const nrOfWordsToReplace = Math.floor(Math.random() * words.length);
const indexesOfWordsToReplace
= Array.from({length: nrOfWordsToReplace}, () => {
return Math.floor(Math.random() * words.length);
});
//for each word in the input, create a span element to add in #transformed
//words expected to be kept will have their span with class .word.kept-word
//words expected to be removed will have their span with class .word.remove-word
let index = 0;
const outputWords = [];
for(word of words){
if( indexesOfWordsToReplace.includes(index) ){
const outputWord = createOutputWordElement(word, 'removed-word');
outputWords.push( outputWord );
}else{
const outputWord = createOutputWordElement(word, 'kept-word');
outputWords.push( outputWord );
}
index++;
}
const codeContainer = document.querySelector('pre');
codeContainer.innerHTML = '';
//clear its content appends those spans to #transform
const transformed = document.getElementById('transformed');
transformed.innerHTML = '';
for(outputWord of outputWords){
if (outputWord.classList.contains('removed-word')){
outputWord.innerText = '';
outputWord.contentEditable = true;
}
transformed.append(outputWord);
const code = document.createElement('code');
code.innerText = outputWord.outerHTML;
codeContainer.append(code);
}
}
//returns a span element having the word as content and classname among its classes
function createOutputWordElement(word, classname){
const outputWord = document.createElement('span');
outputWord.classList.add('word');
outputWord.classList.add(classname);
outputWord.dataset.original = word;
outputWord.innerText = word;
return outputWord;
}
body{
padding: 1rem;
}
*{
box-sizing: border-box;
}
button{
width: 100%;
margin-top: 1rem;
margin-bottom: 1rem;
padding: 1rem;
cursor: pointer;
text-transform: uppercase;
}
#input{
display: block;
width: 100%;
}
pre code{
display: block;
}
#transformed{
border: dashed 3px darkgray;
padding: 1rem;
}
.word{
border: solid 2px;
padding: .25rem;
margin-right: .50rem;
display: inline-block;
}
.word.kept-word{
border-color: darkgray;
}
.word.removed-word{
border-color: red;
cursor: pointer;
min-width: 2rem;
}
.
<input type="text" id="input">
<button type="button" onclick="transform();">Parse sentence</button>
<div id="transformed"></div>
<pre>
</pre>

progressbar html tag change

I'am working on progressbar that change the level when reaching some point.
The code.
I want to change the text under the progressbar when the progressbar reach 100 or above 90.
I could change it once but I want to go to next level, like this.
silver ==> gold ==> diamond ==> and more
const step = 5;
var content=document.getElementById('mylevel').innerHTML;
const updateProgress = () => {
const currentWidth = Number(document.getElementById("progressvalue").style.width.replace( "%", ""));
if (currentWidth>=100) {
return;
}
else {
document.getElementById("progressvalue").style.width = `${currentWidth+step}%`;
}
if (currentWidth > 90) {
document.getElementById("mylevel").textContent = "gold";
document.getElementById("progressvalue").style.width = "0%";
}
if (currentWidth > 90 && content == "gold") {
document.getElementById("mylevel").textContent = "diamond";
document.getElementById("progressvalue").style.width = "0%";
}
}
const restart = () => {
document.getElementById("progressvalue").style.width = "0%";
}
.progress {
background-color: #ededed;
width: 100%;
overflow: hidden;
}
#progressvalue {
height: 40px;
background-color: lightgreen;
width: 0%;
}
<div class="progress">
<div id="progressvalue"></div>
</div>
<p id="mylevel">silver</p>
<br />
<button type="button" onclick="updateProgress()">
Update Progress
</button>
<button type="button" onclick="restart()">
Restart
</button>
When the updateprogress is above 90 the silver change to gold, but I need to change again to diamond when the updateprogress is again above 90.
Am I putting the if condition in a wrong place, I tried many times.
I don't know what I'am missing and am new with JavaScript
I started the code but got help here to make it much better (80% of the code done by
teresaPap thanks)
Update
After closer inspection it is an issue of content not updating you need to put it inside updateProgress() or it will forever remain the initial value.
const step = 5;
const updateProgress = () => {
var content = document.getElementById('mylevel').innerHTML;
//the rest of the code
I do however recommend you to improve your if statements. You only need one if for this task.
A better solution
A better solution would be something like this:
Add a hidden value to keep your level progress
</div>
<p id="hiddenlevel">0</p>
<p id="mylevel">silver</p>
<br />
and css:
#hiddenlevel {
height: 0px;
visibility: hidden;
width: 0%;
}
now that you have a hidden value you can wrap up all future ifs in a single one.
const levels = ["silver", "gold", "diamond"]
var mylevel = Number(document.getElementById("hiddenlevel").innerHTML);
if(currentWidth > 90 && mylevel < levels.length){
document.getElementById("hiddenlevel").textContent = mylevel + 1;
document.getElementById("mylevel").textContent = levels[mylevel + 1];
document.getElementById("progressvalue").style.width = "0%";
}
and just like that you can just add a new level inside the levels array and it will be added without issues.
Update 2
Just noticed I made a mistake!
You don't need a hidden element for this: you might end up having to use hidden elements when using plugins, but it was completely unnecessary here :)
Updated code:
const step = 5;
var mylevel = 0;
const updateProgress = () => {
const currentWidth = Number(document.getElementById("progressvalue").style.width.replace( "%", ""));
if (currentWidth>=100) {
return;
}
else {
document.getElementById("progressvalue").style.width = `${currentWidth+step}%`;
}
const levels = ["silver", "gold", "diamond"];
if(currentWidth > 90 && mylevel < levels.length){
mylevel = mylevel + 1;
document.getElementById("mylevel").textContent = levels[mylevel];
document.getElementById("progressvalue").style.width = "0%";
}
}
const restart = () => {
document.getElementById("progressvalue").style.width = "0%";
}
.progress {
background-color: #ededed;
width: 100%;
overflow: hidden;
}
#progressvalue {
height: 40px;
background-color: lightgreen;
width: 0%;
}
<div class="progress">
<div id="progressvalue"></div>
</div>
<p id="mylevel">silver</p>
<br />
<button type="button" onclick="updateProgress()">
Update Progress
</button>
<button type="button" onclick="restart()">
Restart
</button>

How do I add class for time(clock)

I get date and clock.
var mydate = new Date();
var clock = tarih.getHours();
var minute = tarih.getMinutes();
And want this;
if (clock> 5) {
add this class, if have id "menu" = "menu_edit" (i dont know how can i do)
}
How can I do that?
If 'menu' is id of element:
document.querySelector('#menu').className += " menu_edit";
UPD:
According to your comment:
document.querySelector('.class1').className += ' class2';
Or if there are several elements:
var elems = document.querySelectorAll('.class1');
elems.forEach = [].forEach;
elems.forEach(function(el){
el.className += ' class2';
});
https://developer.mozilla.org/docs/Web/API/Document/querySelector - about function.
http://www.w3schools.com/cssref/css_selectors.asp - about selectors.
Maybe something like this. Please see the comments for an explanation.
checkout https://babeljs.io/ for info on compiling ES6 to ES5
const menu = document.querySelector('#menu')
const menuClasses = [
'menu--morning',
'menu--afternoon',
'menu--evening'
]
// helper function to toggle classes like a radio button
// this uses currying to lock in the classes and element, but
// allow us to change the active class dynamically
const toggleClasses = (classes, element) => clazz => {
element.classList.remove(...classes)
element.classList.add(clazz)
}
// create the toggle function and pass in the classes and the element
const toggleMenuClass = toggleClasses(menuClasses, menu)
// run a timer every n seconds
const timer = () => {
const date = new Date()
// I'm using seconds for the example as you will see the change
// but you should change this to hours
const second = date.getSeconds()
if (second < 20) {
toggleMenuClass('menu--morning')
}
else if (second < 40) {
toggleMenuClass('menu--afternoon')
}
else {
toggleMenuClass('menu--evening')
}
// just to show the current time for the example
menu.textContent = second
// call the timer function again after 500 milliseconds
setTimeout(timer, 500)
}
// init the timer on load
timer()
#menu {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
transition: 1s background;
font-size: 5em;
font-family: sans-serif;
color:#fff;
text-align: center;
line-height: 100vh;
}
#menu.menu--morning {
background: #AED6F1;
}
#menu.menu--afternoon {
background: #ABEBC6;
}
#menu.menu--evening {
background: #B95A75;
}
<div id="menu">clock</div>
Thanks everyone. I solved my problem with pHp.
Instead of adding class, i try take a different css page. Thanks for all things.
Have a nice day. :)
$clock = date('H');
if ($clock > 14) {
echo "<link rel='stylesheet' type='text/css' href='css/night.css'>";
}

Image gallery with max items and pagination with javascript

This is my situation:
I have a image gallery with 10 images visible on the main page and a pagination bar. The images came from a for loop iteration over a json file. That's no problem, they are just there ;-)
Something like:
for i=0; i <10; i++
create div with styles and images[i].image;
My question is:
I want to display the next 10 images on page 2, so when you click on page 2, it counts from 11 to 20.
I found the jQuery 'Jpaginate'-plugin...
Can i accomplish that with this plugin?
Could someone explain me in the way i have to thing with Vars, Counts, Objects??
Thanks and kind regards,
Mike
I have made you an example on how you can approach this. I'm not saying it is bugproof, but it's the concept that matters. You might find some inspiration and maybe reach your goal.
var imgSrc = "https://s-media-cache-ak0.pinimg.com/236x/36/a5/7b/36a57b0f0ab16e885fcc230addb695c2.jpg";
var json = [];
for (var i = 0; i < 36; i++)
json.push({
Title: "Title " + (i + 1),
Source: imgSrc
});
/*
Just for ease, I'm creating an array with 36 objects (3x3 gallery)
so 9 images per page
*/
var pageLimit = 9;
var page = 1;
showImages();
$("#btnPrevious").click(function() {
if (pageLimit <= 9) {
pageLimit = 9;
page = 1;
} else {
page--;
pageLimit -= 9;
}
showImages();
});
$("#btnNext").click(function() {
if (pageLimit >= json.length) {
pageLimit = json.length;
} else {
page++;
pageLimit += 9;
}
showImages();
});
function showImages() {
$(".images").empty();
for (var i = pageLimit - 9; i < pageLimit; i++) {
var template = $("<div></div>").addClass("template");
var img = $("<img>");
img.attr("src", json[i].Source);
img.attr("alt", json[i].Title);
var br = $("<br/>");
var title = $("<span></span>").html(json[i].Title);
template.append(img).append(br).append(title);
$(".images").append(template);
}
$("#page").html("Page " + page);
}
.gallery {
width: 100%;
height: 500px;
border: 1px solid black;
background-color: lightgray;
text-align: center;
}
.images {
width: 90%;
margin: 0 auto;
height: 100%;
margin-bottom: 15px;
}
img {
height: auto;
width: 33%;
margin: 20px 5px;
}
.template {
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gallery">
<div class="images"></div>
<button id="btnPrevious">
< Previous
</button>
<span id="page"></span>
<button id="btnNext">
> Next
</button>
</div>
Don't mind the CSS, because I suck at that (lol). It was based on the space I had on jsFiddle, but looking at it now (on full page or just the area the snippet provides) it looks awful. If a CSS guru could fix this .. Question in a question?
You can create your own pagination plugin.
You must store current page somewhere and modify your factory.
Something like: for i=current_page * count_per_page; i < count_per_page * (current_page + 1); i++ create div with styles and images[i].image;

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..

Categories